sauerbraten-0.0.20130203.dfsg/0000755000175000017500000000000012267567260015412 5ustar vincentvincentsauerbraten-0.0.20130203.dfsg/readme_source.txt0000644000175000017500000000673611743256100020766 0ustar vincentvincentSauerbraten source code license, usage, and documentation. You may use the Sauerbraten source code if you abide by the ZLIB license http://www.opensource.org/licenses/zlib-license.php (very similar to the BSD license): LICENSE ======= Sauerbraten game engine source code, any release. Copyright (C) 2001-2012 Wouter van Oortmerssen, Lee Salzman, Mike Dysart, Robert Pointon, and Quinton Reeves 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. LICENSE NOTES ============= The license covers the source code found in the "src" directory of this archive as well as the .cfg files under the "data" directory. The included ENet network library which Sauerbraten uses is covered by an MIT-style license, which is however compatible with the above license for all practical purposes. Game media included in the game (maps, textures, sounds, models etc.) are NOT covered by this license, and may have individual copyrights and distribution restrictions (see individual readmes). USAGE ===== Compiling the sources should be straight forward. Unix users need to make sure to have the development version of all libs installed (OpenGL, SDL, SDL_mixer, SDL_image, zlib). The included Makefile can be used to build. Windows users can use the included Visual Studio project files in the vcpp directory, which references the lib/include directories for the external libraries and should thus be self contained. Release mode builds will place executables in the bin dir ready for testing and distribution. An alternative to Visual Studio for Windows is MinGW/MSYS, which can be compiled using the provided Makefile. Another alternative for Windows is to compile under Code::Blocks with the provided vcpp/sauerbraten.cbp project file. The Sauerbraten sources are very small, compact, and non-redundant, so anyone wishing to modify the source code should be able to gain an overview of Sauerbraten's inner workings by simply reading through the source code in its entirety. Small amounts of comments should guide you through the more tricky sections. When reading the source code and trying to understand Sauerbaten's internal design, keep in mind the goal of Cube: minimalism. I wanted to create a very complete game / game engine with absolutely minimal means, and made a sport out of it keeping the implementation small and simple. Sauerbraten is not a commercial product, it is merely the author's idea of a fun little programming project. AUTHORS ====== Wouter "Aardappel" van Oortmerssen http://strlen.com Lee "eihrul" Salzman http://lee.fov120.com Mike "Gilt" Dysart Robert "baby-rabbit" Pointon http://www.fernlightning.com Quinton "Quin" Reeves http://www.redeclipse.net For additional authors/contributors, see the Sauerbraten binary distribution readme. sauerbraten-0.0.20130203.dfsg/Makefile0000644000175000017500000005662412017053537017055 0ustar vincentvincentCXXFLAGS= -O3 -fomit-frame-pointer override CXXFLAGS+= -Wall -fsigned-char -fno-exceptions -fno-rtti PLATFORM= $(shell uname -s) PLATFORM_PREFIX= native INCLUDES= -Ishared -Iengine -Ifpsgame -Ienet/include STRIP= ifeq (,$(findstring -g,$(CXXFLAGS))) ifeq (,$(findstring -pg,$(CXXFLAGS))) STRIP=strip endif endif MV=mv ifneq (,$(findstring MINGW,$(PLATFORM))) WINDRES= windres ifneq (,$(findstring 64,$(PLATFORM))) WINLIB=lib64 WINBIN=../bin64 override CXX+= -m64 override WINDRES+= -F pe-x86-64 else WINLIB=lib WINBIN=../bin override CXX+= -m32 override WINDRES+= -F pe-i386 endif CLIENT_INCLUDES= $(INCLUDES) -Iinclude ifneq (,$(findstring TDM,$(PLATFORM))) STD_LIBS= else STD_LIBS= -static-libgcc -static-libstdc++ endif CLIENT_LIBS= -mwindows $(STD_LIBS) -L$(WINBIN) -L$(WINLIB) -lSDL -lSDL_image -lSDL_mixer -lzlib1 -lopengl32 -lenet -lws2_32 -lwinmm else CLIENT_INCLUDES= $(INCLUDES) -I/usr/X11R6/include `sdl-config --cflags` CLIENT_LIBS= -Lenet/.libs -lenet -L/usr/X11R6/lib -lX11 `sdl-config --libs` -lSDL_image -lSDL_mixer -lz -lGL endif ifeq ($(PLATFORM),Linux) CLIENT_LIBS+= -lrt endif CLIENT_OBJS= \ shared/crypto.o \ shared/geom.o \ shared/stream.o \ shared/tools.o \ shared/zip.o \ engine/3dgui.o \ engine/bih.o \ engine/blend.o \ engine/blob.o \ engine/client.o \ engine/command.o \ engine/console.o \ engine/cubeloader.o \ engine/decal.o \ engine/dynlight.o \ engine/glare.o \ engine/grass.o \ engine/lightmap.o \ engine/main.o \ engine/material.o \ engine/menus.o \ engine/movie.o \ engine/normal.o \ engine/octa.o \ engine/octaedit.o \ engine/octarender.o \ engine/physics.o \ engine/pvs.o \ engine/rendergl.o \ engine/rendermodel.o \ engine/renderparticles.o \ engine/rendersky.o \ engine/rendertext.o \ engine/renderva.o \ engine/server.o \ engine/serverbrowser.o \ engine/shader.o \ engine/shadowmap.o \ engine/sound.o \ engine/texture.o \ engine/water.o \ engine/world.o \ engine/worldio.o \ fpsgame/ai.o \ fpsgame/client.o \ fpsgame/entities.o \ fpsgame/fps.o \ fpsgame/monster.o \ fpsgame/movable.o \ fpsgame/render.o \ fpsgame/scoreboard.o \ fpsgame/server.o \ fpsgame/waypoint.o \ fpsgame/weapon.o CLIENT_PCH= shared/cube.h.gch engine/engine.h.gch fpsgame/game.h.gch ifneq (,$(findstring MINGW,$(PLATFORM))) SERVER_INCLUDES= -DSTANDALONE $(INCLUDES) -Iinclude SERVER_LIBS= -mwindows $(STD_LIBS) -L$(WINBIN) -L$(WINLIB) -lzlib1 -lenet -lws2_32 -lwinmm MASTER_LIBS= $(STD_LIBS) -L$(WINBIN) -L$(WINLIB) -lzlib1 -lenet -lws2_32 -lwinmm else SERVER_INCLUDES= -DSTANDALONE $(INCLUDES) SERVER_LIBS= -Lenet/.libs -lenet -lz MASTER_LIBS= $(SERVER_LIBS) endif SERVER_OBJS= \ shared/crypto-standalone.o \ shared/stream-standalone.o \ shared/tools-standalone.o \ engine/command-standalone.o \ engine/server-standalone.o \ engine/worldio-standalone.o \ fpsgame/entities-standalone.o \ fpsgame/server-standalone.o MASTER_OBJS= \ shared/crypto-standalone.o \ shared/stream-standalone.o \ shared/tools-standalone.o \ engine/command-standalone.o \ engine/master-standalone.o ifeq ($(PLATFORM),SunOS) CLIENT_LIBS+= -lsocket -lnsl -lX11 SERVER_LIBS+= -lsocket -lnsl endif default: all all: client server enet/Makefile: cd enet; ./configure --enable-shared=no --enable-static=yes libenet: enet/Makefile $(MAKE) -C enet/ all clean-enet: enet/Makefile $(MAKE) -C enet/ clean clean: -$(RM) $(CLIENT_PCH) $(CLIENT_OBJS) $(SERVER_OBJS) $(MASTER_OBJS) sauer_client sauer_server sauer_master %.h.gch: %.h $(CXX) $(CXXFLAGS) -o $(subst .h.gch,.tmp.h.gch,$@) $(subst .h.gch,.h,$@) $(MV) $(subst .h.gch,.tmp.h.gch,$@) $@ %-standalone.o: %.cpp $(CXX) $(CXXFLAGS) -c -o $@ $(subst -standalone.o,.cpp,$@) $(CLIENT_OBJS): CXXFLAGS += $(CLIENT_INCLUDES) $(filter shared/%,$(CLIENT_OBJS)): $(filter shared/%,$(CLIENT_PCH)) $(filter engine/%,$(CLIENT_OBJS)): $(filter engine/%,$(CLIENT_PCH)) $(filter fpsgame/%,$(CLIENT_OBJS)): $(filter fpsgame/%,$(CLIENT_PCH)) $(SERVER_OBJS): CXXFLAGS += $(SERVER_INCLUDES) $(filter-out $(SERVER_OBJS),$(MASTER_OBJS)): CXXFLAGS += $(SERVER_INCLUDES) ifneq (,$(findstring MINGW,$(PLATFORM))) client: $(CLIENT_OBJS) $(WINDRES) -I vcpp -i vcpp/mingw.rc -J rc -o vcpp/mingw.res -O coff $(CXX) $(CXXFLAGS) -o $(WINBIN)/sauerbraten.exe vcpp/mingw.res $(CLIENT_OBJS) $(CLIENT_LIBS) server: $(SERVER_OBJS) $(WINDRES) -I vcpp -i vcpp/mingw.rc -J rc -o vcpp/mingw.res -O coff $(CXX) $(CXXFLAGS) -o $(WINBIN)/sauer_server.exe vcpp/mingw.res $(SERVER_OBJS) $(SERVER_LIBS) master: $(MASTER_OBJS) $(CXX) $(CXXFLAGS) -o $(WINBIN)/sauer_master.exe $(MASTER_OBJS) $(MASTER_LIBS) install: all else client: libenet $(CLIENT_OBJS) $(CXX) $(CXXFLAGS) -o sauer_client $(CLIENT_OBJS) $(CLIENT_LIBS) server: libenet $(SERVER_OBJS) $(CXX) $(CXXFLAGS) -o sauer_server $(SERVER_OBJS) $(SERVER_LIBS) master: libenet $(MASTER_OBJS) $(CXX) $(CXXFLAGS) -o sauer_master $(MASTER_OBJS) $(MASTER_LIBS) shared/cube2font.o: shared/cube2font.c $(CXX) $(CXXFLAGS) -c -o $@ $< `freetype-config --cflags` cube2font: shared/cube2font.o $(CXX) $(CXXFLAGS) -o cube2font shared/cube2font.o `freetype-config --libs` -lz install: all cp sauer_client ../bin_unix/$(PLATFORM_PREFIX)_client cp sauer_server ../bin_unix/$(PLATFORM_PREFIX)_server ifneq (,$(STRIP)) $(STRIP) ../bin_unix/$(PLATFORM_PREFIX)_client $(STRIP) ../bin_unix/$(PLATFORM_PREFIX)_server endif endif depend: makedepend -Y -Ishared -Iengine -Ifpsgame $(subst .o,.cpp,$(CLIENT_OBJS)) makedepend -a -o.h.gch -Y -Ishared -Iengine -Ifpsgame $(subst .h.gch,.h,$(CLIENT_PCH)) makedepend -a -o-standalone.o -Y -DSTANDALONE -Ishared -Iengine -Ifpsgame $(subst -standalone.o,.cpp,$(SERVER_OBJS)) makedepend -a -o-standalone.o -Y -DSTANDALONE -Ishared -Iengine -Ifpsgame $(subst -standalone.o,.cpp,$(filter-out $(SERVER_OBJS), $(MASTER_OBJS))) engine/engine.h.gch: shared/cube.h.gch fpsgame/game.h.gch: shared/cube.h.gch # DO NOT DELETE shared/crypto.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h shared/crypto.o: shared/command.h shared/iengine.h shared/igame.h shared/geom.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h shared/geom.o: shared/command.h shared/iengine.h shared/igame.h shared/stream.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h shared/stream.o: shared/command.h shared/iengine.h shared/igame.h shared/tools.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h shared/tools.o: shared/command.h shared/iengine.h shared/igame.h shared/zip.o: shared/cube.h shared/tools.h shared/geom.h shared/ents.h shared/zip.o: shared/command.h shared/iengine.h shared/igame.h engine/3dgui.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/3dgui.o: shared/ents.h shared/command.h shared/iengine.h engine/3dgui.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/3dgui.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/3dgui.o: engine/textedit.h engine/bih.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/bih.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h engine/bih.o: engine/world.h engine/octa.h engine/lightmap.h engine/bih.h engine/bih.o: engine/texture.h engine/model.h engine/varray.h engine/blend.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/blend.o: shared/ents.h shared/command.h shared/iengine.h engine/blend.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/blend.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/blob.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/blob.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h engine/blob.o: engine/world.h engine/octa.h engine/lightmap.h engine/bih.h engine/blob.o: engine/texture.h engine/model.h engine/varray.h engine/client.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/client.o: shared/ents.h shared/command.h shared/iengine.h engine/client.o: shared/igame.h engine/world.h engine/octa.h engine/client.o: engine/lightmap.h engine/bih.h engine/texture.h engine/client.o: engine/model.h engine/varray.h engine/command.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/command.o: shared/ents.h shared/command.h shared/iengine.h engine/command.o: shared/igame.h engine/world.h engine/octa.h engine/command.o: engine/lightmap.h engine/bih.h engine/texture.h engine/command.o: engine/model.h engine/varray.h engine/console.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/console.o: shared/ents.h shared/command.h shared/iengine.h engine/console.o: shared/igame.h engine/world.h engine/octa.h engine/console.o: engine/lightmap.h engine/bih.h engine/texture.h engine/console.o: engine/model.h engine/varray.h engine/cubeloader.o: engine/engine.h shared/cube.h shared/tools.h engine/cubeloader.o: shared/geom.h shared/ents.h shared/command.h engine/cubeloader.o: shared/iengine.h shared/igame.h engine/world.h engine/cubeloader.o: engine/octa.h engine/lightmap.h engine/bih.h engine/cubeloader.o: engine/texture.h engine/model.h engine/varray.h engine/decal.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/decal.o: shared/ents.h shared/command.h shared/iengine.h engine/decal.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/decal.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/dynlight.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/dynlight.o: shared/ents.h shared/command.h shared/iengine.h engine/dynlight.o: shared/igame.h engine/world.h engine/octa.h engine/dynlight.o: engine/lightmap.h engine/bih.h engine/texture.h engine/dynlight.o: engine/model.h engine/varray.h engine/glare.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/glare.o: shared/ents.h shared/command.h shared/iengine.h engine/glare.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/glare.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/glare.o: engine/rendertarget.h engine/grass.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/grass.o: shared/ents.h shared/command.h shared/iengine.h engine/grass.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/grass.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/lightmap.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/lightmap.o: shared/ents.h shared/command.h shared/iengine.h engine/lightmap.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.o: engine/lightmap.h engine/bih.h engine/texture.h engine/lightmap.o: engine/model.h engine/varray.h engine/main.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/main.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h engine/main.o: engine/world.h engine/octa.h engine/lightmap.h engine/bih.h engine/main.o: engine/texture.h engine/model.h engine/varray.h engine/material.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/material.o: shared/ents.h shared/command.h shared/iengine.h engine/material.o: shared/igame.h engine/world.h engine/octa.h engine/material.o: engine/lightmap.h engine/bih.h engine/texture.h engine/material.o: engine/model.h engine/varray.h engine/menus.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/menus.o: shared/ents.h shared/command.h shared/iengine.h engine/menus.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/menus.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/movie.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/movie.o: shared/ents.h shared/command.h shared/iengine.h engine/movie.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/movie.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/normal.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/normal.o: shared/ents.h shared/command.h shared/iengine.h engine/normal.o: shared/igame.h engine/world.h engine/octa.h engine/normal.o: engine/lightmap.h engine/bih.h engine/texture.h engine/normal.o: engine/model.h engine/varray.h engine/octa.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/octa.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h engine/octa.o: engine/world.h engine/octa.h engine/lightmap.h engine/bih.h engine/octa.o: engine/texture.h engine/model.h engine/varray.h engine/octaedit.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/octaedit.o: shared/ents.h shared/command.h shared/iengine.h engine/octaedit.o: shared/igame.h engine/world.h engine/octa.h engine/octaedit.o: engine/lightmap.h engine/bih.h engine/texture.h engine/octaedit.o: engine/model.h engine/varray.h engine/octarender.o: engine/engine.h shared/cube.h shared/tools.h engine/octarender.o: shared/geom.h shared/ents.h shared/command.h engine/octarender.o: shared/iengine.h shared/igame.h engine/world.h engine/octarender.o: engine/octa.h engine/lightmap.h engine/bih.h engine/octarender.o: engine/texture.h engine/model.h engine/varray.h engine/physics.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/physics.o: shared/ents.h shared/command.h shared/iengine.h engine/physics.o: shared/igame.h engine/world.h engine/octa.h engine/physics.o: engine/lightmap.h engine/bih.h engine/texture.h engine/physics.o: engine/model.h engine/varray.h engine/mpr.h engine/pvs.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/pvs.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h engine/pvs.o: engine/world.h engine/octa.h engine/lightmap.h engine/bih.h engine/pvs.o: engine/texture.h engine/model.h engine/varray.h engine/rendergl.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/rendergl.o: shared/ents.h shared/command.h shared/iengine.h engine/rendergl.o: shared/igame.h engine/world.h engine/octa.h engine/rendergl.o: engine/lightmap.h engine/bih.h engine/texture.h engine/rendergl.o: engine/model.h engine/varray.h engine/rendermodel.o: engine/engine.h shared/cube.h shared/tools.h engine/rendermodel.o: shared/geom.h shared/ents.h shared/command.h engine/rendermodel.o: shared/iengine.h shared/igame.h engine/world.h engine/rendermodel.o: engine/octa.h engine/lightmap.h engine/bih.h engine/rendermodel.o: engine/texture.h engine/model.h engine/varray.h engine/rendermodel.o: engine/ragdoll.h engine/animmodel.h engine/vertmodel.h engine/rendermodel.o: engine/skelmodel.h engine/md2.h engine/md3.h engine/rendermodel.o: engine/md5.h engine/obj.h engine/smd.h engine/iqm.h engine/renderparticles.o: engine/engine.h shared/cube.h shared/tools.h engine/renderparticles.o: shared/geom.h shared/ents.h shared/command.h engine/renderparticles.o: shared/iengine.h shared/igame.h engine/world.h engine/renderparticles.o: engine/octa.h engine/lightmap.h engine/bih.h engine/renderparticles.o: engine/texture.h engine/model.h engine/varray.h engine/renderparticles.o: engine/rendertarget.h engine/depthfx.h engine/renderparticles.o: engine/explosion.h engine/lensflare.h engine/renderparticles.o: engine/lightning.h engine/rendersky.o: engine/engine.h shared/cube.h shared/tools.h engine/rendersky.o: shared/geom.h shared/ents.h shared/command.h engine/rendersky.o: shared/iengine.h shared/igame.h engine/world.h engine/rendersky.o: engine/octa.h engine/lightmap.h engine/bih.h engine/rendersky.o: engine/texture.h engine/model.h engine/varray.h engine/rendertext.o: engine/engine.h shared/cube.h shared/tools.h engine/rendertext.o: shared/geom.h shared/ents.h shared/command.h engine/rendertext.o: shared/iengine.h shared/igame.h engine/world.h engine/rendertext.o: engine/octa.h engine/lightmap.h engine/bih.h engine/rendertext.o: engine/texture.h engine/model.h engine/varray.h engine/renderva.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/renderva.o: shared/ents.h shared/command.h shared/iengine.h engine/renderva.o: shared/igame.h engine/world.h engine/octa.h engine/renderva.o: engine/lightmap.h engine/bih.h engine/texture.h engine/renderva.o: engine/model.h engine/varray.h engine/server.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/server.o: shared/ents.h shared/command.h shared/iengine.h engine/server.o: shared/igame.h engine/world.h engine/octa.h engine/server.o: engine/lightmap.h engine/bih.h engine/texture.h engine/server.o: engine/model.h engine/varray.h engine/serverbrowser.o: engine/engine.h shared/cube.h shared/tools.h engine/serverbrowser.o: shared/geom.h shared/ents.h shared/command.h engine/serverbrowser.o: shared/iengine.h shared/igame.h engine/world.h engine/serverbrowser.o: engine/octa.h engine/lightmap.h engine/bih.h engine/serverbrowser.o: engine/texture.h engine/model.h engine/varray.h engine/shader.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/shader.o: shared/ents.h shared/command.h shared/iengine.h engine/shader.o: shared/igame.h engine/world.h engine/octa.h engine/shader.o: engine/lightmap.h engine/bih.h engine/texture.h engine/shader.o: engine/model.h engine/varray.h engine/shadowmap.o: engine/engine.h shared/cube.h shared/tools.h engine/shadowmap.o: shared/geom.h shared/ents.h shared/command.h engine/shadowmap.o: shared/iengine.h shared/igame.h engine/world.h engine/shadowmap.o: engine/octa.h engine/lightmap.h engine/bih.h engine/shadowmap.o: engine/texture.h engine/model.h engine/varray.h engine/shadowmap.o: engine/rendertarget.h engine/sound.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/sound.o: shared/ents.h shared/command.h shared/iengine.h engine/sound.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/sound.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/texture.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/texture.o: shared/ents.h shared/command.h shared/iengine.h engine/texture.o: shared/igame.h engine/world.h engine/octa.h engine/texture.o: engine/lightmap.h engine/bih.h engine/texture.h engine/texture.o: engine/model.h engine/varray.h engine/scale.h engine/water.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/water.o: shared/ents.h shared/command.h shared/iengine.h engine/water.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/water.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/world.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/world.o: shared/ents.h shared/command.h shared/iengine.h engine/world.o: shared/igame.h engine/world.h engine/octa.h engine/lightmap.h engine/world.o: engine/bih.h engine/texture.h engine/model.h engine/varray.h engine/worldio.o: engine/engine.h shared/cube.h shared/tools.h shared/geom.h engine/worldio.o: shared/ents.h shared/command.h shared/iengine.h engine/worldio.o: shared/igame.h engine/world.h engine/octa.h engine/worldio.o: engine/lightmap.h engine/bih.h engine/texture.h engine/worldio.o: engine/model.h engine/varray.h fpsgame/ai.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/ai.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h fpsgame/ai.o: fpsgame/ai.h fpsgame/client.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/client.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/client.o: shared/igame.h fpsgame/ai.h fpsgame/capture.h fpsgame/ctf.h fpsgame/client.o: fpsgame/collect.h fpsgame/entities.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/entities.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/entities.o: shared/igame.h fpsgame/ai.h fpsgame/fps.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/fps.o: shared/ents.h shared/command.h shared/iengine.h shared/igame.h fpsgame/fps.o: fpsgame/ai.h fpsgame/monster.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/monster.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/monster.o: shared/igame.h fpsgame/ai.h fpsgame/movable.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/movable.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/movable.o: shared/igame.h fpsgame/ai.h fpsgame/render.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/render.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/render.o: shared/igame.h fpsgame/ai.h fpsgame/scoreboard.o: fpsgame/game.h shared/cube.h shared/tools.h fpsgame/scoreboard.o: shared/geom.h shared/ents.h shared/command.h fpsgame/scoreboard.o: shared/iengine.h shared/igame.h fpsgame/ai.h fpsgame/server.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/server.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/server.o: shared/igame.h fpsgame/ai.h fpsgame/capture.h fpsgame/ctf.h fpsgame/server.o: fpsgame/collect.h fpsgame/extinfo.h fpsgame/aiman.h fpsgame/waypoint.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/waypoint.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/waypoint.o: shared/igame.h fpsgame/ai.h fpsgame/weapon.o: fpsgame/game.h shared/cube.h shared/tools.h shared/geom.h fpsgame/weapon.o: shared/ents.h shared/command.h shared/iengine.h fpsgame/weapon.o: shared/igame.h fpsgame/ai.h shared/cube.h.gch: shared/tools.h shared/geom.h shared/ents.h shared/cube.h.gch: shared/command.h shared/iengine.h shared/igame.h engine/engine.h.gch: shared/cube.h shared/tools.h shared/geom.h shared/ents.h engine/engine.h.gch: shared/command.h shared/iengine.h shared/igame.h engine/engine.h.gch: engine/world.h engine/octa.h engine/lightmap.h engine/engine.h.gch: engine/bih.h engine/texture.h engine/model.h engine/engine.h.gch: engine/varray.h fpsgame/game.h.gch: shared/cube.h shared/tools.h shared/geom.h shared/ents.h fpsgame/game.h.gch: shared/command.h shared/iengine.h shared/igame.h fpsgame/game.h.gch: fpsgame/ai.h shared/crypto-standalone.o: shared/cube.h shared/tools.h shared/geom.h shared/crypto-standalone.o: shared/ents.h shared/command.h shared/iengine.h shared/crypto-standalone.o: shared/igame.h shared/stream-standalone.o: shared/cube.h shared/tools.h shared/geom.h shared/stream-standalone.o: shared/ents.h shared/command.h shared/iengine.h shared/stream-standalone.o: shared/igame.h shared/tools-standalone.o: shared/cube.h shared/tools.h shared/geom.h shared/tools-standalone.o: shared/ents.h shared/command.h shared/iengine.h shared/tools-standalone.o: shared/igame.h engine/command-standalone.o: engine/engine.h shared/cube.h shared/tools.h engine/command-standalone.o: shared/geom.h shared/ents.h shared/command.h engine/command-standalone.o: shared/iengine.h shared/igame.h engine/world.h engine/server-standalone.o: engine/engine.h shared/cube.h shared/tools.h engine/server-standalone.o: shared/geom.h shared/ents.h shared/command.h engine/server-standalone.o: shared/iengine.h shared/igame.h engine/world.h engine/worldio-standalone.o: engine/engine.h shared/cube.h shared/tools.h engine/worldio-standalone.o: shared/geom.h shared/ents.h shared/command.h engine/worldio-standalone.o: shared/iengine.h shared/igame.h engine/world.h fpsgame/entities-standalone.o: fpsgame/game.h shared/cube.h shared/tools.h fpsgame/entities-standalone.o: shared/geom.h shared/ents.h shared/command.h fpsgame/entities-standalone.o: shared/iengine.h shared/igame.h fpsgame/ai.h fpsgame/server-standalone.o: fpsgame/game.h shared/cube.h shared/tools.h fpsgame/server-standalone.o: shared/geom.h shared/ents.h shared/command.h fpsgame/server-standalone.o: shared/iengine.h shared/igame.h fpsgame/ai.h fpsgame/server-standalone.o: fpsgame/capture.h fpsgame/ctf.h fpsgame/server-standalone.o: fpsgame/collect.h fpsgame/extinfo.h fpsgame/server-standalone.o: fpsgame/aiman.h engine/master-standalone.o: shared/cube.h shared/tools.h shared/geom.h engine/master-standalone.o: shared/ents.h shared/command.h shared/iengine.h engine/master-standalone.o: shared/igame.h sauerbraten-0.0.20130203.dfsg/shared/0000755000175000017500000000000012100771036016640 5ustar vincentvincentsauerbraten-0.0.20130203.dfsg/shared/ents.h0000644000175000017500000001606511701563241017775 0ustar vincentvincent// this file defines static map entities ("entity") and dynamic entities (players/monsters, "dynent") // the gamecode extends these types to add game specific functionality // ET_*: the only static entity types dictated by the engine... rest are gamecode dependent enum { ET_EMPTY=0, ET_LIGHT, ET_MAPMODEL, ET_PLAYERSTART, ET_ENVMAP, ET_PARTICLES, ET_SOUND, ET_SPOTLIGHT, ET_GAMESPECIFIC }; struct entity // persistent map entity { vec o; // position short attr1, attr2, attr3, attr4, attr5; uchar type; // type is one of the above uchar reserved; }; struct entitylight { vec color, dir; int millis; entitylight() : color(1, 1, 1), dir(0, 0, 1), millis(-1) {} }; struct extentity : entity // part of the entity that doesn't get saved to disk { enum { F_NOVIS = 1<<0, F_NOSHADOW = 1<<1, F_NOCOLLIDE = 1<<2, F_ANIM = 1<<3 }; uchar spawned, inoctanode, visible, flags; // the only dynamic state of a map entity entitylight light; extentity *attached; extentity() : visible(false), flags(0), attached(NULL) {} }; #define MAXENTS 10000 //extern vector ents; // map entities enum { CS_ALIVE = 0, CS_DEAD, CS_SPAWNING, CS_LAGGED, CS_EDITING, CS_SPECTATOR }; enum { PHYS_FLOAT = 0, PHYS_FALL, PHYS_SLIDE, PHYS_SLOPE, PHYS_FLOOR, PHYS_STEP_UP, PHYS_STEP_DOWN, PHYS_BOUNCE }; enum { ENT_PLAYER = 0, ENT_AI, ENT_INANIMATE, ENT_CAMERA, ENT_BOUNCE }; enum { COLLIDE_AABB = 0, COLLIDE_OBB, COLLIDE_ELLIPSE }; struct physent // base entity type, can be affected by physics { vec o, vel, falling; // origin, velocity vec deltapos, newpos; // movement interpolation float yaw, pitch, roll; float maxspeed; // cubes per second, 100 for player int timeinair; float radius, eyeheight, aboveeye; // bounding box size float xradius, yradius, zmargin; vec floor; // the normal of floor the dynent is on int inwater; bool jumping; char move, strafe; uchar physstate; // one of PHYS_* above uchar state, editstate; // one of CS_* above uchar type; // one of ENT_* above uchar collidetype; // one of COLLIDE_* above bool blocked; // used by physics to signal ai physent() : o(0, 0, 0), deltapos(0, 0, 0), newpos(0, 0, 0), yaw(0), pitch(0), roll(0), maxspeed(100), radius(4.1f), eyeheight(14), aboveeye(1), xradius(4.1f), yradius(4.1f), zmargin(0), state(CS_ALIVE), editstate(CS_ALIVE), type(ENT_PLAYER), collidetype(COLLIDE_ELLIPSE), blocked(false) { reset(); } void resetinterp() { newpos = o; deltapos = vec(0, 0, 0); } void reset() { inwater = 0; timeinair = 0; strafe = move = 0; physstate = PHYS_FALL; vel = falling = vec(0, 0, 0); floor = vec(0, 0, 1); } vec feetpos(float offset = 0) const { return vec(o).add(vec(0, 0, offset - eyeheight)); } vec headpos(float offset = 0) const { return vec(o).add(vec(0, 0, offset)); } bool maymove() const { return timeinair || physstate < PHYS_FLOOR || vel.squaredlen() > 1e-4f || deltapos.squaredlen() > 1e-4f; } }; enum { ANIM_DEAD = 0, ANIM_DYING, ANIM_IDLE, ANIM_FORWARD, ANIM_BACKWARD, ANIM_LEFT, ANIM_RIGHT, ANIM_HOLD1, ANIM_HOLD2, ANIM_HOLD3, ANIM_HOLD4, ANIM_HOLD5, ANIM_HOLD6, ANIM_HOLD7, ANIM_ATTACK1, ANIM_ATTACK2, ANIM_ATTACK3, ANIM_ATTACK4, ANIM_ATTACK5, ANIM_ATTACK6, ANIM_ATTACK7, ANIM_PAIN, ANIM_JUMP, ANIM_SINK, ANIM_SWIM, ANIM_EDIT, ANIM_LAG, ANIM_TAUNT, ANIM_WIN, ANIM_LOSE, ANIM_GUN_IDLE, ANIM_GUN_SHOOT, ANIM_VWEP_IDLE, ANIM_VWEP_SHOOT, ANIM_SHIELD, ANIM_POWERUP, ANIM_MAPMODEL, ANIM_TRIGGER, NUMANIMS }; static const char * const animnames[] = { "dead", "dying", "idle", "forward", "backward", "left", "right", "hold 1", "hold 2", "hold 3", "hold 4", "hold 5", "hold 6", "hold 7", "attack 1", "attack 2", "attack 3", "attack 4", "attack 5", "attack 6", "attack 7", "pain", "jump", "sink", "swim", "edit", "lag", "taunt", "win", "lose", "gun idle", "gun shoot", "vwep idle", "vwep shoot", "shield", "powerup", "mapmodel", "trigger" }; #define ANIM_ALL 0x7F #define ANIM_INDEX 0x7F #define ANIM_LOOP (1<<7) #define ANIM_START (1<<8) #define ANIM_END (1<<9) #define ANIM_REVERSE (1<<10) #define ANIM_CLAMP (ANIM_START|ANIM_END) #define ANIM_DIR 0x780 #define ANIM_SECONDARY 11 #define ANIM_NOSKIN (1<<22) #define ANIM_SETTIME (1<<23) #define ANIM_FULLBRIGHT (1<<24) #define ANIM_REUSE (1<<25) #define ANIM_NORENDER (1<<26) #define ANIM_RAGDOLL (1<<27) #define ANIM_SETSPEED (1<<28) #define ANIM_NOPITCH (1<<29) #define ANIM_GHOST (1<<30) #define ANIM_FLAGS (0x1FF<<22) struct animinfo // description of a character's animation { int anim, frame, range, basetime; float speed; uint varseed; animinfo() : anim(0), frame(0), range(0), basetime(0), speed(100.0f), varseed(0) { } bool operator==(const animinfo &o) const { return frame==o.frame && range==o.range && (anim&(ANIM_SETTIME|ANIM_DIR))==(o.anim&(ANIM_SETTIME|ANIM_DIR)) && (anim&ANIM_SETTIME || basetime==o.basetime) && speed==o.speed; } bool operator!=(const animinfo &o) const { return frame!=o.frame || range!=o.range || (anim&(ANIM_SETTIME|ANIM_DIR))!=(o.anim&(ANIM_SETTIME|ANIM_DIR)) || (!(anim&ANIM_SETTIME) && basetime!=o.basetime) || speed!=o.speed; } }; struct animinterpinfo // used for animation blending of animated characters { animinfo prev, cur; int lastswitch; void *lastmodel; animinterpinfo() : lastswitch(-1), lastmodel(NULL) {} void reset() { lastswitch = -1; } }; #define MAXANIMPARTS 3 struct occludequery; struct ragdolldata; struct dynent : physent // animated characters, or characters that can receive input { bool k_left, k_right, k_up, k_down; // see input code entitylight light; animinterpinfo animinterp[MAXANIMPARTS]; ragdolldata *ragdoll; occludequery *query; int occluded, lastrendered; dynent() : ragdoll(NULL), query(NULL), occluded(0), lastrendered(0) { reset(); } ~dynent() { #ifndef STANDALONE extern void cleanragdoll(dynent *d); if(ragdoll) cleanragdoll(this); #endif } void stopmoving() { k_left = k_right = k_up = k_down = jumping = false; move = strafe = 0; } void reset() { physent::reset(); stopmoving(); loopi(MAXANIMPARTS) animinterp[i].reset(); } vec abovehead() { return vec(o).add(vec(0, 0, aboveeye+4)); } }; sauerbraten-0.0.20130203.dfsg/shared/cube.h0000644000175000017500000000202212011474074017726 0ustar vincentvincent#ifndef __CUBE_H__ #define __CUBE_H__ #define _FILE_OFFSET_BITS 64 #ifdef __GNUC__ #define gamma __gamma #endif #ifdef WIN32 #define _USE_MATH_DEFINES #endif #include #ifdef __GNUC__ #undef gamma #endif #include #include #include #include #include #include #include #include #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0500 #include "windows.h" #ifndef _WINDOWS #define _WINDOWS #endif #ifndef __GNUC__ #include #include #endif #define ZLIB_DLL #endif #ifndef STANDALONE #include #include #include #endif #include #include #ifdef __sun__ #undef sun #undef MAXNAMELEN #ifdef queue #undef queue #endif #define queue __squeue #endif #include "tools.h" #include "geom.h" #include "ents.h" #include "command.h" #include "iengine.h" #include "igame.h" #endif sauerbraten-0.0.20130203.dfsg/shared/zip.cpp0000644000175000017500000004224412072672414020164 0ustar vincentvincent#include "cube.h" enum { ZIP_LOCAL_FILE_SIGNATURE = 0x04034B50, ZIP_LOCAL_FILE_SIZE = 30, ZIP_FILE_SIGNATURE = 0x02014B50, ZIP_FILE_SIZE = 46, ZIP_DIRECTORY_SIGNATURE = 0x06054B50, ZIP_DIRECTORY_SIZE = 22 }; struct ziplocalfileheader { uint signature; ushort version, flags, compression, modtime, moddate; uint crc32, compressedsize, uncompressedsize; ushort namelength, extralength; }; struct zipfileheader { uint signature; ushort version, needversion, flags, compression, modtime, moddate; uint crc32, compressedsize, uncompressedsize; ushort namelength, extralength, commentlength, disknumber, internalattribs; uint externalattribs, offset; }; struct zipdirectoryheader { uint signature; ushort disknumber, directorydisk, diskentries, entries; uint size, offset; ushort commentlength; }; struct zipfile { char *name; uint header, offset, size, compressedsize; zipfile() : name(NULL), header(0), offset(~0U), size(0), compressedsize(0) { } ~zipfile() { DELETEA(name); } }; struct zipstream; struct ziparchive { char *name; FILE *data; hashtable files; int openfiles; zipstream *owner; ziparchive() : name(NULL), data(NULL), files(512), openfiles(0), owner(NULL) { } ~ziparchive() { DELETEA(name); if(data) { fclose(data); data = NULL; } } }; static bool findzipdirectory(FILE *f, zipdirectoryheader &hdr) { if(fseek(f, 0, SEEK_END) < 0) return false; uchar buf[1024], *src = NULL; int len = 0, offset = ftell(f), end = max(offset - 0xFFFF - ZIP_DIRECTORY_SIZE, 0); const uint signature = lilswap(ZIP_DIRECTORY_SIGNATURE); while(offset > end) { int carry = min(len, ZIP_DIRECTORY_SIZE-1), next = min((int)sizeof(buf) - carry, offset - end); offset -= next; memmove(&buf[next], buf, carry); if(next + carry < ZIP_DIRECTORY_SIZE || fseek(f, offset, SEEK_SET) < 0 || (int)fread(buf, 1, next, f) != next) return false; len = next + carry; uchar *search = &buf[next-1]; for(; search >= buf; search--) if(*(uint *)search == signature) break; if(search >= buf) { src = search; break; } } if(&buf[len] - src < ZIP_DIRECTORY_SIZE) return false; hdr.signature = lilswap(*(uint *)src); src += 4; hdr.disknumber = lilswap(*(ushort *)src); src += 2; hdr.directorydisk = lilswap(*(ushort *)src); src += 2; hdr.diskentries = lilswap(*(ushort *)src); src += 2; hdr.entries = lilswap(*(ushort *)src); src += 2; hdr.size = lilswap(*(uint *)src); src += 4; hdr.offset = lilswap(*(uint *)src); src += 4; hdr.commentlength = lilswap(*(ushort *)src); src += 2; if(hdr.signature != ZIP_DIRECTORY_SIGNATURE || hdr.disknumber != hdr.directorydisk || hdr.diskentries != hdr.entries) return false; return true; } #ifndef STANDALONE VAR(dbgzip, 0, 0, 1); #endif static bool readzipdirectory(const char *archname, FILE *f, int entries, int offset, int size, vector &files) { uchar *buf = new uchar[size], *src = buf; if(fseek(f, offset, SEEK_SET) < 0 || (int)fread(buf, 1, size, f) != size) { delete[] buf; return false; } loopi(entries) { if(src + ZIP_FILE_SIZE > &buf[size]) break; zipfileheader hdr; hdr.signature = lilswap(*(uint *)src); src += 4; hdr.version = lilswap(*(ushort *)src); src += 2; hdr.needversion = lilswap(*(ushort *)src); src += 2; hdr.flags = lilswap(*(ushort *)src); src += 2; hdr.compression = lilswap(*(ushort *)src); src += 2; hdr.modtime = lilswap(*(ushort *)src); src += 2; hdr.moddate = lilswap(*(ushort *)src); src += 2; hdr.crc32 = lilswap(*(uint *)src); src += 4; hdr.compressedsize = lilswap(*(uint *)src); src += 4; hdr.uncompressedsize = lilswap(*(uint *)src); src += 4; hdr.namelength = lilswap(*(ushort *)src); src += 2; hdr.extralength = lilswap(*(ushort *)src); src += 2; hdr.commentlength = lilswap(*(ushort *)src); src += 2; hdr.disknumber = lilswap(*(ushort *)src); src += 2; hdr.internalattribs = lilswap(*(ushort *)src); src += 2; hdr.externalattribs = lilswap(*(uint *)src); src += 4; hdr.offset = lilswap(*(uint *)src); src += 4; if(hdr.signature != ZIP_FILE_SIGNATURE) break; if(!hdr.namelength || !hdr.uncompressedsize || (hdr.compression && (hdr.compression != Z_DEFLATED || !hdr.compressedsize))) { src += hdr.namelength + hdr.extralength + hdr.commentlength; continue; } if(src + hdr.namelength > &buf[size]) break; string pname; int namelen = min((int)hdr.namelength, (int)sizeof(pname)-1); memcpy(pname, src, namelen); pname[namelen] = '\0'; path(pname); char *name = newstring(pname); zipfile &f = files.add(); f.name = name; f.header = hdr.offset; f.size = hdr.uncompressedsize; f.compressedsize = hdr.compression ? hdr.compressedsize : 0; #ifndef STANDALONE if(dbgzip) conoutf(CON_DEBUG, "%s: file %s, size %d, compress %d, flags %x", archname, name, hdr.uncompressedsize, hdr.compression, hdr.flags); #endif src += hdr.namelength + hdr.extralength + hdr.commentlength; } delete[] buf; return files.length() > 0; } static bool readlocalfileheader(FILE *f, ziplocalfileheader &h, uint offset) { fseek(f, offset, SEEK_SET); uchar buf[ZIP_LOCAL_FILE_SIZE]; if(fread(buf, 1, ZIP_LOCAL_FILE_SIZE, f) != ZIP_LOCAL_FILE_SIZE) return false; uchar *src = buf; h.signature = lilswap(*(uint *)src); src += 4; h.version = lilswap(*(ushort *)src); src += 2; h.flags = lilswap(*(ushort *)src); src += 2; h.compression = lilswap(*(ushort *)src); src += 2; h.modtime = lilswap(*(ushort *)src); src += 2; h.moddate = lilswap(*(ushort *)src); src += 2; h.crc32 = lilswap(*(uint *)src); src += 4; h.compressedsize = lilswap(*(uint *)src); src += 4; h.uncompressedsize = lilswap(*(uint *)src); src += 4; h.namelength = lilswap(*(ushort *)src); src += 2; h.extralength = lilswap(*(ushort *)src); src += 2; if(h.signature != ZIP_LOCAL_FILE_SIGNATURE) return false; // h.uncompressedsize or h.compressedsize may be zero - so don't validate return true; } static vector archives; ziparchive *findzip(const char *name) { loopv(archives) if(!strcmp(name, archives[i]->name)) return archives[i]; return NULL; } static bool checkprefix(vector &files, const char *prefix, int prefixlen) { loopv(files) { if(!strncmp(files[i].name, prefix, prefixlen)) return false; } return true; } static void mountzip(ziparchive &arch, vector &files, const char *mountdir, const char *stripdir) { string packagesdir = "packages/"; path(packagesdir); int striplen = stripdir ? (int)strlen(stripdir) : 0; if(!mountdir && !stripdir) loopv(files) { zipfile &f = files[i]; const char *foundpackages = strstr(f.name, packagesdir); if(foundpackages) { if(foundpackages > f.name) { stripdir = f.name; striplen = foundpackages - f.name; } break; } const char *foundogz = strstr(f.name, ".ogz"); if(foundogz) { const char *ogzdir = foundogz; while(--ogzdir >= f.name && *ogzdir != PATHDIV); if(ogzdir < f.name || checkprefix(files, f.name, ogzdir + 1 - f.name)) { if(ogzdir >= f.name) { stripdir = f.name; striplen = ogzdir + 1 - f.name; } if(!mountdir) mountdir = "packages/base/"; break; } } } string mdir = "", fname; if(mountdir) { copystring(mdir, mountdir); if(fixpackagedir(mdir) <= 1) mdir[0] = '\0'; } loopv(files) { zipfile &f = files[i]; formatstring(fname)("%s%s", mdir, striplen && !strncmp(f.name, stripdir, striplen) ? &f.name[striplen] : f.name); if(arch.files.access(fname)) continue; char *mname = newstring(fname); zipfile &mf = arch.files[mname]; mf = f; mf.name = mname; } } bool addzip(const char *name, const char *mount = NULL, const char *strip = NULL) { string pname; copystring(pname, name); path(pname); int plen = (int)strlen(pname); if(plen < 4 || !strchr(&pname[plen-4], '.')) concatstring(pname, ".zip"); ziparchive *exists = findzip(pname); if(exists) { conoutf(CON_ERROR, "already added zip %s", pname); return true; } FILE *f = fopen(findfile(pname, "rb"), "rb"); if(!f) { conoutf(CON_ERROR, "could not open file %s", pname); return false; } zipdirectoryheader h; vector files; if(!findzipdirectory(f, h) || !readzipdirectory(pname, f, h.entries, h.offset, h.size, files)) { conoutf(CON_ERROR, "could not read directory in zip %s", pname); fclose(f); return false; } ziparchive *arch = new ziparchive; arch->name = newstring(pname); arch->data = f; mountzip(*arch, files, mount, strip); archives.add(arch); conoutf("added zip %s", pname); return true; } bool removezip(const char *name) { string pname; copystring(pname, name); path(pname); int plen = (int)strlen(pname); if(plen < 4 || !strchr(&pname[plen-4], '.')) concatstring(pname, ".zip"); ziparchive *exists = findzip(pname); if(!exists) { conoutf(CON_ERROR, "zip %s is not loaded", pname); return false; } if(exists->openfiles) { conoutf(CON_ERROR, "zip %s has open files", pname); return false; } conoutf("removed zip %s", exists->name); archives.removeobj(exists); delete exists; return true; } struct zipstream : stream { enum { BUFSIZE = 16384 }; ziparchive *arch; zipfile *info; z_stream zfile; uchar *buf; int reading; bool ended; zipstream() : arch(NULL), info(NULL), buf(NULL), reading(-1), ended(false) { zfile.zalloc = NULL; zfile.zfree = NULL; zfile.opaque = NULL; zfile.next_in = zfile.next_out = NULL; zfile.avail_in = zfile.avail_out = 0; } ~zipstream() { close(); } void readbuf(uint size = BUFSIZE) { if(!zfile.avail_in) zfile.next_in = (Bytef *)buf; size = min(size, uint(&buf[BUFSIZE] - &zfile.next_in[zfile.avail_in])); if(arch->owner != this) { arch->owner = NULL; if(fseek(arch->data, reading, SEEK_SET) >= 0) arch->owner = this; else return; } uint remaining = info->offset + info->compressedsize - reading; int n = arch->owner == this ? (int)fread(zfile.next_in + zfile.avail_in, 1, min(size, remaining), arch->data) : 0; zfile.avail_in += n; reading += n; } bool open(ziparchive *a, zipfile *f) { if(f->offset == ~0U) { ziplocalfileheader h; a->owner = NULL; if(!readlocalfileheader(a->data, h, f->header)) return false; f->offset = f->header + ZIP_LOCAL_FILE_SIZE + h.namelength + h.extralength; } if(f->compressedsize && inflateInit2(&zfile, -MAX_WBITS) != Z_OK) return false; a->openfiles++; arch = a; info = f; reading = f->offset; ended = false; if(f->compressedsize) buf = new uchar[BUFSIZE]; return true; } void stopreading() { if(reading < 0) return; #ifndef STANDALONE if(dbgzip) conoutf(CON_DEBUG, info->compressedsize ? "%s: zfile.total_out %u, info->size %u" : "%s: reading %u, info->size %u", info->name, info->compressedsize ? uint(zfile.total_out) : reading - info->offset, info->size); #endif if(info->compressedsize) inflateEnd(&zfile); reading = -1; } void close() { stopreading(); DELETEA(buf); if(arch) { arch->owner = NULL; arch->openfiles--; arch = NULL; } } offset size() { return info->size; } bool end() { return reading < 0 || ended; } offset tell() { return reading >= 0 ? (info->compressedsize ? zfile.total_out : reading - info->offset) : -1; } bool seek(offset pos, int whence) { if(reading < 0) return false; if(!info->compressedsize) { switch(whence) { case SEEK_END: pos += info->offset + info->size; break; case SEEK_CUR: pos += reading; break; case SEEK_SET: pos += info->offset; break; default: return false; } pos = clamp(pos, offset(info->offset), offset(info->offset + info->size)); arch->owner = NULL; if(fseek(arch->data, int(pos), SEEK_SET) < 0) return false; arch->owner = this; reading = pos; ended = false; return true; } switch(whence) { case SEEK_END: pos += info->size; break; case SEEK_CUR: pos += zfile.total_out; break; case SEEK_SET: break; default: return false; } if(pos >= (offset)info->size) { reading = info->offset + info->compressedsize; zfile.next_in += zfile.avail_in; zfile.avail_in = 0; zfile.total_in = info->compressedsize; arch->owner = NULL; ended = false; return true; } if(pos < 0) return false; if(pos >= (offset)zfile.total_out) pos -= zfile.total_out; else { if(zfile.next_in && zfile.total_in <= uint(zfile.next_in - buf)) { zfile.avail_in += zfile.total_in; zfile.next_in -= zfile.total_in; } else { arch->owner = NULL; zfile.avail_in = 0; zfile.next_in = NULL; reading = info->offset; } inflateReset(&zfile); } uchar skip[512]; while(pos > 0) { int skipped = (int)min(pos, (offset)sizeof(skip)); if(read(skip, skipped) != skipped) return false; pos -= skipped; } ended = false; return true; } int read(void *buf, int len) { if(reading < 0 || !buf || !len) return 0; if(!info->compressedsize) { if(arch->owner != this) { arch->owner = NULL; if(fseek(arch->data, reading, SEEK_SET) < 0) { stopreading(); return 0; } arch->owner = this; } int n = (int)fread(buf, 1, min(len, int(info->size + info->offset - reading)), arch->data); reading += n; if(n < len) ended = true; return n; } zfile.next_out = (Bytef *)buf; zfile.avail_out = len; while(zfile.avail_out > 0) { if(!zfile.avail_in) readbuf(BUFSIZE); int err = inflate(&zfile, Z_NO_FLUSH); if(err != Z_OK) { if(err == Z_STREAM_END) ended = true; else { #ifndef STANDALONE if(dbgzip) conoutf(CON_DEBUG, "inflate error: %s", zError(err)); #endif stopreading(); } break; } } return len - zfile.avail_out; } }; stream *openzipfile(const char *name, const char *mode) { for(; *mode; mode++) if(*mode=='w' || *mode=='a') return NULL; loopvrev(archives) { ziparchive *arch = archives[i]; zipfile *f = arch->files.access(name); if(!f) continue; zipstream *s = new zipstream; if(s->open(arch, f)) return s; delete s; } return NULL; } int listzipfiles(const char *dir, const char *ext, vector &files) { int extsize = ext ? (int)strlen(ext)+1 : 0, dirsize = (int)strlen(dir), dirs = 0; loopvrev(archives) { ziparchive *arch = archives[i]; int oldsize = files.length(); enumerate(arch->files, zipfile, f, { if(strncmp(f.name, dir, dirsize)) continue; const char *name = f.name + dirsize; if(name[0] == PATHDIV) name++; if(strchr(name, PATHDIV)) continue; if(!ext) files.add(newstring(name)); else { int namelength = (int)strlen(name) - extsize; if(namelength > 0 && name[namelength] == '.' && strncmp(name+namelength+1, ext, extsize-1)==0) files.add(newstring(name, namelength)); } }); if(files.length() > oldsize) dirs++; } return dirs; } #ifndef STANDALONE ICOMMAND(addzip, "sss", (const char *name, const char *mount, const char *strip), addzip(name, mount[0] ? mount : NULL, strip[0] ? strip : NULL)); ICOMMAND(removezip, "s", (const char *name), removezip(name)); #endif sauerbraten-0.0.20130203.dfsg/shared/cube2font.c0000644000175000017500000004630411706616501020710 0ustar vincentvincent#include #include #include #include #include #include #include #include FT_FREETYPE_H #include FT_STROKER_H #include FT_GLYPH_H typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; int imin(int a, int b) { return a < b ? a : b; } int imax(int a, int b) { return a > b ? a : b; } void fatal(const char *fmt, ...) { va_list v; va_start(v, fmt); vfprintf(stderr, fmt, v); va_end(v); fputc('\n', stderr); exit(EXIT_FAILURE); } uint bigswap(uint n) { const int islittleendian = 1; return *(const uchar *)&islittleendian ? (n<<24) | (n>>24) | ((n>>8)&0xFF00) | ((n<<8)&0xFF0000) : n; } size_t writebig(FILE *f, uint n) { n = bigswap(n); return fwrite(&n, 1, sizeof(n), f); } void writepngchunk(FILE *f, const char *type, uchar *data, uint len) { uint crc; writebig(f, len); fwrite(type, 1, 4, f); fwrite(data, 1, len, f); crc = crc32(0, Z_NULL, 0); crc = crc32(crc, (const Bytef *)type, 4); if(data) crc = crc32(crc, data, len); writebig(f, crc); } struct pngihdr { uint width, height; uchar bitdepth, colortype, compress, filter, interlace; }; void savepng(const char *filename, uchar *data, int w, int h, int bpp, int flip) { const uchar signature[] = { 137, 80, 78, 71, 13, 10, 26, 10 }; struct pngihdr ihdr; FILE *f; long idat; uint len, crc; z_stream z; uchar buf[1<<12]; int i, j; memset(&ihdr, 0, sizeof(ihdr)); ihdr.width = bigswap(w); ihdr.height = bigswap(h); ihdr.bitdepth = 8; switch(bpp) { case 1: ihdr.colortype = 0; break; case 2: ihdr.colortype = 4; break; case 3: ihdr.colortype = 2; break; case 4: ihdr.colortype = 6; break; default: fatal("cube2font: invalid PNG bpp"); return; } f = fopen(filename, "wb"); if(!f) { fatal("cube2font: could not write to %s", filename); return; } fwrite(signature, 1, sizeof(signature), f); writepngchunk(f, "IHDR", (uchar *)&ihdr, 13); idat = ftell(f); len = 0; fwrite("\0\0\0\0IDAT", 1, 8, f); crc = crc32(0, Z_NULL, 0); crc = crc32(crc, (const Bytef *)"IDAT", 4); z.zalloc = NULL; z.zfree = NULL; z.opaque = NULL; if(deflateInit(&z, Z_BEST_COMPRESSION) != Z_OK) goto error; z.next_out = (Bytef *)buf; z.avail_out = sizeof(buf); for(i = 0; i < h; i++) { uchar filter = 0; for(j = 0; j < 2; j++) { z.next_in = j ? (Bytef *)data + (flip ? h-i-1 : i)*w*bpp : (Bytef *)&filter; z.avail_in = j ? w*bpp : 1; while(z.avail_in > 0) { if(deflate(&z, Z_NO_FLUSH) != Z_OK) goto cleanuperror; #define FLUSHZ do { \ int flush = sizeof(buf) - z.avail_out; \ crc = crc32(crc, buf, flush); \ len += flush; \ fwrite(buf, 1, flush, f); \ z.next_out = (Bytef *)buf; \ z.avail_out = sizeof(buf); \ } while(0) FLUSHZ; } } } for(;;) { int err = deflate(&z, Z_FINISH); if(err != Z_OK && err != Z_STREAM_END) goto cleanuperror; FLUSHZ; if(err == Z_STREAM_END) break; } deflateEnd(&z); fseek(f, idat, SEEK_SET); writebig(f, len); fseek(f, 0, SEEK_END); writebig(f, crc); writepngchunk(f, "IEND", NULL, 0); fclose(f); return; cleanuperror: deflateEnd(&z); error: fclose(f); fatal("cube2font: failed saving PNG to %s", filename); } enum { CT_PRINT = 1<<0, CT_SPACE = 1<<1, CT_DIGIT = 1<<2, CT_ALPHA = 1<<3, CT_LOWER = 1<<4, CT_UPPER = 1<<5, CT_UNICODE = 1<<6 }; #define CUBECTYPE(s, p, d, a, A, u, U) \ 0, U, U, U, U, U, U, U, U, s, s, s, s, s, U, U, \ U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, \ s, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, \ d, d, d, d, d, d, d, d, d, d, p, p, p, p, p, p, \ p, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, \ A, A, A, A, A, A, A, A, A, A, A, p, p, p, p, p, \ p, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, \ a, a, a, a, a, a, a, a, a, a, a, p, p, p, p, U, \ U, u, u, u, u, u, u, u, u, u, u, u, u, u, u, u, \ u, u, u, u, u, u, u, u, u, u, u, u, u, u, u, U, \ u, U, u, U, u, U, u, U, u, U, u, U, u, U, u, U, \ u, U, u, U, u, U, u, U, u, U, u, U, u, U, u, U, \ u, U, u, U, u, U, u, U, U, u, U, u, U, u, U, U, \ U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, \ U, U, U, U, u, u, u, u, u, u, u, u, u, u, u, u, \ u, u, u, u, u, u, u, u, u, u, u, u, u, u, U, u const uchar cubectype[256] = { CUBECTYPE(CT_SPACE, CT_PRINT, CT_PRINT|CT_DIGIT, CT_PRINT|CT_ALPHA|CT_LOWER, CT_PRINT|CT_ALPHA|CT_UPPER, CT_PRINT|CT_UNICODE|CT_ALPHA|CT_LOWER, CT_PRINT|CT_UNICODE|CT_ALPHA|CT_UPPER) }; int iscubeprint(uchar c) { return cubectype[c]&CT_PRINT; } int iscubespace(uchar c) { return cubectype[c]&CT_SPACE; } int iscubealpha(uchar c) { return cubectype[c]&CT_ALPHA; } int iscubealnum(uchar c) { return cubectype[c]&(CT_ALPHA|CT_DIGIT); } int iscubelower(uchar c) { return cubectype[c]&CT_LOWER; } int iscubeupper(uchar c) { return cubectype[c]&CT_UPPER; } const int cube2unichars[256] = { 0, 192, 193, 194, 195, 196, 197, 198, 199, 9, 10, 11, 12, 13, 200, 201, 202, 203, 204, 205, 206, 207, 209, 210, 211, 212, 213, 214, 216, 217, 218, 219, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 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, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 220, 221, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 241, 242, 243, 244, 245, 246, 248, 249, 250, 251, 252, 253, 255, 0x104, 0x105, 0x106, 0x107, 0x10C, 0x10D, 0x10E, 0x10F, 0x118, 0x119, 0x11A, 0x11B, 0x11E, 0x11F, 0x130, 0x131, 0x141, 0x142, 0x143, 0x144, 0x147, 0x148, 0x150, 0x151, 0x152, 0x153, 0x158, 0x159, 0x15A, 0x15B, 0x15E, 0x15F, 0x160, 0x161, 0x164, 0x165, 0x16E, 0x16F, 0x170, 0x171, 0x178, 0x179, 0x17A, 0x17B, 0x17C, 0x17D, 0x17E, 0x404, 0x411, 0x413, 0x414, 0x416, 0x417, 0x418, 0x419, 0x41B, 0x41F, 0x423, 0x424, 0x426, 0x427, 0x428, 0x429, 0x42A, 0x42B, 0x42C, 0x42D, 0x42E, 0x42F, 0x431, 0x432, 0x433, 0x434, 0x436, 0x437, 0x438, 0x439, 0x43A, 0x43B, 0x43C, 0x43D, 0x43F, 0x442, 0x444, 0x446, 0x447, 0x448, 0x449, 0x44A, 0x44B, 0x44C, 0x44D, 0x44E, 0x44F, 0x454, 0x490, 0x491 }; int cube2uni(uchar c) { return cube2unichars[c]; } const char *encodeutf8(int uni) { static char buf[7]; char *dst = buf; if(uni <= 0x7F) { *dst++ = uni; goto uni1; } else if(uni <= 0x7FF) { *dst++ = 0xC0 | (uni>>6); goto uni2; } else if(uni <= 0xFFFF) { *dst++ = 0xE0 | (uni>>12); goto uni3; } else if(uni <= 0x1FFFFF) { *dst++ = 0xF0 | (uni>>18); goto uni4; } else if(uni <= 0x3FFFFFF) { *dst++ = 0xF8 | (uni>>24); goto uni5; } else if(uni <= 0x7FFFFFFF) { *dst++ = 0xFC | (uni>>30); goto uni6; } else goto uni1; uni6: *dst++ = 0x80 | ((uni>>24)&0x3F); uni5: *dst++ = 0x80 | ((uni>>18)&0x3F); uni4: *dst++ = 0x80 | ((uni>>12)&0x3F); uni3: *dst++ = 0x80 | ((uni>>6)&0x3F); uni2: *dst++ = 0x80 | (uni&0x3F); uni1: *dst++ = '\0'; return buf; } struct fontchar { int code, uni, tex, x, y, w, h, offx, offy, offset, advance; FT_BitmapGlyph color, alpha; }; const char *texdir = ""; const char *texfilename(const char *name, int texnum) { static char file[256]; snprintf(file, sizeof(file), "%s%d.png", name, texnum); return file; } const char *texname(const char *name, int texnum) { static char file[512]; snprintf(file, sizeof(file), "%s%s", texdir, texfilename(name, texnum)); return file; } void writetexs(const char *name, struct fontchar *chars, int numchars, int numtexs, int tw, int th) { int tex; uchar *pixels = (uchar *)malloc(tw*th*2); if(!pixels) fatal("cube2font: failed allocating textures"); for(tex = 0; tex < numtexs; tex++) { const char *file = texfilename(name, tex); int texchars = 0, i; uchar *dst, *src; memset(pixels, 0, tw*th*2); for(i = 0; i < numchars; i++) { struct fontchar *c = &chars[i]; int x, y; if(c->tex != tex) continue; texchars++; dst = &pixels[2*((c->y + c->offy - c->color->top)*tw + c->x + c->color->left - c->offx)]; src = (uchar *)c->color->bitmap.buffer; for(y = 0; y < c->color->bitmap.rows; y++) { for(x = 0; x < c->color->bitmap.width; x++) dst[2*x] = src[x]; src += c->color->bitmap.pitch; dst += 2*tw; } dst = &pixels[2*((c->y + c->offy - c->alpha->top)*tw + c->x + c->alpha->left - c->offx)]; src = (uchar *)c->alpha->bitmap.buffer; for(y = 0; y < c->alpha->bitmap.rows; y++) { for(x = 0; x < c->alpha->bitmap.width; x++) dst[2*x+1] = src[x]; src += c->alpha->bitmap.pitch; dst += 2*tw; } } printf("cube2font: writing %d chars to %s\n", texchars, file); savepng(file, pixels, tw, th, 2, 0); } free(pixels); } void writecfg(const char *name, struct fontchar *chars, int numchars, int x1, int y1, int x2, int y2, int sw, int sh, int argc, char **argv) { FILE *f; char file[256]; int i, lastcode = 0, lasttex = 0; snprintf(file, sizeof(file), "%s.cfg", name); f = fopen(file, "w"); if(!f) fatal("cube2font: failed writing %s", file); printf("cube2font: writing %d chars to %s\n", numchars, file); fprintf(f, "//"); for(i = 1; i < argc; i++) fprintf(f, " %s", argv[i]); fprintf(f, "\n"); fprintf(f, "font \"%s\" \"%s\" %d %d\n", name, texname(name, 0), sw, sh); for(i = 0; i < numchars; i++) { struct fontchar *c = &chars[i]; if(!lastcode && lastcode < c->code) { fprintf(f, "fontoffset \"%s\"\n", encodeutf8(c->uni)); lastcode = c->code; } else if(lastcode < c->code) { if(lastcode + 1 == c->code) fprintf(f, "fontskip // %d\n", lastcode); else fprintf(f, "fontskip %d // %d .. %d\n", c->code - lastcode, lastcode, c->code-1); lastcode = c->code; } if(lasttex != c->tex) { fprintf(f, "\nfonttex \"%s\"\n", texname(name, c->tex)); lasttex = c->tex; } if(c->code != c->uni) fprintf(f, "fontchar %d %d %d %d %d %d %d // %s (%d -> 0x%X)\n", c->x, c->y, c->w, c->h, c->offx+c->offset, y2-c->offy, c->advance, encodeutf8(c->uni), c->code, c->uni); else fprintf(f, "fontchar %d %d %d %d %d %d %d // %s (%d)\n", c->x, c->y, c->w, c->h, c->offx+c->offset, y2-c->offy, c->advance, encodeutf8(c->uni), c->code); lastcode++; } fclose(f); } int groupchar(int c) { switch(c) { case 0x152: case 0x153: case 0x178: return 1; } if(c < 127 || c >= 0x2000) return 0; if(c < 0x100) return 1; if(c < 0x400) return 2; return 3; } int sortchars(const void *x, const void *y) { const struct fontchar *xc = *(const struct fontchar **)x, *yc = *(const struct fontchar **)y; int xg = groupchar(xc->uni), yg = groupchar(yc->uni); if(xg < yg) return -1; if(xg > yg) return 1; if(xc->h != yc->h) return yc->h - xc->h; if(xc->w != yc->w) return yc->w - xc->w; return yc->uni - xc->uni; } int scorechar(struct fontchar *f, int pad, int tw, int th, int rw, int rh, int ry) { int score = 0; if(rw + f->w > tw) { ry += rh + pad; score = 1; } if(ry + f->h > th) score = 2; return score; } int main(int argc, char **argv) { FT_Library l; FT_Face f; FT_Stroker s, s2; int i, pad, offset, advance, w, h, tw, th, c, trial = -2, rw = 0, rh = 0, ry = 0, x1 = INT_MAX, x2 = INT_MIN, y1 = INT_MAX, y2 = INT_MIN, w2 = 0, h2 = 0, sw = 0, sh = 0; float outborder = 0, inborder = 0; struct fontchar chars[256]; struct fontchar *order[256]; int numchars = 0, numtex = 0; if(argc < 11) fatal("Usage: cube2font infile outfile outborder[:inborder] pad offset advance charwidth charheight texwidth texheight [spacewidth spaceheight texdir]"); sscanf(argv[3], "%f:%f", &outborder, &inborder); pad = atoi(argv[4]); offset = atoi(argv[5]); advance = atoi(argv[6]); w = atoi(argv[7]); h = atoi(argv[8]); tw = atoi(argv[9]); th = atoi(argv[10]); if(argc > 11) sw = atoi(argv[11]); if(argc > 12) sh = atoi(argv[12]); if(argc > 13) texdir = argv[13]; if(FT_Init_FreeType(&l)) fatal("cube2font: failed initing freetype"); if(FT_New_Face(l, argv[1], 0, &f) || FT_Set_Charmap(f, f->charmaps[0]) || FT_Set_Pixel_Sizes(f, w, h) || FT_Stroker_New(l, &s) || FT_Stroker_New(l, &s2)) fatal("cube2font: failed loading font %s", argv[1]); if(outborder > 0) FT_Stroker_Set(s, (FT_Fixed)(outborder * 64), FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0); if(inborder > 0) FT_Stroker_Set(s2, (FT_Fixed)(inborder * 64), FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0); for(c = 0; c < 256; c++) if(iscubeprint(c)) { FT_Glyph p, p2; FT_BitmapGlyph b, b2; struct fontchar *dst = &chars[numchars]; dst->code = c; dst->uni = cube2uni(c); if(FT_Load_Char(f, dst->uni, FT_LOAD_DEFAULT)) fatal("cube2font: failed loading character %s", encodeutf8(dst->uni)); FT_Get_Glyph(f->glyph, &p); p2 = p; if(outborder > 0) FT_Glyph_StrokeBorder(&p, s, 0, 0); if(inborder > 0) FT_Glyph_StrokeBorder(&p2, s2, 1, 0); FT_Glyph_To_Bitmap(&p, FT_RENDER_MODE_NORMAL, 0, 1); FT_Glyph_To_Bitmap(&p2, FT_RENDER_MODE_NORMAL, 0, 1); b = (FT_BitmapGlyph)p; b2 = (FT_BitmapGlyph)p2; dst->tex = -1; dst->x = INT_MIN; dst->y = INT_MIN; dst->offx = imin(b->left, b2->left); dst->offy = imax(b->top, b2->top); dst->offset = offset; dst->advance = offset + ((p->advance.x+0xFFFF)>>16) + advance; dst->w = imax(b->left + b->bitmap.width, b2->left + b2->bitmap.width) - dst->offx; dst->h = dst->offy - imin(b->top - b->bitmap.rows, b2->top - b2->bitmap.rows); dst->alpha = b; dst->color = b2; order[numchars++] = dst; } qsort(order, numchars, sizeof(order[0]), sortchars); for(i = 0; i < numchars;) { struct fontchar *dst; int j, k, trial0, prevscore, dstscore, fitscore; for(trial0 = trial, prevscore = -1; (trial -= 2) >= trial0-512;) { int g, fw = rw, fh = rh, fy = ry, curscore = 0, reused = 0; for(j = i; j < numchars; j++) { dst = order[j]; if(dst->tex >= 0 || dst->tex <= trial) continue; g = groupchar(dst->uni); dstscore = scorechar(dst, pad, tw, th, fw, fh, fy); for(k = j; k < numchars; k++) { struct fontchar *fit = order[k]; if(fit->tex >= 0 || fit->tex <= trial) continue; if(fit->tex >= trial0 && groupchar(fit->uni) != g) break; fitscore = scorechar(fit, pad, tw, th, fw, fh, fy); if(fitscore < dstscore || (fitscore == dstscore && fit->h > dst->h)) { dst = fit; dstscore = fitscore; } } if(fw + dst->w > tw) { fy += fh + pad; fw = fh = 0; } if(fy + dst->h > th) { fy = fw = fh = 0; if(curscore > 0) break; } if(dst->tex >= trial+1 && dst->tex <= trial+2) { dst->tex = trial; reused++; } else dst->tex = trial; fw += dst->w + pad; fh = imax(fh, dst->h); if(dst != order[j]) --j; curscore++; } if(reused < prevscore || curscore <= prevscore) break; prevscore = curscore; } for(; i < numchars; i++) { dst = order[i]; if(dst->tex >= 0) continue; dstscore = scorechar(dst, pad, tw, th, rw, rh, ry); for(j = i; j < numchars; j++) { struct fontchar *fit = order[j]; if(fit->tex < trial || fit->tex > trial+2) continue; fitscore = scorechar(fit, pad, tw, th, rw, rh, ry); if(fitscore < dstscore || (fitscore == dstscore && fit->h > dst->h)) { dst = fit; dstscore = fitscore; } } if(dst->tex < trial || dst->tex > trial+2) break; if(rw + dst->w > tw) { ry += rh + pad; rw = rh = 0; } if(ry + dst->h > th) { ry = rw = rh = 0; numtex++; } dst->tex = numtex; dst->x = rw; dst->y = ry; rw += dst->w + pad; rh = imax(rh, dst->h); y1 = imin(y1, dst->offy - dst->h); y2 = imax(y2, dst->offy); x1 = imin(x1, dst->offx); x2 = imax(x2, dst->offx + dst->w); w2 = imax(w2, dst->w); h2 = imax(h2, dst->h); if(dst != order[i]) --i; } } if(rh > 0) numtex++; #if 0 if(sw <= 0) { if(FT_Load_Char(f, ' ', FT_LOAD_DEFAULT)) fatal("cube2font: failed loading space character"); sw = (f->glyph->advance.x+0x3F)>>6; } #endif if(sh <= 0) sh = y2 - y1; if(sw <= 0) sw = sh/3; writetexs(argv[2], chars, numchars, numtex, tw, th); writecfg(argv[2], chars, numchars, x1, y1, x2, y2, sw, sh, argc, argv); for(i = 0; i < numchars; i++) { FT_Done_Glyph((FT_Glyph)chars[i].alpha); FT_Done_Glyph((FT_Glyph)chars[i].color); } FT_Stroker_Done(s); FT_Stroker_Done(s2); FT_Done_FreeType(l); printf("cube2font: (%d, %d) .. (%d, %d) = (%d, %d) / (%d, %d), %d texs\n", x1, y1, x2, y2, x2 - x1, y2 - y1, w2, h2, numtex); return EXIT_SUCCESS; } sauerbraten-0.0.20130203.dfsg/shared/crypto.cpp0000644000175000017500000006265712051737222020710 0ustar vincentvincent#include "cube.h" ///////////////////////// cryptography ///////////////////////////////// /* Based off the reference implementation of Tiger, a cryptographically * secure 192 bit hash function by Ross Anderson and Eli Biham. More info at: * http://www.cs.technion.ac.il/~biham/Reports/Tiger/ */ #define TIGER_PASSES 3 namespace tiger { typedef unsigned long long int chunk; union hashval { uchar bytes[3*8]; chunk chunks[3]; }; chunk sboxes[4*256]; void compress(const chunk *str, chunk state[3]) { chunk a, b, c; chunk aa, bb, cc; chunk x0, x1, x2, x3, x4, x5, x6, x7; a = state[0]; b = state[1]; c = state[2]; x0=str[0]; x1=str[1]; x2=str[2]; x3=str[3]; x4=str[4]; x5=str[5]; x6=str[6]; x7=str[7]; aa = a; bb = b; cc = c; loop(pass_no, TIGER_PASSES) { if(pass_no) { x0 -= x7 ^ 0xA5A5A5A5A5A5A5A5ULL; x1 ^= x0; x2 += x1; x3 -= x2 ^ ((~x1)<<19); x4 ^= x3; x5 += x4; x6 -= x5 ^ ((~x4)>>23); x7 ^= x6; x0 += x7; x1 -= x0 ^ ((~x7)<<19); x2 ^= x1; x3 += x2; x4 -= x3 ^ ((~x2)>>23); x5 ^= x4; x6 += x5; x7 -= x6 ^ 0x0123456789ABCDEFULL; } #define sb1 (sboxes) #define sb2 (sboxes+256) #define sb3 (sboxes+256*2) #define sb4 (sboxes+256*3) #define round(a, b, c, x) \ c ^= x; \ a -= sb1[((c)>>(0*8))&0xFF] ^ sb2[((c)>>(2*8))&0xFF] ^ \ sb3[((c)>>(4*8))&0xFF] ^ sb4[((c)>>(6*8))&0xFF] ; \ b += sb4[((c)>>(1*8))&0xFF] ^ sb3[((c)>>(3*8))&0xFF] ^ \ sb2[((c)>>(5*8))&0xFF] ^ sb1[((c)>>(7*8))&0xFF] ; \ b *= mul; uint mul = !pass_no ? 5 : (pass_no==1 ? 7 : 9); round(a, b, c, x0) round(b, c, a, x1) round(c, a, b, x2) round(a, b, c, x3) round(b, c, a, x4) round(c, a, b, x5) round(a, b, c, x6) round(b, c, a, x7) chunk tmp = a; a = c; c = b; b = tmp; } a ^= aa; b -= bb; c += cc; state[0] = a; state[1] = b; state[2] = c; } void gensboxes() { const char *str = "Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham"; chunk state[3] = { 0x0123456789ABCDEFULL, 0xFEDCBA9876543210ULL, 0xF096A5B4C3B2E187ULL }; uchar temp[64]; if(!*(const uchar *)&islittleendian) loopj(64) temp[j^7] = str[j]; else loopj(64) temp[j] = str[j]; loopi(1024) loop(col, 8) ((uchar *)&sboxes[i])[col] = i&0xFF; int abc = 2; loop(pass, 5) loopi(256) for(int sb = 0; sb < 1024; sb += 256) { abc++; if(abc >= 3) { abc = 0; compress((chunk *)temp, state); } loop(col, 8) { uchar val = ((uchar *)&sboxes[sb+i])[col]; ((uchar *)&sboxes[sb+i])[col] = ((uchar *)&sboxes[sb + ((uchar *)&state[abc])[col]])[col]; ((uchar *)&sboxes[sb + ((uchar *)&state[abc])[col]])[col] = val; } } } void hash(const uchar *str, int length, hashval &val) { static bool init = false; if(!init) { gensboxes(); init = true; } uchar temp[64]; val.chunks[0] = 0x0123456789ABCDEFULL; val.chunks[1] = 0xFEDCBA9876543210ULL; val.chunks[2] = 0xF096A5B4C3B2E187ULL; int i = length; for(; i >= 64; i -= 64, str += 64) { if(!*(const uchar *)&islittleendian) { loopj(64) temp[j^7] = str[j]; compress((chunk *)temp, val.chunks); } else compress((chunk *)str, val.chunks); } int j; if(!*(const uchar *)&islittleendian) { for(j = 0; j < i; j++) temp[j^7] = str[j]; temp[j^7] = 0x01; while(++j&7) temp[j^7] = 0; } else { for(j = 0; j < i; j++) temp[j] = str[j]; temp[j] = 0x01; while(++j&7) temp[j] = 0; } if(j > 56) { while(j < 64) temp[j++] = 0; compress((chunk *)temp, val.chunks); j = 0; } while(j < 56) temp[j++] = 0; *(chunk *)(temp+56) = (chunk)length<<3; compress((chunk *)temp, val.chunks); if(!*(const uchar *)&islittleendian) { loopk(3) { uchar *c = &val.bytes[k*sizeof(chunk)]; loopl(sizeof(chunk)/2) swap(c[l], c[sizeof(chunk)-1-l]); } } } } /* Elliptic curve cryptography based on NIST DSS prime curves. */ #define BI_DIGIT_BITS 16 #define BI_DIGIT_MASK ((1< struct bigint { typedef ushort digit; typedef uint dbldigit; int len; digit digits[BI_DIGITS]; bigint() {} bigint(digit n) { if(n) { len = 1; digits[0] = n; } else len = 0; } bigint(const char *s) { parse(s); } template bigint(const bigint &y) { *this = y; } static int parsedigits(ushort *digits, int maxlen, const char *s) { int slen = 0; while(isxdigit(s[slen])) slen++; int len = (slen+2*sizeof(ushort)-1)/(2*sizeof(ushort)); if(len>maxlen) return 0; memset(digits, 0, len*sizeof(ushort)); loopi(slen) { int c = s[slen-i-1]; if(isalpha(c)) c = toupper(c) - 'A' + 10; else if(isdigit(c)) c -= '0'; else return 0; digits[i/(2*sizeof(ushort))] |= c<<(4*(i%(2*sizeof(ushort)))); } return len; } void parse(const char *s) { len = parsedigits(digits, BI_DIGITS, s); shrink(); } void zero() { len = 0; } void print(stream *out) const { vector buf; printdigits(buf); out->write(buf.getbuf(), buf.length()); } void printdigits(vector &buf) const { loopi(len) { digit d = digits[len-i-1]; loopj(BI_DIGIT_BITS/4) { uint shift = BI_DIGIT_BITS - (j+1)*4; int val = (d >> shift) & 0xF; if(val < 10) buf.add('0' + val); else buf.add('a' + val - 10); } } } template bigint &operator=(const bigint &y) { len = y.len; memcpy(digits, y.digits, len*sizeof(digit)); return *this; } bool iszero() const { return !len; } bool isone() const { return len==1 && digits[0]==1; } int numbits() const { if(!len) return 0; int bits = len*BI_DIGIT_BITS; digit last = digits[len-1], mask = 1<<(BI_DIGIT_BITS-1); while(mask) { if(last&mask) return bits; bits--; mask >>= 1; } return 0; } bool hasbit(int n) const { return n/BI_DIGIT_BITS < len && ((digits[n/BI_DIGIT_BITS]>>(n%BI_DIGIT_BITS))&1); } template bigint &add(const bigint &x, const bigint &y) { dbldigit carry = 0; int maxlen = max(x.len, y.len), i; for(i = 0; i < y.len || carry; i++) { carry += (i < x.len ? (dbldigit)x.digits[i] : 0) + (i < y.len ? (dbldigit)y.digits[i] : 0); digits[i] = (digit)carry; carry >>= BI_DIGIT_BITS; } if(i < x.len && this != &x) memcpy(&digits[i], &x.digits[i], (x.len - i)*sizeof(digit)); len = max(i, maxlen); return *this; } template bigint &add(const bigint &y) { return add(*this, y); } template bigint &sub(const bigint &x, const bigint &y) { ASSERT(x >= y); dbldigit borrow = 0; int i; for(i = 0; i < y.len || borrow; i++) { borrow = (1<>BI_DIGIT_BITS)^1; } if(i < x.len && this != &x) memcpy(&digits[i], &x.digits[i], (x.len - i)*sizeof(digit)); len = x.len; shrink(); return *this; } template bigint &sub(const bigint &y) { return sub(*this, y); } void shrink() { while(len && !digits[len-1]) len--; } template bigint &mul(const bigint &x, const bigint &y) { if(!x.len || !y.len) { len = 0; return *this; } memset(digits, 0, y.len*sizeof(digit)); loopi(x.len) { dbldigit carry = 0; loopj(y.len) { carry += (dbldigit)x.digits[i] * (dbldigit)y.digits[j] + (dbldigit)digits[i+j]; digits[i+j] = (digit)carry; carry >>= BI_DIGIT_BITS; } digits[i+y.len] = carry; } len = x.len + y.len; shrink(); return *this; } template bigint &rshift(const bigint &x, int n) { if(!len || !n) return *this; int dig = (n-1)/BI_DIGIT_BITS; n = ((n-1) % BI_DIGIT_BITS)+1; digit carry = digit(x.digits[dig]>>n); loopi(len-dig-1) { digit tmp = x.digits[i+dig+1]; digits[i] = digit((tmp<<(BI_DIGIT_BITS-n)) | carry); carry = digit(tmp>>n); } digits[len-dig-1] = carry; len -= dig + (n>>BI_DIGIT_BITS); shrink(); return *this; } bigint &rshift(int n) { return rshift(*this, n); } template bigint &lshift(const bigint &x, int n) { if(!len || !n) return *this; int dig = n/BI_DIGIT_BITS; n %= BI_DIGIT_BITS; digit carry = 0; for(int i = len-1; i>=0; i--) { digit tmp = x.digits[i]; digits[i+dig] = digit((tmp<>(BI_DIGIT_BITS-n)); } len += dig; if(carry) digits[len++] = carry; if(dig) memset(digits, 0, dig*sizeof(digit)); return *this; } bigint &lshift(int n) { return lshift(*this, n); } template bool operator==(const bigint &y) const { if(len!=y.len) return false; for(int i = len-1; i>=0; i--) if(digits[i]!=y.digits[i]) return false; return true; } template bool operator!=(const bigint &y) const { return !(*this==y); } template bool operator<(const bigint &y) const { if(leny.len) return false; for(int i = len-1; i>=0; i--) { if(digits[i]y.digits[i]) return false; } return false; } template bool operator>(const bigint &y) const { return y<*this; } template bool operator<=(const bigint &y) const { return !(y<*this); } template bool operator>=(const bigint &y) const { return !(*this gfint; /* NIST prime Galois fields. * Currently only supports NIST P-192, where P=2^192-2^64-1. */ struct gfield : gfint { static const gfield P; gfield() {} gfield(digit n) : gfint(n) {} gfield(const char *s) : gfint(s) {} template gfield(const bigint &y) : gfint(y) {} template gfield &operator=(const bigint &y) { gfint::operator=(y); return *this; } template gfield &add(const bigint &x, const bigint &y) { gfint::add(x, y); if(*this >= P) gfint::sub(*this, P); return *this; } template gfield &add(const bigint &y) { return add(*this, y); } template gfield &mul2(const bigint &x) { return add(x, x); } gfield &mul2() { return mul2(*this); } template gfield &div2(const bigint &x) { if(hasbit(0)) { gfint::add(x, P); rshift(1); } else rshift(x, 1); return *this; } gfield &div2() { return div2(*this); } template gfield &sub(const bigint &x, const bigint &y) { if(x < y) { gfint tmp; /* necessary if this==&y, using this instead would clobber y */ tmp.add(x, P); gfint::sub(tmp, y); } else gfint::sub(x, y); return *this; } template gfield &sub(const bigint &y) { return sub(*this, y); } template gfield &neg(const bigint &x) { gfint::sub(P, x); return *this; } gfield &neg() { return neg(*this); } template gfield &square(const bigint &x) { return mul(x, x); } gfield &square() { return square(*this); } template gfield &mul(const bigint &x, const bigint &y) { bigint result; result.mul(x, y); reduce(result); return *this; } template gfield &mul(const bigint &y) { return mul(*this, y); } template void reduce(const bigint &result) { #if GF_BITS==192 len = min(result.len, GF_DIGITS); memcpy(digits, result.digits, len*sizeof(digit)); shrink(); if(result.len > 192/BI_DIGIT_BITS) { gfield s; memcpy(s.digits, &result.digits[192/BI_DIGIT_BITS], min(result.len-192/BI_DIGIT_BITS, 64/BI_DIGIT_BITS)*sizeof(digit)); if(result.len < 256/BI_DIGIT_BITS) memset(&s.digits[result.len-192/BI_DIGIT_BITS], 0, (256/BI_DIGIT_BITS-result.len)*sizeof(digit)); memcpy(&s.digits[64/BI_DIGIT_BITS], s.digits, 64/BI_DIGIT_BITS*sizeof(digit)); s.len = 128/BI_DIGIT_BITS; s.shrink(); add(s); if(result.len > 256/BI_DIGIT_BITS) { memset(s.digits, 0, 64/BI_DIGIT_BITS*sizeof(digit)); memcpy(&s.digits[64/BI_DIGIT_BITS], &result.digits[256/BI_DIGIT_BITS], min(result.len-256/BI_DIGIT_BITS, 64/BI_DIGIT_BITS)*sizeof(digit)); if(result.len < 320/BI_DIGIT_BITS) memset(&s.digits[result.len+(64-256)/BI_DIGIT_BITS], 0, (320/BI_DIGIT_BITS-result.len)*sizeof(digit)); memcpy(&s.digits[128/BI_DIGIT_BITS], &s.digits[64/BI_DIGIT_BITS], 64/BI_DIGIT_BITS*sizeof(digit)); s.len = GF_DIGITS; s.shrink(); add(s); if(result.len > 320/BI_DIGIT_BITS) { memcpy(s.digits, &result.digits[320/BI_DIGIT_BITS], min(result.len-320/BI_DIGIT_BITS, 64/BI_DIGIT_BITS)*sizeof(digit)); if(result.len < 384/BI_DIGIT_BITS) memset(&s.digits[result.len-320/BI_DIGIT_BITS], 0, (384/BI_DIGIT_BITS-result.len)*sizeof(digit)); memcpy(&s.digits[64/BI_DIGIT_BITS], s.digits, 64/BI_DIGIT_BITS*sizeof(digit)); memcpy(&s.digits[128/BI_DIGIT_BITS], s.digits, 64/BI_DIGIT_BITS*sizeof(digit)); s.len = GF_DIGITS; s.shrink(); add(s); } } } else if(*this >= P) gfint::sub(*this, P); #else #error Unsupported GF #endif } template gfield &pow(const bigint &x, const bigint &y) { gfield a(x); if(y.hasbit(0)) *this = a; else { len = 1; digits[0] = 1; if(!y.len) return *this; } for(int i = 1, j = y.numbits(); i < j; i++) { a.square(); if(y.hasbit(i)) mul(a); } return *this; } template gfield &pow(const bigint &y) { return pow(*this, y); } bool invert(const gfield &x) { if(!x.len) return false; gfint u(x), v(P), A((gfint::digit)1), C((gfint::digit)0); while(!u.iszero()) { int ushift = 0, ashift = 0; while(!u.hasbit(ushift)) { ushift++; if(A.hasbit(ashift)) { if(ashift) { A.rshift(ashift); ashift = 0; } A.add(P); } ashift++; } if(ushift) u.rshift(ushift); if(ashift) A.rshift(ashift); int vshift = 0, cshift = 0; while(!v.hasbit(vshift)) { vshift++; if(C.hasbit(cshift)) { if(cshift) { C.rshift(cshift); cshift = 0; } C.add(P); } cshift++; } if(vshift) v.rshift(vshift); if(cshift) C.rshift(cshift); if(u >= v) { u.sub(v); if(A < C) A.add(P); A.sub(C); } else { v.sub(v, u); if(C < A) C.add(P); C.sub(A); } } if(C >= P) gfint::sub(C, P); else { len = C.len; memcpy(digits, C.digits, len*sizeof(digit)); } ASSERT(*this < P); return true; } void invert() { invert(*this); } template static int legendre(const bigint &x) { static const gfint Psub1div2(gfint(P).sub(bigint<1>(1)).rshift(1)); gfield L; L.pow(x, Psub1div2); if(!L.len) return 0; if(L.len==1) return 1; return -1; } int legendre() const { return legendre(*this); } bool sqrt(const gfield &x) { if(!x.len) { len = 0; return true; } #if GF_BITS==224 #error Unsupported GF #else ASSERT((P.digits[0]%4)==3); static const gfint Padd1div4(gfint(P).add(bigint<1>(1)).rshift(2)); switch(legendre(x)) { case 0: len = 0; return true; case -1: return false; default: pow(x, Padd1div4); return true; } #endif } bool sqrt() { return sqrt(*this); } }; struct ecjacobian { static const gfield B; static const ecjacobian base; static const ecjacobian origin; gfield x, y, z; ecjacobian() {} ecjacobian(const gfield &x, const gfield &y) : x(x), y(y), z(bigint<1>(1)) {} ecjacobian(const gfield &x, const gfield &y, const gfield &z) : x(x), y(y), z(z) {} void mul2() { if(z.iszero()) return; else if(y.iszero()) { *this = origin; return; } gfield a, b, c, d; d.sub(x, c.square(z)); d.mul(c.add(x)); c.mul2(d).add(d); z.mul(y).add(z); a.square(y); b.mul2(a); d.mul2(x).mul(b); x.square(c).sub(d).sub(d); a.square(b).add(a); y.sub(d, x).mul(c).sub(a); } void add(const ecjacobian &q) { if(q.z.iszero()) return; else if(z.iszero()) { *this = q; return; } gfield a, b, c, d, e, f; a.square(z); b.mul(q.y, a).mul(z); a.mul(q.x); if(q.z.isone()) { c.add(x, a); d.add(y, b); a.sub(x, a); b.sub(y, b); } else { f.mul(y, e.square(q.z)).mul(q.z); e.mul(x); c.add(e, a); d.add(f, b); a.sub(e, a); b.sub(f, b); } if(a.iszero()) { if(b.iszero()) mul2(); else *this = origin; return; } if(!q.z.isone()) z.mul(q.z); z.mul(a); x.square(b).sub(f.mul(c, e.square(a))); y.sub(f, x).sub(x).mul(b).sub(e.mul(a).mul(d)).div2(); } template void mul(const ecjacobian &p, const bigint q) { *this = origin; for(int i = q.numbits()-1; i >= 0; i--) { mul2(); if(q.hasbit(i)) add(p); } } template void mul(const bigint q) { ecjacobian tmp(*this); mul(tmp, q); } void normalize() { if(z.iszero() || z.isone()) return; gfield tmp; z.invert(); tmp.square(z); x.mul(tmp); y.mul(tmp).mul(z); z = bigint<1>(1); } bool calcy(bool ybit) { gfield y2, tmp; y2.square(x).mul(x).sub(tmp.add(x, x).add(x)).add(B); if(!y.sqrt(y2)) { y.zero(); return false; } if(y.hasbit(0) != ybit) y.neg(); return true; } void print(vector &buf) { normalize(); buf.add(y.hasbit(0) ? '-' : '+'); x.printdigits(buf); } void parse(const char *s) { bool ybit = *s++ == '-'; x.parse(s); calcy(ybit); z = bigint<1>(1); } }; const ecjacobian ecjacobian::origin(gfield((gfield::digit)1), gfield((gfield::digit)1), gfield((gfield::digit)0)); #if GF_BITS==192 const gfield gfield::P("fffffffffffffffffffffffffffffffeffffffffffffffff"); const gfield ecjacobian::B("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1"); const ecjacobian ecjacobian::base( gfield("188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012"), gfield("07192b95ffc8da78631011ed6b24cdd573f977a11e794811") ); #elif GF_BITS==224 const gfield gfield::P("ffffffffffffffffffffffffffffffff000000000000000000000001"); const gfield ecjacobian::B("b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4"); const ecjacobian ecjacobian::base( gfield("b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21"), gfield("bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34"), ); #elif GF_BITS==256 const gfield gfield::P("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff"); const gfield ecjacobian::B("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"); const ecjacobian ecjacobian::base( gfield("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"), gfield("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"), ); #elif GF_BITS==384 const gfield gfield::P("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"); const gfield ecjacobian::B("b3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"); const ecjacobian ecjacobian::base( gfield("aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"), gfield("3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"), ); #elif GF_BITS==521 const gfield gfield::P("1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); const gfield ecjacobian::B("051953eb968e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"); const ecjacobian ecjacobian::base( gfield("c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"), gfield("11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650") ); #else #error Unsupported GF #endif void genprivkey(const char *seed, vector &privstr, vector &pubstr) { tiger::hashval hash; tiger::hash((const uchar *)seed, (int)strlen(seed), hash); bigint<8*sizeof(hash.bytes)/BI_DIGIT_BITS> privkey; memcpy(privkey.digits, hash.bytes, sizeof(hash.bytes)); privkey.len = 8*sizeof(hash.bytes)/BI_DIGIT_BITS; privkey.shrink(); privkey.printdigits(privstr); privstr.add('\0'); ecjacobian c(ecjacobian::base); c.mul(privkey); c.normalize(); c.print(pubstr); pubstr.add('\0'); } bool hashstring(const char *str, char *result, int maxlen) { tiger::hashval hv; if(maxlen < 2*(int)sizeof(hv.bytes) + 1) return false; tiger::hash((uchar *)str, strlen(str), hv); loopi(sizeof(hv.bytes)) { uchar c = hv.bytes[i]; *result++ = "0123456789abcdef"[c&0xF]; *result++ = "0123456789abcdef"[c>>4]; } *result = '\0'; return true; } void answerchallenge(const char *privstr, const char *challenge, vector &answerstr) { gfint privkey; privkey.parse(privstr); ecjacobian answer; answer.parse(challenge); answer.mul(privkey); answer.normalize(); answer.x.printdigits(answerstr); answerstr.add('\0'); } void *parsepubkey(const char *pubstr) { ecjacobian *pubkey = new ecjacobian; pubkey->parse(pubstr); return pubkey; } void freepubkey(void *pubkey) { delete (ecjacobian *)pubkey; } void *genchallenge(void *pubkey, const void *seed, int seedlen, vector &challengestr) { tiger::hashval hash; tiger::hash((const uchar *)seed, sizeof(seed), hash); gfint challenge; memcpy(challenge.digits, hash.bytes, sizeof(hash.bytes)); challenge.len = 8*sizeof(hash.bytes)/BI_DIGIT_BITS; challenge.shrink(); ecjacobian answer(*(ecjacobian *)pubkey); answer.mul(challenge); answer.normalize(); ecjacobian secret(ecjacobian::base); secret.mul(challenge); secret.normalize(); secret.print(challengestr); challengestr.add('\0'); return new gfield(answer.x); } void freechallenge(void *answer) { delete (gfint *)answer; } bool checkchallenge(const char *answerstr, void *correct) { gfint answer(answerstr); return answer == *(gfint *)correct; } sauerbraten-0.0.20130203.dfsg/shared/tools.cpp0000644000175000017500000001053312072027322020506 0ustar vincentvincent// implementation of generic tools #include "cube.h" #ifndef WIN32 #include #endif int guessnumcpus() { int numcpus = 1; #ifdef WIN32 SYSTEM_INFO info; GetSystemInfo(&info); numcpus = (int)info.dwNumberOfProcessors; #elif defined(_SC_NPROCESSORS_ONLN) numcpus = (int)sysconf(_SC_NPROCESSORS_ONLN); #endif return max(numcpus, 1); } ////////////////////////// rnd numbers //////////////////////////////////////// #define N (624) #define M (397) #define K (0x9908B0DFU) static uint state[N]; static int next = N; void seedMT(uint seed) { state[0] = seed; for(uint i = 1; i < N; i++) state[i] = seed = 1812433253U * (seed ^ (seed >> 30)) + i; next = 0; } uint randomMT() { int cur = next; if(++next >= N) { if(next > N) { seedMT(5489U + time(NULL)); cur = next++; } else next = 0; } uint y = (state[cur] & 0x80000000U) | (state[next] & 0x7FFFFFFFU); state[cur] = y = state[cur < N-M ? cur + M : cur + M-N] ^ (y >> 1) ^ (-int(y & 1U) & K); y ^= (y >> 11); y ^= (y << 7) & 0x9D2C5680U; y ^= (y << 15) & 0xEFC60000U; y ^= (y >> 18); return y; } ///////////////////////// network /////////////////////// // all network traffic is in 32bit ints, which are then compressed using the following simple scheme (assumes that most values are small). template static inline void putint_(T &p, int n) { if(n<128 && n>-127) p.put(n); else if(n<0x8000 && n>=-0x8000) { p.put(0x80); p.put(n); p.put(n>>8); } else { p.put(0x81); p.put(n); p.put(n>>8); p.put(n>>16); p.put(n>>24); } } void putint(ucharbuf &p, int n) { putint_(p, n); } void putint(packetbuf &p, int n) { putint_(p, n); } void putint(vector &p, int n) { putint_(p, n); } int getint(ucharbuf &p) { int c = (char)p.get(); if(c==-128) { int n = p.get(); n |= char(p.get())<<8; return n; } else if(c==-127) { int n = p.get(); n |= p.get()<<8; n |= p.get()<<16; return n|(p.get()<<24); } else return c; } // much smaller encoding for unsigned integers up to 28 bits, but can handle signed template static inline void putuint_(T &p, int n) { if(n < 0 || n >= (1<<21)) { p.put(0x80 | (n & 0x7F)); p.put(0x80 | ((n >> 7) & 0x7F)); p.put(0x80 | ((n >> 14) & 0x7F)); p.put(n >> 21); } else if(n < (1<<7)) p.put(n); else if(n < (1<<14)) { p.put(0x80 | (n & 0x7F)); p.put(n >> 7); } else { p.put(0x80 | (n & 0x7F)); p.put(0x80 | ((n >> 7) & 0x7F)); p.put(n >> 14); } } void putuint(ucharbuf &p, int n) { putuint_(p, n); } void putuint(packetbuf &p, int n) { putuint_(p, n); } void putuint(vector &p, int n) { putuint_(p, n); } int getuint(ucharbuf &p) { int n = p.get(); if(n & 0x80) { n += (p.get() << 7) - 0x80; if(n & (1<<14)) n += (p.get() << 14) - (1<<14); if(n & (1<<21)) n += (p.get() << 21) - (1<<21); if(n & (1<<28)) n |= -1<<28; } return n; } template static inline void putfloat_(T &p, float f) { lilswap(&f, 1); p.put((uchar *)&f, sizeof(float)); } void putfloat(ucharbuf &p, float f) { putfloat_(p, f); } void putfloat(packetbuf &p, float f) { putfloat_(p, f); } void putfloat(vector &p, float f) { putfloat_(p, f); } float getfloat(ucharbuf &p) { float f; p.get((uchar *)&f, sizeof(float)); return lilswap(f); } template static inline void sendstring_(const char *t, T &p) { while(*t) putint(p, *t++); putint(p, 0); } void sendstring(const char *t, ucharbuf &p) { sendstring_(t, p); } void sendstring(const char *t, packetbuf &p) { sendstring_(t, p); } void sendstring(const char *t, vector &p) { sendstring_(t, p); } void getstring(char *text, ucharbuf &p, int len) { char *t = text; do { if(t>=&text[len]) { text[len-1] = 0; return; } if(!p.remaining()) { *t = 0; return; } *t = getint(p); } while(*t++); } void filtertext(char *dst, const char *src, bool whitespace, int len) { for(int c = uchar(*src); c; c = uchar(*++src)) { if(c == '\f') { if(!*++src) break; continue; } if(iscubeprint(c) || (iscubespace(c) && whitespace)) { *dst++ = c; if(!--len) break; } } *dst = '\0'; } sauerbraten-0.0.20130203.dfsg/shared/command.h0000644000175000017500000003120312067262417020440 0ustar vincentvincent// script binding functionality enum { VAL_NULL = 0, VAL_INT, VAL_FLOAT, VAL_STR, VAL_ANY, VAL_CODE, VAL_MACRO, VAL_IDENT }; enum { CODE_START = 0, CODE_OFFSET, CODE_POP, CODE_ENTER, CODE_EXIT, CODE_VAL, CODE_VALI, CODE_MACRO, CODE_BOOL, CODE_BLOCK, CODE_COMPILE, CODE_FORCE, CODE_RESULT, CODE_IDENT, CODE_IDENTU, CODE_IDENTARG, CODE_COM, CODE_COMD, CODE_COMC, CODE_COMV, CODE_CONC, CODE_CONCW, CODE_CONCM, CODE_DOWN, CODE_SVAR, CODE_SVAR1, CODE_IVAR, CODE_IVAR1, CODE_IVAR2, CODE_IVAR3, CODE_FVAR, CODE_FVAR1, CODE_LOOKUP, CODE_LOOKUPU, CODE_LOOKUPARG, CODE_ALIAS, CODE_ALIASU, CODE_ALIASARG, CODE_CALL, CODE_CALLU, CODE_CALLARG, CODE_PRINT, CODE_LOCAL, CODE_OP_MASK = 0x3F, CODE_RET = 6, CODE_RET_MASK = 0xC0, /* return type flags */ RET_NULL = VAL_NULL< x ? IDF_READONLY : 0)) { storage.i = s; } // ID_FVAR ident(int t, const char *n, float m, float x, float *s, void *f = NULL, int flags = 0) : type(t), name(n), minvalf(m), maxvalf(x), fun((identfun)f), flags(flags | (m > x ? IDF_READONLY : 0)) { storage.f = s; } // ID_SVAR ident(int t, const char *n, char **s, void *f = NULL, int flags = 0) : type(t), name(n), fun((identfun)f), flags(flags) { storage.s = s; } // ID_ALIAS ident(int t, const char *n, char *a, int flags) : type(t), name(n), valtype(VAL_STR), code(NULL), stack(NULL), flags(flags) { val.s = a; } ident(int t, const char *n, int a, int flags) : type(t), name(n), valtype(VAL_INT), code(NULL), stack(NULL), flags(flags) { val.i = a; } ident(int t, const char *n, float a, int flags) : type(t), name(n), valtype(VAL_FLOAT), code(NULL), stack(NULL), flags(flags) { val.f = a; } ident(int t, const char *n, int flags) : type(t), name(n), valtype(VAL_NULL), code(NULL), stack(NULL), flags(flags) {} ident(int t, const char *n, const tagval &v, int flags) : type(t), name(n), valtype(v.type), code(NULL), stack(NULL), flags(flags) { val = v; } // ID_COMMAND ident(int t, const char *n, const char *args, uint argmask, void *f = NULL, int flags = 0) : type(t), name(n), args(args), argmask(argmask), fun((identfun)f), flags(flags) {} void changed() { if(fun) fun(); } void setval(const tagval &v) { valtype = v.type; val = v; } void setval(const identstack &v) { valtype = v.valtype; val = v.val; } void forcenull() { if(valtype==VAL_STR) delete[] val.s; valtype = VAL_NULL; } float getfloat() const; int getint() const; const char *getstr() const; void getval(tagval &v) const; }; static inline bool htcmp(const char *key, const ident &id) { return !strcmp(key, id.name); } extern void addident(ident *id); extern tagval *commandret; extern const char *intstr(int v); extern void intret(int v); extern const char *floatstr(float v); extern void floatret(float v); extern void stringret(char *s); extern void result(tagval &v); extern void result(const char *s); static inline int parseint(const char *s) { return int(strtol(s, NULL, 0)); } static inline float parsefloat(const char *s) { // not all platforms (windows) can parse hexadecimal integers via strtod char *end; double val = strtod(s, &end); return val || end==s || (*end!='x' && *end!='X') ? float(val) : float(parseint(s)); } static inline const char *getstr(const identval &v, int type) { switch(type) { case VAL_STR: case VAL_MACRO: return v.s; case VAL_INT: return intstr(v.i); case VAL_FLOAT: return floatstr(v.f); default: return ""; } } inline const char *tagval::getstr() const { return ::getstr(*this, type); } inline const char *ident::getstr() const { return ::getstr(val, valtype); } static inline int getint(const identval &v, int type) { switch(type) { case VAL_INT: return v.i; case VAL_FLOAT: return int(v.f); case VAL_STR: case VAL_MACRO: return parseint(v.s); default: return 0; } } inline int tagval::getint() const { return ::getint(*this, type); } inline int ident::getint() const { return ::getint(val, valtype); } static inline float getfloat(const identval &v, int type) { switch(type) { case VAL_FLOAT: return v.f; case VAL_INT: return float(v.i); case VAL_STR: case VAL_MACRO: return parsefloat(v.s); default: return 0.0f; } } inline float tagval::getfloat() const { return ::getfloat(*this, type); } inline float ident::getfloat() const { return ::getfloat(val, valtype); } inline void ident::getval(tagval &v) const { switch(valtype) { case VAL_STR: case VAL_MACRO: v.setstr(newstring(val.s)); break; case VAL_INT: v.setint(val.i); break; case VAL_FLOAT: v.setfloat(val.f); break; default: v.setnull(); break; } } // nasty macros for registering script functions, abuses globals to avoid excessive infrastructure #define KEYWORD(name, type) static bool __dummy_##name = addkeyword(type, #name) #define COMMANDN(name, fun, nargs) static bool __dummy_##fun = addcommand(#name, (identfun)fun, nargs) #define COMMAND(name, nargs) COMMANDN(name, name, nargs) #define _VAR(name, global, min, cur, max, persist) int global = variable(#name, min, cur, max, &global, NULL, persist) #define VARN(name, global, min, cur, max) _VAR(name, global, min, cur, max, 0) #define VARNP(name, global, min, cur, max) _VAR(name, global, min, cur, max, IDF_PERSIST) #define VARNR(name, global, min, cur, max) _VAR(name, global, min, cur, max, IDF_OVERRIDE) #define VAR(name, min, cur, max) _VAR(name, name, min, cur, max, 0) #define VARP(name, min, cur, max) _VAR(name, name, min, cur, max, IDF_PERSIST) #define VARR(name, min, cur, max) _VAR(name, name, min, cur, max, IDF_OVERRIDE) #define _VARF(name, global, min, cur, max, body, persist) void var_##name(); int global = variable(#name, min, cur, max, &global, var_##name, persist); void var_##name() { body; } #define VARFN(name, global, min, cur, max, body) _VARF(name, global, min, cur, max, body, 0) #define VARF(name, min, cur, max, body) _VARF(name, name, min, cur, max, body, 0) #define VARFP(name, min, cur, max, body) _VARF(name, name, min, cur, max, body, IDF_PERSIST) #define VARFR(name, min, cur, max, body) _VARF(name, name, min, cur, max, body, IDF_OVERRIDE) #define _HVAR(name, global, min, cur, max, persist) int global = variable(#name, min, cur, max, &global, NULL, persist | IDF_HEX) #define HVARN(name, global, min, cur, max) _HVAR(name, global, min, cur, max, 0) #define HVARNP(name, global, min, cur, max) _HVAR(name, global, min, cur, max, IDF_PERSIST) #define HVARNR(name, global, min, cur, max) _HVAR(name, global, min, cur, max, IDF_OVERRIDE) #define HVAR(name, min, cur, max) _HVAR(name, name, min, cur, max, 0) #define HVARP(name, min, cur, max) _HVAR(name, name, min, cur, max, IDF_PERSIST) #define HVARR(name, min, cur, max) _HVAR(name, name, min, cur, max, IDF_OVERRIDE) #define _HVARF(name, global, min, cur, max, body, persist) void var_##name(); int global = variable(#name, min, cur, max, &global, var_##name, persist | IDF_HEX); void var_##name() { body; } #define HVARFN(name, global, min, cur, max, body) _HVARF(name, global, min, cur, max, body, 0) #define HVARF(name, min, cur, max, body) _HVARF(name, name, min, cur, max, body, 0) #define HVARFP(name, min, cur, max, body) _HVARF(name, name, min, cur, max, body, IDF_PERSIST) #define HVARFR(name, min, cur, max, body) _HVARF(name, name, min, cur, max, body, IDF_OVERRIDE) #define _FVAR(name, global, min, cur, max, persist) float global = fvariable(#name, min, cur, max, &global, NULL, persist) #define FVARN(name, global, min, cur, max) _FVAR(name, global, min, cur, max, 0) #define FVARNP(name, global, min, cur, max) _FVAR(name, global, min, cur, max, IDF_PERSIST) #define FVARNR(name, global, min, cur, max) _FVAR(name, global, min, cur, max, IDF_OVERRIDE) #define FVAR(name, min, cur, max) _FVAR(name, name, min, cur, max, 0) #define FVARP(name, min, cur, max) _FVAR(name, name, min, cur, max, IDF_PERSIST) #define FVARR(name, min, cur, max) _FVAR(name, name, min, cur, max, IDF_OVERRIDE) #define _FVARF(name, global, min, cur, max, body, persist) void var_##name(); float global = fvariable(#name, min, cur, max, &global, var_##name, persist); void var_##name() { body; } #define FVARFN(name, global, min, cur, max, body) _FVARF(name, global, min, cur, max, body, 0) #define FVARF(name, min, cur, max, body) _FVARF(name, name, min, cur, max, body, 0) #define FVARFP(name, min, cur, max, body) _FVARF(name, name, min, cur, max, body, IDF_PERSIST) #define FVARFR(name, min, cur, max, body) _FVARF(name, name, min, cur, max, body, IDF_OVERRIDE) #define _SVAR(name, global, cur, persist) char *global = svariable(#name, cur, &global, NULL, persist) #define SVARN(name, global, cur) _SVAR(name, global, cur, 0) #define SVARNP(name, global, cur) _SVAR(name, global, cur, IDF_PERSIST) #define SVARNR(name, global, cur) _SVAR(name, global, cur, IDF_OVERRIDE) #define SVAR(name, cur) _SVAR(name, name, cur, 0) #define SVARP(name, cur) _SVAR(name, name, cur, IDF_PERSIST) #define SVARR(name, cur) _SVAR(name, name, cur, IDF_OVERRIDE) #define _SVARF(name, global, cur, body, persist) void var_##name(); char *global = svariable(#name, cur, &global, var_##name, persist); void var_##name() { body; } #define SVARFN(name, global, cur, body) _SVARF(name, global, cur, body, 0) #define SVARF(name, cur, body) _SVARF(name, name, cur, body, 0) #define SVARFP(name, cur, body) _SVARF(name, name, cur, body, IDF_PERSIST) #define SVARFR(name, cur, body) _SVARF(name, name, cur, body, IDF_OVERRIDE) // anonymous inline commands, uses nasty template trick with line numbers to keep names unique #define ICOMMANDNS(name, cmdname, nargs, proto, b) template struct cmdname; template<> struct cmdname<__LINE__> { static bool init; static void run proto; }; bool cmdname<__LINE__>::init = addcommand(name, (identfun)cmdname<__LINE__>::run, nargs); void cmdname<__LINE__>::run proto \ { b; } #define ICOMMANDN(name, cmdname, nargs, proto, b) ICOMMANDNS(#name, cmdname, nargs, proto, b) #define ICOMMANDNAME(name) _icmd_##name #define ICOMMAND(name, nargs, proto, b) ICOMMANDN(name, ICOMMANDNAME(name), nargs, proto, b) #define ICOMMANDSNAME _icmds_ #define ICOMMANDS(name, nargs, proto, b) ICOMMANDNS(name, ICOMMANDSNAME, nargs, proto, b) sauerbraten-0.0.20130203.dfsg/shared/geom.h0000644000175000017500000012761312057466657017777 0ustar vincentvincentstruct vec4; struct vec2; struct vec { union { struct { float x, y, z; }; struct { float r, g, b; }; float v[3]; }; vec() {} explicit vec(int a) : x(a), y(a), z(a) {} explicit vec(float a) : x(a), y(a), z(a) {} vec(float a, float b, float c) : x(a), y(b), z(c) {} explicit vec(int v[3]) : x(v[0]), y(v[1]), z(v[2]) {} explicit vec(float *v) : x(v[0]), y(v[1]), z(v[2]) {} explicit vec(const vec4 &v); explicit vec(const vec2 &v, float z = 0); vec(float yaw, float pitch) : x(-sinf(yaw)*cosf(pitch)), y(cosf(yaw)*cosf(pitch)), z(sinf(pitch)) {} float &operator[](int i) { return v[i]; } float operator[](int i) const { return v[i]; } vec &set(int i, float f) { v[i] = f; return *this; } bool operator==(const vec &o) const { return x == o.x && y == o.y && z == o.z; } bool operator!=(const vec &o) const { return x != o.x || y != o.y || z != o.z; } bool iszero() const { return x==0 && y==0 && z==0; } float squaredlen() const { return x*x + y*y + z*z; } float dot2(const vec &o) const { return x*o.x + y*o.y; } float dot(const vec &o) const { return x*o.x + y*o.y + z*o.z; } vec &mul(const vec &o) { x *= o.x; y *= o.y; z *= o.z; return *this; } vec &mul(float f) { x *= f; y *= f; z *= f; return *this; } vec &div(const vec &o) { x /= o.x; y /= o.y; z /= o.z; return *this; } vec &div(float f) { x /= f; y /= f; z /= f; return *this; } vec &add(const vec &o) { x += o.x; y += o.y; z += o.z; return *this; } vec &add(float f) { x += f; y += f; z += f; return *this; } vec &sub(const vec &o) { x -= o.x; y -= o.y; z -= o.z; return *this; } vec &sub(float f) { x -= f; y -= f; z -= f; return *this; } vec &neg2() { x = -x; y = -y; return *this; } vec &neg() { x = -x; y = -y; z = -z; return *this; } vec &min(const vec &o) { x = ::min(x, o.x); y = ::min(y, o.y); z = ::min(z, o.z); return *this; } vec &max(const vec &o) { x = ::max(x, o.x); y = ::max(y, o.y); z = ::max(z, o.z); return *this; } vec &min(float f) { x = ::min(x, f); y = ::min(y, f); z = ::min(z, f); return *this; } vec &max(float f) { x = ::max(x, f); y = ::max(y, f); z = ::max(z, f); return *this; } vec &clamp(float f, float h) { x = ::clamp(x, f, h); y = ::clamp(y, f, h); z = ::clamp(z, f, h); return *this; } float magnitude2() const { return sqrtf(dot2(*this)); } float magnitude() const { return sqrtf(squaredlen()); } vec &normalize() { div(magnitude()); return *this; } bool isnormalized() const { float m = squaredlen(); return (m>0.99f && m<1.01f); } float squaredist(const vec &e) const { return vec(*this).sub(e).squaredlen(); } float dist(const vec &e) const { vec t; return dist(e, t); } float dist(const vec &e, vec &t) const { t = *this; t.sub(e); return t.magnitude(); } float dist2(const vec &o) const { float dx = x-o.x, dy = y-o.y; return sqrtf(dx*dx + dy*dy); } bool reject(const vec &o, float r) { return x>o.x+r || xo.y+r || y vec &cross(const A &a, const B &b) { x = a.y*b.z-a.z*b.y; y = a.z*b.x-a.x*b.z; z = a.x*b.y-a.y*b.x; return *this; } vec &cross(const vec &o, const vec &a, const vec &b) { return cross(vec(a).sub(o), vec(b).sub(o)); } float scalartriple(const vec &a, const vec &b) const { return x*(a.y*b.z-a.z*b.y) + y*(a.z*b.x-a.x*b.z) + z*(a.x*b.y-a.y*b.x); } vec &reflectz(float rz) { z = 2*rz - z; return *this; } vec &reflect(const vec &n) { float k = 2*dot(n); x -= k*n.x; y -= k*n.y; z -= k*n.z; return *this; } vec &project(const vec &n) { float k = dot(n); x -= k*n.x; y -= k*n.y; z -= k*n.z; return *this; } vec &projectxydir(const vec &n) { if(n.z) z = -(x*n.x/n.z + y*n.y/n.z); return *this; } vec &projectxy(const vec &n) { float m = squaredlen(), k = dot(n); projectxydir(n); rescale(sqrtf(::max(m - k*k, 0.0f))); return *this; } vec &projectxy(const vec &n, float threshold) { float m = squaredlen(), k = ::min(dot(n), threshold); projectxydir(n); rescale(sqrtf(::max(m - k*k, 0.0f))); return *this; } vec &lerp(const vec &b, float t) { x += (b.x-x)*t; y += (b.y-y)*t; z += (b.z-z)*t; return *this; } vec &lerp(const vec &a, const vec &b, float t) { x = a.x + (b.x-a.x)*t; y = a.y + (b.y-a.y)*t; z = a.z + (b.z-a.z)*t; return *this; } vec &rescale(float k) { float mag = magnitude(); if(mag > 1e-6f) mul(k / mag); return *this; } vec &rotate_around_z(float c, float s) { float rx = x, ry = y; x = c*rx-s*ry; y = c*ry+s*rx; return *this; } vec &rotate_around_x(float c, float s) { float ry = y, rz = z; y = c*ry-s*rz; z = c*rz+s*ry; return *this; } vec &rotate_around_y(float c, float s) { float rx = x, rz = z; x = c*rx-s*rz; z = c*rz+s*rx; return *this; } vec &rotate_around_z(float angle) { return rotate_around_z(cosf(angle), sinf(angle)); } vec &rotate_around_x(float angle) { return rotate_around_x(cosf(angle), sinf(angle)); } vec &rotate_around_y(float angle) { return rotate_around_y(cosf(angle), sinf(angle)); } vec &rotate(float angle, const vec &d) { float c = cosf(angle), s = sinf(angle); return rotate(c, s, d); } vec &rotate(float c, float s, const vec &d) { *this = vec(x*(d.x*d.x*(1-c)+c) + y*(d.x*d.y*(1-c)-d.z*s) + z*(d.x*d.z*(1-c)+d.y*s), x*(d.y*d.x*(1-c)+d.z*s) + y*(d.y*d.y*(1-c)+c) + z*(d.y*d.z*(1-c)-d.x*s), x*(d.x*d.z*(1-c)-d.y*s) + y*(d.y*d.z*(1-c)+d.x*s) + z*(d.z*d.z*(1-c)+c)); return *this; } void orthogonal(const vec &d) { int i = fabs(d.x) > fabs(d.y) ? (fabs(d.x) > fabs(d.z) ? 0 : 2) : (fabs(d.y) > fabs(d.z) ? 1 : 2); v[i] = d[(i+1)%3]; v[(i+1)%3] = -d[i]; v[(i+2)%3] = 0; } void orthonormalize(vec &s, vec &t) const { s.sub(vec(*this).mul(dot(s))); t.sub(vec(*this).mul(dot(t))) .sub(vec(s).mul(s.dot(t))); } template float dist_to_bb(const T &min, const T &max) const { float sqrdist = 0; loopi(3) { if (v[i] < min[i]) { float delta = v[i]-min[i]; sqrdist += delta*delta; } else if(v[i] > max[i]) { float delta = max[i]-v[i]; sqrdist += delta*delta; } } return sqrtf(sqrdist); } template float dist_to_bb(const T &o, S size) const { return dist_to_bb(o, T(o).add(size)); } }; static inline bool htcmp(const vec &x, const vec &y) { return x == y; } static inline uint hthash(const vec &k) { union { uint i; float f; } x, y, z; x.f = k.x; y.f = k.y; z.f = k.z; uint v = x.i^y.i^z.i; return v + (v>>12); } struct vec4 { union { struct { float x, y, z, w; }; float v[4]; }; vec4() {} explicit vec4(const vec &p, float w = 0) : x(p.x), y(p.y), z(p.z), w(w) {} vec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {} float &operator[](int i) { return v[i]; } float operator[](int i) const { return v[i]; } float dot3(const vec4 &o) const { return x*o.x + y*o.y + z*o.z; } float dot3(const vec &o) const { return x*o.x + y*o.y + z*o.z; } float dot(const vec4 &o) const { return dot3(o) + w*o.w; } float dot(const vec &o) const { return x*o.x + y*o.y + z*o.z + w; } float squaredlen() const { return dot(*this); } float magnitude() const { return sqrtf(squaredlen()); } float magnitude3() const { return sqrtf(dot3(*this)); } vec4 &normalize() { mul(1/magnitude()); return *this; } vec4 &lerp(const vec4 &b, float t) { x += (b.x-x)*t; y += (b.y-y)*t; z += (b.z-z)*t; w += (b.w-w)*t; return *this; } vec4 &lerp(const vec4 &a, const vec4 &b, float t) { x = a.x+(b.x-a.x)*t; y = a.y+(b.y-a.y)*t; z = a.z+(b.z-a.z)*t; w = a.w+(b.w-a.w)*t; return *this; } vec4 &mul3(float f) { x *= f; y *= f; z *= f; return *this; } vec4 &mul(float f) { mul3(f); w *= f; return *this; } vec4 &mul(const vec4 &o) { x *= o.x; y *= o.y; z *= o.z; w *= o.w; return *this; } vec4 &div3(float f) { x /= f; y /= f; z /= f; return *this; } vec4 &div(float f) { div3(f); w /= f; return *this; } vec4 &div(const vec4 &o) { x /= o.x; y /= o.y; z /= o.z; w /= o.w; return *this; } vec4 &add(const vec4 &o) { x += o.x; y += o.y; z += o.z; w += o.w; return *this; } vec4 &addw(float f) { w += f; return *this; } vec4 &sub(const vec4 &o) { x -= o.x; y -= o.y; z -= o.z; w -= o.w; return *this; } vec4 &subw(float f) { w -= f; return *this; } vec4 &neg3() { x = -x; y = -y; z = -z; return *this; } vec4 &neg() { neg3(); w = -w; return *this; } void setxyz(const vec &v) { x = v.x; y = v.y; z = v.z; } }; inline vec::vec(const vec4 &v) : x(v.x), y(v.y), z(v.z) {} struct vec2 { union { struct { float x, y; }; float v[2]; }; vec2() {} vec2(float x, float y) : x(x), y(y) {} explicit vec2(const vec &v) : x(v.x), y(v.y) {} explicit vec2(const vec4 &v) : x(v.x), y(v.y) {} float &operator[](int i) { return v[i]; } float operator[](int i) const { return v[i]; } bool operator==(const vec2 &o) const { return x == o.x && y == o.y; } bool operator!=(const vec2 &o) const { return x != o.x || y != o.y; } bool iszero() const { return x==0 && y==0; } float dot(const vec2 &o) const { return x*o.x + y*o.y; } float squaredlen() const { return dot(*this); } float magnitude() const { return sqrtf(squaredlen()); } vec2 &normalize() { mul(1/magnitude()); return *this; } float cross(const vec2 &o) const { return x*o.y - y*o.x; } vec2 &mul(float f) { x *= f; y *= f; return *this; } vec2 &mul(const vec2 &o) { x *= o.x; y *= o.y; return *this; } vec2 &div(float f) { x /= f; y /= f; return *this; } vec2 &div(const vec2 &o) { x /= o.x; y /= o.y; return *this; } vec2 &add(float f) { x += f; y += f; return *this; } vec2 &add(const vec2 &o) { x += o.x; y += o.y; return *this; } vec2 &sub(float f) { x -= f; y -= f; return *this; } vec2 &sub(const vec2 &o) { x -= o.x; y -= o.y; return *this; } vec2 &neg() { x = -x; y = -y; return *this; } }; inline vec::vec(const vec2 &v, float z) : x(v.x), y(v.y), z(z) {} static inline bool htcmp(const vec2 &x, const vec2 &y) { return x == y; } static inline uint hthash(const vec2 &k) { union { uint i; float f; } x, y; x.f = k.x; y.f = k.y; uint v = x.i^y.i; return v + (v>>12); } struct matrix3x3; struct matrix3x4; struct quat : vec4 { quat() {} quat(float x, float y, float z, float w) : vec4(x, y, z, w) {} quat(const vec &axis, float angle) { w = cosf(angle/2); float s = sinf(angle/2); x = s*axis.x; y = s*axis.y; z = s*axis.z; } explicit quat(const vec &v) { x = v.x; y = v.y; z = v.z; restorew(); } explicit quat(const matrix3x3 &m) { convertmatrix(m); } explicit quat(const matrix3x4 &m) { convertmatrix(m); } void restorew() { w = 1.0f-x*x-y*y-z*z; w = w<0 ? 0 : -sqrtf(w); } quat &add(const vec4 &o) { vec4::add(o); return *this; } quat &sub(const vec4 &o) { vec4::sub(o); return *this; } quat &mul(float k) { vec4::mul(k); return *this; } quat &mul(const quat &p, const quat &o) { x = p.w*o.x + p.x*o.w + p.y*o.z - p.z*o.y; y = p.w*o.y - p.x*o.z + p.y*o.w + p.z*o.x; z = p.w*o.z + p.x*o.y - p.y*o.x + p.z*o.w; w = p.w*o.w - p.x*o.x - p.y*o.y - p.z*o.z; return *this; } quat &mul(const quat &o) { return mul(quat(*this), o); } quat &invert() { neg3(); return *this; } void calcangleaxis(float &angle, vec &axis) { float rr = dot3(*this); if(rr>0) { angle = 2*acosf(w); axis = vec(x, y, z).mul(1/rr); } else { angle = 0; axis = vec(0, 0, 1); } } vec rotate(const vec &v) const { return vec().cross(*this, vec().cross(*this, v).add(vec(v).mul(w))).mul(2).add(v); } vec invertedrotate(const vec &v) const { return vec().cross(*this, vec().cross(*this, v).sub(vec(v).mul(w))).mul(2).add(v); } template void convertmatrix(const M &m) { float trace = m.a.x + m.b.y + m.c.z; if(trace>0) { float r = sqrtf(1 + trace), inv = 0.5f/r; w = 0.5f*r; x = (m.c.y - m.b.z)*inv; y = (m.a.z - m.c.x)*inv; z = (m.b.x - m.a.y)*inv; } else if(m.a.x > m.b.y && m.a.x > m.c.z) { float r = sqrtf(1 + m.a.x - m.b.y - m.c.z), inv = 0.5f/r; x = 0.5f*r; y = (m.b.x + m.a.y)*inv; z = (m.a.z + m.c.x)*inv; w = (m.c.y - m.b.z)*inv; } else if(m.b.y > m.c.z) { float r = sqrtf(1 + m.b.y - m.a.x - m.c.z), inv = 0.5f/r; x = (m.b.x + m.a.y)*inv; y = 0.5f*r; z = (m.c.y + m.b.z)*inv; w = (m.a.z - m.c.x)*inv; } else { float r = sqrtf(1 + m.c.z - m.a.x - m.b.y), inv = 0.5f/r; x = (m.a.z + m.c.x)*inv; y = (m.c.y + m.b.z)*inv; z = 0.5f*r; w = (m.b.x - m.a.y)*inv; } } }; struct dualquat { quat real, dual; dualquat() {} dualquat(const quat &q, const vec &p) : real(q), dual(0.5f*( p.x*q.w + p.y*q.z - p.z*q.y), 0.5f*(-p.x*q.z + p.y*q.w + p.z*q.x), 0.5f*( p.x*q.y - p.y*q.x + p.z*q.w), -0.5f*( p.x*q.x + p.y*q.y + p.z*q.z)) { } explicit dualquat(const quat &q) : real(q), dual(0, 0, 0, 0) {} explicit dualquat(const matrix3x4 &m); dualquat &mul(float k) { real.mul(k); dual.mul(k); return *this; } dualquat &add(const dualquat &d) { real.add(d.real); dual.add(d.dual); return *this; } dualquat &lerp(const dualquat &to, float t) { float k = real.dot(to.real) < 0 ? -t : t; real.mul(1-t).add(vec4(to.real).mul(k)); dual.mul(1-t).add(vec4(to.dual).mul(k)); return *this; } dualquat &lerp(const dualquat &from, const dualquat &to, float t) { float k = from.real.dot(to.real) < 0 ? -t : t; (real = from.real).mul(1-t).add(vec4(to.real).mul(k)); (dual = from.dual).mul(1-t).add(vec4(to.dual).mul(k)); return *this; } dualquat &invert() { real.invert(); dual.invert(); dual.sub(quat(real).mul(2*real.dot(dual))); return *this; } void mul(const dualquat &p, const dualquat &o) { real.mul(p.real, o.real); dual.mul(p.real, o.dual).add(quat().mul(p.dual, o.real)); } void mul(const dualquat &o) { mul(dualquat(*this), o); } void mulorient(const quat &q) { real.mul(q, quat(real)); dual.mul(quat(q).invert(), quat(dual)); } void mulorient(const quat &q, const dualquat &base) { quat trans; trans.mul(base.dual, quat(base.real).invert()); dual.mul(quat(q).invert(), quat(real).mul(trans).add(dual)); real.mul(q, quat(real)); dual.add(quat().mul(real, trans.invert())).sub(quat(real).mul(2*base.real.dot(base.dual))); } void normalize() { float invlen = 1/real.magnitude(); real.mul(invlen); dual.mul(invlen); } void translate(const vec &p) { dual.x += 0.5f*( p.x*real.w + p.y*real.z - p.z*real.y); dual.y += 0.5f*(-p.x*real.z + p.y*real.w + p.z*real.x); dual.z += 0.5f*( p.x*real.y - p.y*real.x + p.z*real.w); dual.w += -0.5f*( p.x*real.x + p.y*real.y + p.z*real.z); } void scale(float k) { dual.mul(k); } void fixantipodal(const dualquat &d) { if(real.dot(d.real) < 0) { real.neg(); dual.neg(); } } void accumulate(const dualquat &d, float k) { if(real.dot(d.real) < 0) k = -k; real.add(vec4(d.real).mul(k)); dual.add(vec4(d.dual).mul(k)); } vec transform(const vec &v) const { return vec().cross(real, vec().cross(real, v).add(vec(v).mul(real.w)).add(vec(dual))).add(vec(dual).mul(real.w)).sub(vec(real).mul(dual.w)).mul(2).add(v); } vec transposedtransform(const vec &v) const { return dualquat(*this).invert().transform(v); } vec transformnormal(const vec &v) const { return real.rotate(v); } vec transposedtransformnormal(const vec &v) const { return real.invertedrotate(v); } vec gettranslation() const { return vec().cross(real, dual).add(vec(dual).mul(real.w)).sub(vec(real).mul(dual.w)).mul(2); } }; struct matrix3x3 { vec a, b, c; matrix3x3() {} matrix3x3(const vec &a, const vec &b, const vec &c) : a(a), b(b), c(c) {} explicit matrix3x3(float angle, const vec &axis) { rotate(angle, axis); } explicit matrix3x3(const quat &q) { float x = q.x, y = q.y, z = q.z, w = q.w, tx = 2*x, ty = 2*y, tz = 2*z, txx = tx*x, tyy = ty*y, tzz = tz*z, txy = tx*y, txz = tx*z, tyz = ty*z, twx = w*tx, twy = w*ty, twz = w*tz; a = vec(1 - (tyy + tzz), txy - twz, txz + twy); b = vec(txy + twz, 1 - (txx + tzz), tyz - twx); c = vec(txz - twy, tyz + twx, 1 - (txx + tyy)); } void mul(const matrix3x3 &m, const matrix3x3 &n) { a = vec(n.a).mul(m.a.x).add(vec(n.b).mul(m.a.y)).add(vec(n.c).mul(m.a.z)); b = vec(n.a).mul(m.b.x).add(vec(n.b).mul(m.b.y)).add(vec(n.c).mul(m.b.z)); c = vec(n.a).mul(m.c.x).add(vec(n.b).mul(m.c.y)).add(vec(n.c).mul(m.c.z)); } void mul(const matrix3x3 &n) { mul(*this, n); } void multranspose(const matrix3x3 &m, const matrix3x3 &n) { a = vec(m.a.dot(n.a), m.a.dot(n.b), m.a.dot(n.c)); b = vec(m.b.dot(n.a), m.b.dot(n.b), m.b.dot(n.c)); c = vec(m.c.dot(n.a), m.c.dot(n.b), m.c.dot(n.c)); } void transposemul(const matrix3x3 &m, const matrix3x3 &n) { a = vec(n.a).mul(m.a.x).add(vec(n.b).mul(m.b.x)).add(vec(n.c).mul(m.c.x)); b = vec(n.a).mul(m.a.y).add(vec(n.b).mul(m.b.y)).add(vec(n.c).mul(m.c.y)); c = vec(n.a).mul(m.a.z).add(vec(n.b).mul(m.b.z)).add(vec(n.c).mul(m.c.z)); } void transpose(const matrix3x3 &o) { a = vec(o.a.x, o.b.x, o.c.x); b = vec(o.a.y, o.b.y, o.c.y); c = vec(o.a.z, o.b.z, o.c.z); } void rotate(float angle, const vec &axis) { rotate(cosf(angle), sinf(angle), axis); } void rotate(float ck, float sk, const vec &axis) { a = vec(axis.x*axis.x*(1-ck)+ck, axis.x*axis.y*(1-ck)-axis.z*sk, axis.x*axis.z*(1-ck)+axis.y*sk); b = vec(axis.y*axis.x*(1-ck)+axis.z*sk, axis.y*axis.y*(1-ck)+ck, axis.y*axis.z*(1-ck)-axis.x*sk); c = vec(axis.x*axis.z*(1-ck)-axis.y*sk, axis.y*axis.z*(1-ck)+axis.x*sk, axis.z*axis.z*(1-ck)+ck); } bool calcangleaxis(float &angle, vec &axis, float threshold = 1e-9f) { angle = acosf(clamp(0.5f*(a.x + b.y + c.z - 1), -1.0f, 1.0f)); if(angle <= 0) axis = vec(0, 0, 1); else if(angle < M_PI) { axis = vec(c.y - b.z, a.z - c.x, b.x - a.y); float r = axis.magnitude(); if(r <= threshold) return false; axis.mul(1/r); } else if(a.x >= b.y && a.x >= c.z) { float r = sqrtf(max(1 + a.x - b.y - c.z, 0.0f)); if(r <= threshold) return false; axis.x = 0.5f*r; axis.y = a.y/r; axis.z = a.z/r; } else if(b.y >= c.z) { float r = sqrtf(max(1 + b.y - a.x - c.z, 0.0f)); if(r <= threshold) return false; axis.y = 0.5f*r; axis.x = a.y/r; axis.z = b.z/r; } else { float r = sqrtf(max(1 + b.y - a.x - c.z, 0.0f)); if(r <= threshold) return false; axis.z = 0.5f*r; axis.x = a.z/r; axis.y = b.z/r; } return true; } vec transform(const vec &o) const { return vec(a.dot(o), b.dot(o), c.dot(o)); } vec transposedtransform(const vec &o) const { return vec(a.x*o.x + b.x*o.y + c.x*o.z, a.y*o.x + b.y*o.y + c.y*o.z, a.z*o.x + b.z*o.y + c.z*o.z); } }; struct matrix2x3 { vec a, b; matrix2x3() {} matrix2x3(const vec &a, const vec &b) : a(a), b(b) {} vec2 transform(const vec &o) const { return vec2(a.dot(o), b.dot(o)); } vec transposedtransform(const vec2 &o) const { return vec(a.x*o.x + b.x*o.y, a.y*o.x + b.y*o.y, a.z*o.x + b.z*o.y); } }; struct matrix3x4 { vec4 a, b, c; matrix3x4() {} matrix3x4(const vec4 &x, const vec4 &y, const vec4 &z) : a(x), b(y), c(z) {} matrix3x4(const matrix3x3 &rot, const vec &trans) : a(rot.a, trans.x), b(rot.b, trans.y), c(rot.c, trans.z) {} matrix3x4(const dualquat &d) { vec4 r = vec4(d.real).mul(1/d.real.squaredlen()), rr = vec4(r).mul(d.real); r.mul(2); float xy = r.x*d.real.y, xz = r.x*d.real.z, yz = r.y*d.real.z, wx = r.w*d.real.x, wy = r.w*d.real.y, wz = r.w*d.real.z; a = vec4(rr.w + rr.x - rr.y - rr.z, xy - wz, xz + wy, -(d.dual.w*r.x - d.dual.x*r.w + d.dual.y*r.z - d.dual.z*r.y)); b = vec4(xy + wz, rr.w + rr.y - rr.x - rr.z, yz - wx, -(d.dual.w*r.y - d.dual.x*r.z - d.dual.y*r.w + d.dual.z*r.x)); c = vec4(xz - wy, yz + wx, rr.w + rr.z - rr.x - rr.y, -(d.dual.w*r.z + d.dual.x*r.y - d.dual.y*r.x - d.dual.z*r.w)); } void mul(float k) { a.mul(k); b.mul(k); c.mul(k); } void scale(float k) { a.mul(k); b.mul(k); c.mul(k); } void translate(const vec &p) { a.w += p.x; b.w += p.y; c.w += p.z; } void transformedtranslate(const vec &p, float scale = 1) { a.w += a.dot3(p)*scale; b.w += b.dot3(p)*scale; c.w += c.dot3(p)*scale; } void accumulate(const matrix3x4 &m, float k) { a.add(vec4(m.a).mul(k)); b.add(vec4(m.b).mul(k)); c.add(vec4(m.c).mul(k)); } void normalize() { a.mul3(1/a.magnitude3()); b.mul3(1/b.magnitude3()); c.mul3(1/c.magnitude3()); } void lerp(const matrix3x4 &to, float t) { a.lerp(to.a, t); b.lerp(to.b, t); c.lerp(to.c, t); } void lerp(const matrix3x4 &from, const matrix3x4 &to, float t) { a.lerp(from.a, to.a, t); b.lerp(from.b, to.b, t); c.lerp(from.c, to.c, t); } void identity() { a = vec4(1, 0, 0, 0); b = vec4(0, 1, 0, 0); c = vec4(0, 0, 1, 0); } void mul(const matrix3x4 &m, const matrix3x4 &n) { a = vec4(n.a).mul(m.a.x).add(vec4(n.b).mul(m.a.y)).add(vec4(n.c).mul(m.a.z)).addw(m.a.w); b = vec4(n.a).mul(m.b.x).add(vec4(n.b).mul(m.b.y)).add(vec4(n.c).mul(m.b.z)).addw(m.b.w); c = vec4(n.a).mul(m.c.x).add(vec4(n.b).mul(m.c.y)).add(vec4(n.c).mul(m.c.z)).addw(m.c.w); } void mul(const matrix3x4 &n) { mul(*this, n); } void mul(const matrix3x3 &rot, const vec &trans, const matrix3x4 &o) { a = vec4(o.a).mul(rot.a.x).add(vec4(o.b).mul(rot.a.y)).add(vec4(o.c).mul(rot.a.z)).addw(trans.x); b = vec4(o.a).mul(rot.b.x).add(vec4(o.b).mul(rot.b.y)).add(vec4(o.c).mul(rot.b.z)).addw(trans.y); c = vec4(o.a).mul(rot.c.x).add(vec4(o.b).mul(rot.c.y)).add(vec4(o.c).mul(rot.c.z)).addw(trans.z); } void mulorient(const matrix3x3 &m) { vec ra = vec(a).mul(m.a.x).add(vec(b).mul(m.a.y)).add(vec(c).mul(m.a.z)), rb = vec(a).mul(m.b.x).add(vec(b).mul(m.b.y)).add(vec(c).mul(m.b.z)), rc = vec(a).mul(m.c.x).add(vec(b).mul(m.c.y)).add(vec(c).mul(m.c.z)); a.setxyz(ra); b.setxyz(rb); c.setxyz(rc); } void mulorient(const matrix3x3 &m, const dualquat &base) { vec trans = transformnormal(base.gettranslation()); translate(trans.sub(m.transform(trans))); mulorient(m); } void transpose(const matrix3x4 &o) { a = vec4(o.a.x, o.b.x, o.c.x, -(o.a.x*o.a.w + o.b.x*o.b.w + o.c.x*o.c.w)); b = vec4(o.a.y, o.b.y, o.c.y, -(o.a.y*o.a.w + o.b.y*o.b.w + o.c.y*o.c.w)); c = vec4(o.a.z, o.b.z, o.c.z, -(o.a.z*o.a.w + o.b.z*o.b.w + o.c.z*o.c.w)); } void transposemul(const matrix3x3 &rot, const vec &trans, const matrix3x4 &o) { a = vec4(o.a).mul(rot.a.x).add(vec4(o.b).mul(rot.b.x)).add(vec4(o.c).mul(rot.c.x)).addw(trans.x); b = vec4(o.a).mul(rot.a.y).add(vec4(o.b).mul(rot.b.y)).add(vec4(o.c).mul(rot.c.y)).addw(trans.y); c = vec4(o.a).mul(rot.a.z).add(vec4(o.b).mul(rot.b.z)).add(vec4(o.c).mul(rot.c.z)).addw(trans.z); } void transposemul(const matrix3x4 &m, const matrix3x4 &n) { float tx = m.a.x*m.a.w + m.b.x*m.b.w + m.c.x*m.c.w, ty = m.a.y*m.a.w + m.b.y*m.b.w + m.c.y*m.c.w, tz = m.a.z*m.a.w + m.b.z*m.b.w + m.c.z*m.c.w; a = vec4(n.a).mul(m.a.x).add(vec4(n.b).mul(m.b.x)).add(vec4(n.c).mul(m.c.x)).subw(tx); b = vec4(n.a).mul(m.a.y).add(vec4(n.b).mul(m.b.y)).add(vec4(n.c).mul(m.c.y)).subw(ty); c = vec4(n.a).mul(m.a.z).add(vec4(n.b).mul(m.b.z)).add(vec4(n.c).mul(m.c.z)).subw(tz); } void rotate(float angle, const vec &d) { rotate(cosf(angle), sinf(angle), d); } void rotate(float ck, float sk, const vec &d) { a = vec4(d.x*d.x*(1-ck)+ck, d.x*d.y*(1-ck)-d.z*sk, d.x*d.z*(1-ck)+d.y*sk, 0); b = vec4(d.y*d.x*(1-ck)+d.z*sk, d.y*d.y*(1-ck)+ck, d.y*d.z*(1-ck)-d.x*sk, 0); c = vec4(d.x*d.z*(1-ck)-d.y*sk, d.y*d.z*(1-ck)+d.x*sk, d.z*d.z*(1-ck)+ck, 0); } #define ROTVEC(V, m, n) \ { \ float m = V.m, n = V.n; \ V.m = m*ck + n*sk; \ V.n = n*ck - m*sk; \ } void rotate_around_x(float angle) { float ck = cosf(angle), sk = sinf(angle); ROTVEC(a, y, z); ROTVEC(b, y, z); ROTVEC(c, y, z); } void rotate_around_y(float angle) { float ck = cosf(angle), sk = sinf(angle); ROTVEC(a, z, x); ROTVEC(b, z, x); ROTVEC(c, z, x); } void rotate_around_z(float angle) { float ck = cosf(angle), sk = sinf(angle); ROTVEC(a, x, y); ROTVEC(b, x, y); ROTVEC(c, x, y); } #undef ROTVEC vec transform(const vec &o) const { return vec(a.dot(o), b.dot(o), c.dot(o)); } vec transposedtransform(const vec &o) const { vec p = o; p.x -= a.w; p.y -= b.w; p.z -= c.w; return vec(a.x*p.x + b.x*p.y + c.x*p.z, a.y*p.x + b.y*p.y + c.y*p.z, a.z*p.x + b.z*p.y + c.z*p.z); } vec transformnormal(const vec &o) const { return vec(a.dot3(o), b.dot3(o), c.dot3(o)); } vec transposedtransformnormal(const vec &o) const { return vec(a.x*o.x + b.x*o.y + c.x*o.z, a.y*o.x + b.y*o.y + c.y*o.z, a.z*o.x + b.z*o.y + c.z*o.z); } float getscale() const { return a.magnitude3(); } vec gettranslation() const { return vec(a.w, b.w, c.w); } }; inline dualquat::dualquat(const matrix3x4 &m) : real(m) { dual.x = 0.5f*( m.a.w*real.w + m.b.w*real.z - m.c.w*real.y); dual.y = 0.5f*(-m.a.w*real.z + m.b.w*real.w + m.c.w*real.x); dual.z = 0.5f*( m.a.w*real.y - m.b.w*real.x + m.c.w*real.w); dual.w = -0.5f*( m.a.w*real.x + m.b.w*real.y + m.c.w*real.z); } struct plane : vec { float offset; float dist(const vec &p) const { return dot(p)+offset; } bool operator==(const plane &p) const { return x==p.x && y==p.y && z==p.z && offset==p.offset; } bool operator!=(const plane &p) const { return x!=p.x || y!=p.y || z!=p.z || offset!=p.offset; } plane() {} plane(const vec &c, float off) : vec(c), offset(off) {} plane(const vec4 &p) : vec(p), offset(p.w) {} plane(int d, float off) { x = y = z = 0.0f; v[d] = 1.0f; offset = -off; } plane(float a, float b, float c, float d) : vec(a, b, c), offset(d) {} void toplane(const vec &n, const vec &p) { x = n.x; y = n.y; z = n.z; offset = -dot(p); } bool toplane(const vec &a, const vec &b, const vec &c) { cross(vec(b).sub(a), vec(c).sub(a)); float mag = magnitude(); if(!mag) return false; div(mag); offset = -dot(a); return true; } bool rayintersect(const vec &o, const vec &ray, float &dist) { float cosalpha = dot(ray); if(cosalpha==0) return false; float deltac = offset+dot(o); dist -= deltac/cosalpha; return true; } plane &reflectz(float rz) { offset += 2*rz*z; z = -z; return *this; } plane &invert() { neg(); offset = -offset; return *this; } plane &scale(float k) { mul(k); return *this; } plane &translate(const vec &p) { offset += dot(p); return *this; } plane &normalize() { float mag = magnitude(); div(mag); offset /= mag; return *this; } float zintersect(const vec &p) const { return -(x*p.x+y*p.y+offset)/z; } float zdelta(const vec &p) const { return -(x*p.x+y*p.y)/z; } float zdist(const vec &p) const { return p.z-zintersect(p); } }; struct triangle { vec a, b, c; triangle(const vec &a, const vec &b, const vec &c) : a(a), b(b), c(c) {} triangle() {} triangle &add(const vec &o) { a.add(o); b.add(o); c.add(o); return *this; } triangle &sub(const vec &o) { a.sub(o); b.sub(o); c.sub(o); return *this; } bool operator==(const triangle &t) const { return a == t.a && b == t.b && c == t.c; } }; /** Sauerbraten uses 3 different linear coordinate systems which are oriented around each of the axis dimensions. So any point within the game can be defined by four coordinates: (d, x, y, z) d is the reference axis dimension x is the coordinate of the ROW dimension y is the coordinate of the COL dimension z is the coordinate of the reference dimension (DEPTH) typically, if d is not used, then it is implicitly the Z dimension. ie: d=z => x=x, y=y, z=z **/ // DIM: X=0 Y=1 Z=2. const int R[3] = {1, 2, 0}; // row const int C[3] = {2, 0, 1}; // col const int D[3] = {0, 1, 2}; // depth struct ivec { union { struct { int x, y, z; }; struct { int r, g, b; }; int v[3]; }; ivec() {} ivec(const vec &v) : x(int(v.x)), y(int(v.y)), z(int(v.z)) {} explicit ivec(int i) { x = ((i&1)>>0); y = ((i&2)>>1); z = ((i&4)>>2); } ivec(int a, int b, int c) : x(a), y(b), z(c) {} ivec(int d, int row, int col, int depth) { v[R[d]] = row; v[C[d]] = col; v[D[d]] = depth; } ivec(int i, int cx, int cy, int cz, int size) { x = cx+((i&1)>>0)*size; y = cy+((i&2)>>1)*size; z = cz+((i&4)>>2)*size; } vec tovec() const { return vec(x, y, z); } int toint() const { return (x>0?1:0) + (y>0?2:0) + (z>0?4:0); } int &operator[](int i) { return v[i]; } int operator[](int i) const { return v[i]; } //int idx(int i) { return v[i]; } bool operator==(const ivec &v) const { return x==v.x && y==v.y && z==v.z; } bool operator!=(const ivec &v) const { return x!=v.x || y!=v.y || z!=v.z; } bool iszero() const { return x==0 && y==0 && z==0; } ivec &shl(int n) { x<<= n; y<<= n; z<<= n; return *this; } ivec &shr(int n) { x>>= n; y>>= n; z>>= n; return *this; } ivec &mul(int n) { x *= n; y *= n; z *= n; return *this; } ivec &div(int n) { x /= n; y /= n; z /= n; return *this; } ivec &add(int n) { x += n; y += n; z += n; return *this; } ivec &sub(int n) { x -= n; y -= n; z -= n; return *this; } ivec &mul(const ivec &v) { x *= v.x; y *= v.y; z *= v.z; return *this; } ivec &div(const ivec &v) { x /= v.x; y /= v.y; z /= v.z; return *this; } ivec &add(const ivec &v) { x += v.x; y += v.y; z += v.z; return *this; } ivec &sub(const ivec &v) { x -= v.x; y -= v.y; z -= v.z; return *this; } ivec &mask(int n) { x &= n; y &= n; z &= n; return *this; } ivec &neg() { return mul(-1); } ivec &min(const ivec &o) { x = ::min(x, o.x); y = ::min(y, o.y); z = ::min(z, o.z); return *this; } ivec &max(const ivec &o) { x = ::max(x, o.x); y = ::max(y, o.y); z = ::max(z, o.z); return *this; } ivec &min(int n) { x = ::min(x, n); y = ::min(y, n); z = ::min(z, n); return *this; } ivec &max(int n) { x = ::max(x, n); y = ::max(y, n); z = ::max(z, n); return *this; } ivec &abs() { x = ::abs(x); y = ::abs(y); z = ::abs(z); return *this; } ivec &cross(const ivec &a, const ivec &b) { x = a.y*b.z-a.z*b.y; y = a.z*b.x-a.x*b.z; z = a.x*b.y-a.y*b.x; return *this; } int dot(const ivec &o) const { return x*o.x + y*o.y + z*o.z; } float dist(const plane &p) const { return x*p.x + y*p.y + z*p.z + p.offset; } }; static inline bool htcmp(const ivec &x, const ivec &y) { return x == y; } static inline uint hthash(const ivec &k) { return k.x^k.y^k.z; } struct bvec { union { struct { uchar x, y, z; }; struct { uchar r, g, b; }; uchar v[3]; }; bvec() {} bvec(uchar x, uchar y, uchar z) : x(x), y(y), z(z) {} bvec(const vec &v) : x((uchar)((v.x+1)*255/2)), y((uchar)((v.y+1)*255/2)), z((uchar)((v.z+1)*255/2)) {} uchar &operator[](int i) { return v[i]; } uchar operator[](int i) const { return v[i]; } bool operator==(const bvec &v) const { return x==v.x && y==v.y && z==v.z; } bool operator!=(const bvec &v) const { return x!=v.x || y!=v.y || z!=v.z; } bool iszero() const { return x==0 && y==0 && z==0; } vec tovec() const { return vec(x*(2.0f/255.0f)-1.0f, y*(2.0f/255.0f)-1.0f, z*(2.0f/255.0f)-1.0f); } bvec &normalize() { vec n(x-127.5f, y-127.5f, z-127.5f); float mag = 127.5f/n.magnitude(); x = uchar(n.x*mag+127.5f); y = uchar(n.y*mag+127.5f); z = uchar(n.z*mag+127.5f); return *this; } void lerp(const bvec &a, const bvec &b, float t) { x = uchar(a.x + (b.x-a.x)*t); y = uchar(a.y + (b.y-a.y)*t); z = uchar(a.z + (b.z-a.z)*t); } void flip() { x -= 128; y -= 128; z -= 128; } bvec &shl(int n) { x<<= n; y<<= n; z<<= n; return *this; } bvec &shr(int n) { x>>= n; y>>= n; z>>= n; return *this; } static bvec fromcolor(const vec &v) { return bvec(uchar(v.x*255.0f), uchar(v.y*255.0f), uchar(v.z*255.0f)); } vec tocolor() const { return vec(x*(1.0f/255.0f), y*(1.0f/255.0f), z*(1.0f/255.0f)); } }; struct glmatrixf { float v[16]; glmatrixf() {} glmatrixf(const float *m) { memcpy(v, m, sizeof(v)); } glmatrixf(const vec4 &a, const vec4 &b, const vec4 &c, const vec4 &d = vec4(0, 0, 0, 1)) { v[0] = a.x; v[1] = b.x; v[2] = c.x; v[3] = d.x; v[4] = a.y; v[5] = b.y; v[6] = c.y; v[7] = d.y; v[8] = a.z; v[9] = b.z; v[10] = c.z; v[11] = d.z; v[12] = a.w; v[13] = b.w; v[14] = c.w; v[15] = d.w; } glmatrixf(const matrix3x4 &m) { v[0] = m.a.x; v[1] = m.b.x; v[2] = m.c.x; v[3] = 0.0f; v[4] = m.a.y; v[5] = m.b.y; v[6] = m.c.y; v[7] = 0.0f; v[8] = m.a.z; v[9] = m.b.z; v[10] = m.c.z; v[11] = 0.0f; v[12] = m.a.w; v[13] = m.b.w; v[14] = m.c.w; v[15] = 1.0f; } float operator[](int i) const { return v[i]; } float &operator[](int i) { return v[i]; } #define ROTVEC(A, B) \ { \ float a = A, b = B; \ A = a*c + b*s; \ B = b*c - a*s; \ } void rotate_around_x(float angle) { float c = cosf(angle), s = sinf(angle); ROTVEC(v[4], v[8]); ROTVEC(v[5], v[9]); ROTVEC(v[6], v[10]); } void rotate_around_y(float angle) { float c = cosf(angle), s = sinf(angle); ROTVEC(v[8], v[0]); ROTVEC(v[9], v[1]); ROTVEC(v[10], v[2]); } void rotate_around_z(float angle) { float c = cosf(angle), s = sinf(angle); ROTVEC(v[0], v[4]); ROTVEC(v[1], v[5]); ROTVEC(v[2], v[6]); } #undef ROTVEC void rotate(float c, float s, const vec &d) { vec c1(d.x*d.x*(1-c)+c, d.y*d.x*(1-c)+d.z*s, d.x*d.z*(1-c)-d.y*s), c2(d.x*d.y*(1-c)-d.z*s, d.y*d.y*(1-c)+c, d.y*d.z*(1-c)+d.x*s), c3(d.x*d.z*(1-c)+d.y*s, d.y*d.z*(1-c)-d.x*s, d.z*d.z*(1-c)+c); vec r1(v[0], v[4], v[8]); v[0] = r1.dot(c1); v[4] = r1.dot(c2); v[8] = r1.dot(c3); vec r2(v[1], v[5], v[9]); v[1] = r2.dot(c1); v[5] = r2.dot(c2); v[9] = r2.dot(c3); vec r3(v[2], v[6], v[10]); v[2] = r3.dot(c1); v[6] = r3.dot(c2); v[10] = r3.dot(c3); } void rotate(float angle, const vec &d) { float c = cosf(angle), s = sinf(angle); rotate(c, s, d); } #define MULMAT(row, col) \ v[col + row] = x[row]*y[col] + x[row + 4]*y[col + 1] + x[row + 8]*y[col + 2] + x[row + 12]*y[col + 3]; template void mul(const XT x[16], const YT y[16]) { MULMAT(0, 0); MULMAT(1, 0); MULMAT(2, 0); MULMAT(3, 0); MULMAT(0, 4); MULMAT(1, 4); MULMAT(2, 4); MULMAT(3, 4); MULMAT(0, 8); MULMAT(1, 8); MULMAT(2, 8); MULMAT(3, 8); MULMAT(0, 12); MULMAT(1, 12); MULMAT(2, 12); MULMAT(3, 12); } #undef MULMAT void mul(const glmatrixf &x, const glmatrixf &y) { mul(x.v, y.v); } void mul(const glmatrixf &y) { mul(glmatrixf(*this), y); } void identity() { static const float m[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; memcpy(v, m, sizeof(v)); } void translate(float x, float y, float z) { v[12] += x; v[13] += y; v[14] += z; } void translate(const vec &o) { translate(o.x, o.y, o.z); } void transformedtranslate(float x, float y, float z, float scale = 1) { v[12] += (x*v[0] + y*v[4] + z*v[8])*scale; v[13] += (x*v[1] + y*v[5] + z*v[9])*scale; v[14] += (x*v[2] + y*v[6] + z*v[10])*scale; } void transformedtranslate(const vec &p, float scale = 1) { transformedtranslate(p.x, p.y, p.z, scale); } void scale(float x, float y, float z) { v[0] *= x; v[1] *= x; v[2] *= x; v[3] *= x; v[4] *= y; v[5] *= y; v[6] *= y; v[7] *= y; v[8] *= z; v[9] *= z; v[10] *= z; v[11] *= z; } void reflectz(float z) { v[12] += 2*z*v[8]; v[13] += 2*z*v[9]; v[14] += 2*z*v[10]; v[15] += 2*z*v[11]; v[8] = -v[8]; v[9] = -v[9]; v[10] = -v[10]; v[11] = -v[11]; } void projective(float zscale = 0.5f, float zoffset = 0.5f) { loopi(2) loopj(4) v[i + j*4] = 0.5f*(v[i + j*4] + v[3 + j*4]); loopj(4) v[2 + j*4] = zscale*v[2 + j*4] + zoffset*v[3 + j*4]; } void transpose() { swap(v[1], v[4]); swap(v[2], v[8]); swap(v[3], v[12]); swap(v[6], v[9]); swap(v[7], v[13]); swap(v[11], v[14]); } void frustum(float left, float right, float bottom, float top, float znear, float zfar) { float width = right - left, height = top - bottom, zrange = znear - zfar; v[0] = 2*znear/width; v[4] = 0; v[8] = (right + left)/width; v[12] = 0; v[1] = 0; v[5] = 2*znear/height; v[9] = (top + bottom)/height; v[13] = 0; v[2] = 0; v[6] = 0; v[10] = (zfar + znear)/zrange; v[14] = 2*znear*zfar/zrange; v[3] = 0; v[7] = 0; v[11] = -1; v[15] = 0; } void perspective(float fovy, float aspect, float znear, float zfar) { float ydist = znear * tan(fovy/2*RAD), xdist = ydist * aspect; frustum(-xdist, xdist, -ydist, ydist, znear, zfar); } void clip(const plane &p, const glmatrixf &m) { float x = ((p.x<0 ? -1 : (p.x>0 ? 1 : 0)) + m.v[8]) / m.v[0], y = ((p.y<0 ? -1 : (p.y>0 ? 1 : 0)) + m.v[9]) / m.v[5], w = (1 + m.v[10]) / m.v[14], scale = 2 / (x*p.x + y*p.y - p.z + w*p.offset); memcpy(v, m.v, sizeof(v)); v[2] = p.x*scale; v[6] = p.y*scale; v[10] = p.z*scale + 1.0f; v[14] = p.offset*scale; } float transformx(const vec &p) const { return p.x*v[0] + p.y*v[4] + p.z*v[8] + v[12]; } float transformy(const vec &p) const { return p.x*v[1] + p.y*v[5] + p.z*v[9] + v[13]; } float transformz(const vec &p) const { return p.x*v[2] + p.y*v[6] + p.z*v[10] + v[14]; } float transformw(const vec &p) const { return p.x*v[3] + p.y*v[7] + p.z*v[11] + v[15]; } float transformx(const vec4 &p) const { return p.x*v[0] + p.y*v[4] + p.z*v[8] + p.w*v[12]; } float transformy(const vec4 &p) const { return p.x*v[1] + p.y*v[5] + p.z*v[9] + p.w*v[13]; } float transformz(const vec4 &p) const { return p.x*v[2] + p.y*v[6] + p.z*v[10] + p.w*v[14]; } float transformw(const vec4 &p) const { return p.x*v[3] + p.y*v[7] + p.z*v[11] + p.w*v[15]; } template void transform(const T &in, vec &out) const { out.x = transformx(in); out.y = transformy(in); out.z = transformz(in); } template void transform(const T &in, vec4 &out) const { out.x = transformx(in); out.y = transformy(in); out.z = transformz(in); out.w = transformw(in); } template vec perspectivetransform(const T &in) const { return vec(transformx(in), transformy(in), transformz(in)).div(transformw(in)); } void transformnormal(const vec &in, vec &out) const { out.x = in.x*v[0] + in.y*v[4] + in.z*v[8]; out.y = in.x*v[1] + in.y*v[5] + in.z*v[9]; out.z = in.x*v[2] + in.y*v[6] + in.z*v[10]; } void transposedtransform(const vec &in, vec &out) const { vec p(in.x - v[12], in.y - v[13], in.z - v[14]); out.x = p.x*v[0] + p.y*v[1] + p.z*v[2]; out.y = p.x*v[4] + p.y*v[5] + p.z*v[6]; out.z = p.x*v[8] + p.y*v[9] + p.z*v[10]; } void transposedtransformnormal(const vec &in, vec &out) const { out.x = in.x*v[0] + in.y*v[1] + in.z*v[2]; out.y = in.x*v[4] + in.y*v[5] + in.z*v[6]; out.z = in.x*v[8] + in.y*v[9] + in.z*v[10]; } void transposedtransform(const plane &in, plane &out) const { out.x = in.x*v[0] + in.y*v[1] + in.z*v[2] + in.offset*v[3]; out.y = in.x*v[4] + in.y*v[5] + in.z*v[6] + in.offset*v[7]; out.z = in.x*v[8] + in.y*v[9] + in.z*v[10] + in.offset*v[11]; out.offset = in.x*v[12] + in.y*v[13] + in.z*v[14] + in.offset*v[15]; } float getscale() const { return sqrtf(v[0]*v[0] + v[4]*v[4] + v[8]*v[8]); } vec gettranslation() const { return vec(v[12], v[13], v[14]); } vec4 getrow(int i) const { return vec4(v[i], v[i+4], v[i+8], v[i+12]); } vec4 getcolumn(int i) const { i *= 4; return vec4(v[i], v[i+1], v[i+2], v[i+3]); } float determinant() const; void adjoint(const glmatrixf &m); bool invert(const glmatrixf &m, float mindet = 1.0e-10f); }; extern bool raysphereintersect(const vec ¢er, float radius, const vec &o, const vec &ray, float &dist); extern bool rayrectintersect(const vec &b, const vec &s, const vec &o, const vec &ray, float &dist, int &orient); extern bool linecylinderintersect(const vec &from, const vec &to, const vec &start, const vec &end, float radius, float &dist); extern const vec2 sincos360[]; sauerbraten-0.0.20130203.dfsg/shared/tools.h0000644000175000017500000007703412103333460020162 0ustar vincentvincent// generic useful stuff for any C++ program #ifndef _TOOLS_H #define _TOOLS_H #ifdef NULL #undef NULL #endif #define NULL 0 typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; typedef signed long long int llong; typedef unsigned long long int ullong; #ifdef _DEBUG #define ASSERT(c) assert(c) #else #define ASSERT(c) if(c) {} #endif #if defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1400) #define RESTRICT __restrict #else #define RESTRICT #endif inline void *operator new(size_t size) { void *p = malloc(size); if(!p) abort(); return p; } inline void *operator new[](size_t size) { void *p = malloc(size); if(!p) abort(); return p; } inline void operator delete(void *p) { if(p) free(p); } inline void operator delete[](void *p) { if(p) free(p); } inline void *operator new(size_t, void *p) { return p; } inline void *operator new[](size_t, void *p) { return p; } inline void operator delete(void *, void *) {} inline void operator delete[](void *, void *) {} #ifdef swap #undef swap #endif template static inline void swap(T &a, T &b) { T t = a; a = b; b = t; } #ifdef max #undef max #endif #ifdef min #undef min #endif template static inline T max(T a, T b) { return a > b ? a : b; } template static inline T min(T a, T b) { return a < b ? a : b; } template static inline T clamp(T a, U b, U c) { return max(T(b), min(a, T(c))); } #define rnd(x) ((int)(randomMT()&0xFFFFFF)%(x)) #define rndscale(x) (float((randomMT()&0xFFFFFF)*double(x)/double(0xFFFFFF))) #define detrnd(s, x) ((int)(((((uint)(s))*1103515245+12345)>>16)%(x))) #define loop(v,m) for(int v = 0; v=0; i--) #define DELETEP(p) if(p) { delete p; p = 0; } #define DELETEA(p) if(p) { delete[] p; p = 0; } #define PI (3.1415927f) #define PI2 (2*PI) #define SQRT2 (1.4142136f) #define SQRT3 (1.7320508f) #define RAD (PI / 180.0f) #ifdef WIN32 #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef M_LN2 #define M_LN2 0.693147180559945309417 #endif #ifndef __GNUC__ #pragma warning (3: 4189) // local variable is initialized but not referenced #pragma warning (disable: 4244) // conversion from 'int' to 'float', possible loss of data #pragma warning (disable: 4267) // conversion from 'size_t' to 'int', possible loss of data #pragma warning (disable: 4355) // 'this' : used in base member initializer list #pragma warning (disable: 4996) // 'strncpy' was declared deprecated #endif #define strcasecmp _stricmp #define strncasecmp _strnicmp #define PATHDIV '\\' #else #define __cdecl #define _vsnprintf vsnprintf #define PATHDIV '/' #endif #ifdef __GNUC__ #define PRINTFARGS(fmt, args) __attribute__((format(printf, fmt, args))) #else #define PRINTFARGS(fmt, args) #endif // easy safe strings #define MAXSTRLEN 260 typedef char string[MAXSTRLEN]; inline void vformatstring(char *d, const char *fmt, va_list v, int len = MAXSTRLEN) { _vsnprintf(d, len, fmt, v); d[len-1] = 0; } inline char *copystring(char *d, const char *s, size_t len = MAXSTRLEN) { strncpy(d, s, len); d[len-1] = 0; return d; } inline char *concatstring(char *d, const char *s, size_t len = MAXSTRLEN) { size_t used = strlen(d); return used < len ? copystring(d+used, s, len-used) : d; } struct stringformatter { char *buf; stringformatter(char *buf): buf((char *)buf) {} void operator()(const char *fmt, ...) PRINTFARGS(2, 3) { va_list v; va_start(v, fmt); vformatstring(buf, fmt, v); va_end(v); } }; #define formatstring(d) stringformatter((char *)d) #define defformatstring(d) string d; formatstring(d) #define defvformatstring(d,last,fmt) string d; { va_list ap; va_start(ap, last); vformatstring(d, fmt, ap); va_end(ap); } #define loopv(v) for(int i = 0; i<(v).length(); i++) #define loopvj(v) for(int j = 0; j<(v).length(); j++) #define loopvk(v) for(int k = 0; k<(v).length(); k++) #define loopvrev(v) for(int i = (v).length()-1; i>=0; i--) template struct databuf { enum { OVERREAD = 1<<0, OVERWROTE = 1<<1 }; T *buf; int len, maxlen; uchar flags; databuf() : buf(NULL), len(0), maxlen(0), flags(0) {} template databuf(T *buf, U maxlen) : buf(buf), len(0), maxlen((int)maxlen), flags(0) {} const T &get() { static T overreadval = 0; if(len charbuf; typedef databuf ucharbuf; struct packetbuf : ucharbuf { ENetPacket *packet; int growth; packetbuf(ENetPacket *packet) : ucharbuf(packet->data, packet->dataLength), packet(packet), growth(0) {} packetbuf(int growth, int pflags = 0) : growth(growth) { packet = enet_packet_create(NULL, growth, pflags); buf = (uchar *)packet->data; maxlen = packet->dataLength; } ~packetbuf() { cleanup(); } void reliable() { packet->flags |= ENET_PACKET_FLAG_RELIABLE; } void resize(int n) { enet_packet_resize(packet, n); buf = (uchar *)packet->data; maxlen = packet->dataLength; } void checkspace(int n) { if(len + n > maxlen && packet && growth > 0) resize(max(len + n, maxlen + growth)); } ucharbuf subbuf(int sz) { checkspace(sz); return ucharbuf::subbuf(sz); } void put(const uchar &val) { checkspace(1); ucharbuf::put(val); } void put(const uchar *vals, int numvals) { checkspace(numvals); ucharbuf::put(vals, numvals); } ENetPacket *finalize() { resize(len); return packet; } void cleanup() { if(growth > 0 && packet && !packet->referenceCount) { enet_packet_destroy(packet); packet = NULL; buf = NULL; len = maxlen = 0; } } }; template static inline float heapscore(const T &n) { return n; } template static inline bool compareless(const T &x, const T &y) { return x < y; } template static inline void insertionsort(T *start, T *end, F fun) { for(T *i = start+1; i < end; i++) { if(fun(*i, i[-1])) { T tmp = *i; *i = i[-1]; T *j = i-1; for(; j > start && fun(tmp, j[-1]); --j) *j = j[-1]; *j = tmp; } } } template static inline void insertionsort(T *buf, int n, F fun) { insertionsort(buf, buf+n, fun); } template static inline void insertionsort(T *buf, int n) { insertionsort(buf, buf+n, compareless); } template static inline void quicksort(T *start, T *end, F fun) { while(end-start > 10) { T *mid = &start[(end-start)/2], *i = start+1, *j = end-2, pivot; if(fun(*start, *mid)) /* start < mid */ { if(fun(end[-1], *start)) { pivot = *start; *start = end[-1]; end[-1] = *mid; } /* end < start < mid */ else if(fun(end[-1], *mid)) { pivot = end[-1]; end[-1] = *mid; } /* start <= end < mid */ else { pivot = *mid; } /* start < mid <= end */ } else if(fun(*start, end[-1])) { pivot = *start; *start = *mid; } /*mid <= start < end */ else if(fun(*mid, end[-1])) { pivot = end[-1]; end[-1] = *start; *start = *mid; } /* mid < end <= start */ else { pivot = *mid; swap(*start, end[-1]); } /* end <= mid <= start */ *mid = end[-2]; do { while(fun(*i, pivot)) if(++i >= j) goto partitioned; while(fun(pivot, *--j)) if(i >= j) goto partitioned; swap(*i, *j); } while(++i < j); partitioned: end[-2] = *i; *i = pivot; if(i-start < end-(i+1)) { quicksort(start, i, fun); start = i+1; } else { quicksort(i+1, end, fun); end = i; } } insertionsort(start, end, fun); } template static inline void quicksort(T *buf, int n, F fun) { quicksort(buf, buf+n, fun); } template static inline void quicksort(T *buf, int n) { quicksort(buf, buf+n, compareless); } template struct isclass { template static char test(void (C::*)(void)); template static int test(...); enum { yes = sizeof(test(0)) == 1 ? 1 : 0, no = yes^1 }; }; static inline uint hthash(const char *key) { uint h = 5381; for(int i = 0, k; (k = key[i]); i++) h = ((h<<5)+h)^k; // bernstein k=33 xor return h; } static inline bool htcmp(const char *x, const char *y) { return !strcmp(x, y); } static inline uint hthash(int key) { return key; } static inline bool htcmp(int x, int y) { return x==y; } #ifndef STANDALONE static inline uint hthash(GLuint key) { return key; } static inline bool htcmp(GLuint x, GLuint y) { return x==y; } #endif template struct vector { static const int MINSIZE = 8; T *buf; int alen, ulen; vector() : buf(NULL), alen(0), ulen(0) { } vector(const vector &v) : buf(NULL), alen(0), ulen(0) { *this = v; } ~vector() { shrink(0); if(buf) delete[] (uchar *)buf; } vector &operator=(const vector &v) { shrink(0); if(v.length() > alen) growbuf(v.length()); loopv(v) add(v[i]); return *this; } T &add(const T &x) { if(ulen==alen) growbuf(ulen+1); new (&buf[ulen]) T(x); return buf[ulen++]; } T &add() { if(ulen==alen) growbuf(ulen+1); new (&buf[ulen]) T; return buf[ulen++]; } T &dup() { if(ulen==alen) growbuf(ulen+1); new (&buf[ulen]) T(buf[ulen-1]); return buf[ulen++]; } void move(vector &v) { if(!ulen) { swap(buf, v.buf); swap(ulen, v.ulen); swap(alen, v.alen); } else { growbuf(ulen+v.ulen); if(v.ulen) memcpy(&buf[ulen], (void *)v.buf, v.ulen*sizeof(T)); ulen += v.ulen; v.ulen = 0; } } bool inrange(size_t i) const { return i=0 && i=0 && i= 0 && i::no) ulen = i; else while(ulen>i) drop(); } void setsize(int i) { ASSERT(i<=ulen); ulen = i; } void deletecontents() { while(!empty()) delete pop(); } void deletearrays() { while(!empty()) delete[] pop(); } T *getbuf() { return buf; } const T *getbuf() const { return buf; } bool inbuf(const T *e) const { return e >= buf && e < &buf[ulen]; } template void sort(F fun, int i = 0, int n = -1) { quicksort(&buf[i], n < 0 ? ulen-i : n, fun); } void sort() { sort(compareless); } void growbuf(int sz) { int olen = alen; if(!alen) alen = max(MINSIZE, sz); else while(alen < sz) alen *= 2; if(alen <= olen) return; uchar *newbuf = new uchar[alen*sizeof(T)]; if(olen > 0) { memcpy(newbuf, (void *)buf, olen*sizeof(T)); delete[] (uchar *)buf; } buf = (T *)newbuf; } databuf reserve(int sz) { if(ulen+sz > alen) growbuf(ulen+sz); return databuf(&buf[ulen], sz); } void advance(int sz) { ulen += sz; } void addbuf(const databuf &p) { advance(p.length()); } T *pad(int n) { T *buf = reserve(n).buf; advance(n); return buf; } void put(const T &v) { add(v); } void put(const T *v, int n) { databuf buf = reserve(n); buf.put(v, n); addbuf(buf); } void remove(int i, int n) { for(int p = i+n; p0) buf[i] = buf[ulen]; return e; } template int find(const U &o) { loopi(ulen) if(buf[i]==o) return i; return -1; } void removeobj(const T &o) { loopi(ulen) if(buf[i]==o) remove(i--); } void replacewithlast(const T &o) { if(!ulen) return; loopi(ulen-1) if(buf[i]==o) { buf[i] = buf[ulen-1]; } ulen--; } T &insert(int i, const T &e) { add(T()); for(int p = ulen-1; p>i; p--) buf[p] = buf[p-1]; buf[i] = e; return buf[i]; } T *insert(int i, const T *e, int n) { if(ulen+n>alen) growbuf(ulen+n); loopj(n) add(T()); for(int p = ulen-1; p>=i+n; p--) buf[p] = buf[p-n]; loopj(n) buf[i+j] = e[j]; return &buf[i]; } void reverse() { loopi(ulen/2) swap(buf[i], buf[ulen-1-i]); } static int heapparent(int i) { return (i - 1) >> 1; } static int heapchild(int i) { return (i << 1) + 1; } void buildheap() { for(int i = ulen/2; i >= 0; i--) downheap(i); } int upheap(int i) { float score = heapscore(buf[i]); while(i > 0) { int pi = heapparent(i); if(score >= heapscore(buf[pi])) break; swap(buf[i], buf[pi]); i = pi; } return i; } T &addheap(const T &x) { add(x); return buf[upheap(ulen-1)]; } int downheap(int i) { float score = heapscore(buf[i]); for(;;) { int ci = heapchild(i); if(ci >= ulen) break; float cscore = heapscore(buf[ci]); if(score > cscore) { if(ci+1 < ulen && heapscore(buf[ci+1]) < cscore) { swap(buf[ci+1], buf[i]); i = ci+1; } else { swap(buf[ci], buf[i]); i = ci; } } else if(ci+1 < ulen && heapscore(buf[ci+1]) < score) { swap(buf[ci+1], buf[i]); i = ci+1; } else break; } return i; } T removeheap() { T e = removeunordered(0); if(ulen) downheap(0); return e; } template int htfind(const K &key) { loopi(ulen) if(htcmp(key, buf[i])) return i; return -1; } }; template struct hashset { typedef T elem; typedef const T const_elem; enum { CHUNKSIZE = 64 }; struct chain { T elem; chain *next; }; struct chainchunk { chain chains[CHUNKSIZE]; chainchunk *next; }; int size; int numelems; chain **chains; chainchunk *chunks; chain *unused; hashset(int size = 1<<10) : size(size) { numelems = 0; chunks = NULL; unused = NULL; chains = new chain *[size]; loopi(size) chains[i] = NULL; } ~hashset() { DELETEA(chains); deletechunks(); } chain *insert(uint h) { if(!unused) { chainchunk *chunk = new chainchunk; chunk->next = chunks; chunks = chunk; loopi(CHUNKSIZE-1) chunk->chains[i].next = &chunk->chains[i+1]; chunk->chains[CHUNKSIZE-1].next = unused; unused = chunk->chains; } chain *c = unused; unused = unused->next; c->next = chains[h]; chains[h] = c; numelems++; return c; } #define HTFIND(key, success, fail) \ uint h = hthash(key)&(this->size-1); \ for(chain *c = this->chains[h]; c; c = c->next) \ { \ if(htcmp(key, c->elem)) return (success); \ } \ return (fail); template T *access(const K &key) { HTFIND(key, &c->elem, NULL); } template T &access(const K &key, const E &elem) { HTFIND(key, c->elem, insert(h)->elem = elem); } template T &operator[](const K &key) { HTFIND(key, c->elem, insert(h)->elem); } template T &find(const K &key, T ¬found) { HTFIND(key, c->elem, notfound); } template const T &find(const K &key, const T ¬found) { HTFIND(key, c->elem, notfound); } template bool remove(const K &key) { uint h = hthash(key)&(size-1); for(chain **p = &chains[h], *c = chains[h]; c; p = &c->next, c = c->next) { if(htcmp(key, c->elem)) { *p = c->next; c->elem.~T(); new (&c->elem) T; c->next = unused; unused = c; numelems--; return true; } } return false; } void deletechunks() { for(chainchunk *nextchunk; chunks; chunks = nextchunk) { nextchunk = chunks->next; delete chunks; } } void clear() { if(!numelems) return; loopi(size) chains[i] = NULL; numelems = 0; unused = NULL; deletechunks(); } static inline chain *getnext(void *i) { return ((chain *)i)->next; } static inline T &getdata(void *i) { return ((chain *)i)->elem; } }; template struct hashtableentry { K key; T data; hashtableentry() {} hashtableentry(const K &key, const T &data) : key(key), data(data) {} }; template static inline bool htcmp(const U *x, const hashtableentry &y) { return htcmp(x, y.key); } template static inline bool htcmp(const U &x, const hashtableentry &y) { return htcmp(x, y.key); } template struct hashtable : hashset > { typedef hashtableentry entry; typedef struct hashset::chain chain; typedef K key; typedef T value; hashtable(int size = 1<<10) : hashset(size) {} entry &insert(const K &key, uint h) { chain *c = hashset::insert(h); c->elem.key = key; return c->elem; } T *access(const K &key) { HTFIND(key, &c->elem.data, NULL); } T &access(const K &key, const T &data) { HTFIND(key, c->elem.data, insert(key, h).data = data); } T &operator[](const K &key) { HTFIND(key, c->elem.data, insert(key, h).data); } T &find(const K &key, T ¬found) { HTFIND(key, c->elem.data, notfound); } const T &find(const K &key, const T ¬found) { HTFIND(key, c->elem.data, notfound); } static inline chain *getnext(void *i) { return ((chain *)i)->next; } static inline K &getkey(void *i) { return ((chain *)i)->elem.key; } static inline T &getdata(void *i) { return ((chain *)i)->elem.data; } }; #define enumerates(ht,t,e,b) loopi((ht).size) for(hashset::chain *enumc = (ht).chains[i]; enumc;) { t &e = enumc->elem; enumc = enumc->next; b; } #define enumeratekt(ht,k,e,t,f,b) loopi((ht).size) for(hashtable::chain *enumc = (ht).chains[i]; enumc;) { const hashtable::key &e = enumc->elem.key; t &f = enumc->elem.data; enumc = enumc->next; b; } #define enumerate(ht,t,e,b) loopi((ht).size) for(void *enumc = (ht).chains[i]; enumc;) { t &e = (ht).getdata(enumc); enumc = (ht).getnext(enumc); b; } struct unionfind { struct ufval { int rank, next; ufval() : rank(0), next(-1) {} }; vector ufvals; int find(int k) { if(k>=ufvals.length()) return k; while(ufvals[k].next>=0) k = ufvals[k].next; return k; } int compressfind(int k) { if(ufvals[k].next<0) return k; return ufvals[k].next = compressfind(ufvals[k].next); } void unite (int x, int y) { while(ufvals.length() <= max(x, y)) ufvals.add(); x = compressfind(x); y = compressfind(y); if(x==y) return; ufval &xval = ufvals[x], &yval = ufvals[y]; if(xval.rank < yval.rank) xval.next = y; else { yval.next = x; if(xval.rank==yval.rank) yval.rank++; } } }; template struct ringbuf { int index, len; T data[SIZE]; ringbuf() { clear(); } void clear() { index = len = 0; } bool empty() const { return !len; } const int length() const { return len; } T &add() { T &t = data[index]; index++; if(index >= SIZE) index -= SIZE; if(len < SIZE) len++; return t; } T &add(const T &e) { return add() = e; } T &operator[](int i) { i += index - len; return data[i < 0 ? i + SIZE : i%SIZE]; } const T &operator[](int i) const { i += index - len; return data[i < 0 ? i + SIZE : i%SIZE]; } }; template struct queue { int head, tail, len; T data[SIZE]; queue() { clear(); } void clear() { head = tail = len = 0; } int length() const { return len; } bool empty() const { return !len; } bool full() const { return len == SIZE; } T &added() { return data[tail > 0 ? tail-1 : SIZE-1]; } T &added(int offset) { return data[tail-offset > 0 ? tail-offset-1 : tail-offset-1 + SIZE]; } T &adding() { return data[tail]; } T &adding(int offset) { return data[tail+offset >= SIZE ? tail+offset - SIZE : tail+offset]; } T &add() { ASSERT(len < SIZE); T &t = data[tail]; tail = (tail + 1)%SIZE; len++; return t; } T &removing() { return data[head]; } T &removing(int offset) { return data[head+offset >= SIZE ? head+offset - SIZE : head+offset]; } T &remove() { ASSERT(len > 0); T &t = data[head]; head = (head + 1)%SIZE; len--; return t; } }; inline char *newstring(size_t l) { return new char[l+1]; } inline char *newstring(const char *s, size_t l) { return copystring(newstring(l), s, l+1); } inline char *newstring(const char *s) { return newstring(s, strlen(s)); } inline char *newstringbuf(const char *s) { return newstring(s, MAXSTRLEN-1); } const int islittleendian = 1; #ifdef SDL_BYTEORDER #define endianswap16 SDL_Swap16 #define endianswap32 SDL_Swap32 #define endianswap64 SDL_Swap64 #else inline ushort endianswap16(ushort n) { return (n<<8) | (n>>8); } inline uint endianswap32(uint n) { return (n<<24) | (n>>24) | ((n>>8)&0xFF00) | ((n<<8)&0xFF0000); } inline ullong endianswap64(ullong n) { return endianswap32(uint(n >> 32)) | ((ullong)endianswap32(uint(n)) << 32); } #endif template inline T endianswap(T n) { union { T t; uint i; } conv; conv.t = n; conv.i = endianswap32(conv.i); return conv.t; } template<> inline ushort endianswap(ushort n) { return endianswap16(n); } template<> inline short endianswap(short n) { return endianswap16(n); } template<> inline uint endianswap(uint n) { return endianswap32(n); } template<> inline int endianswap(int n) { return endianswap32(n); } template<> inline ullong endianswap(ullong n) { return endianswap64(n); } template<> inline llong endianswap(llong n) { return endianswap64(n); } template<> inline double endianswap(double n) { union { double t; uint i; } conv; conv.t = n; conv.i = endianswap64(conv.i); return conv.t; } template inline void endianswap(T *buf, int len) { for(T *end = &buf[len]; buf < end; buf++) *buf = endianswap(*buf); } template inline T endiansame(T n) { return n; } template inline void endiansame(T *buf, int len) {} #ifdef SDL_BYTEORDER #if SDL_BYTEORDER == SDL_LIL_ENDIAN #define lilswap endiansame #define bigswap endianswap #else #define lilswap endianswap #define bigswap endiansame #endif #else template inline T lilswap(T n) { return *(const uchar *)&islittleendian ? n : endianswap(n); } template inline void lilswap(T *buf, int len) { if(!*(const uchar *)&islittleendian) endianswap(buf, len); } template inline T bigswap(T n) { return *(const uchar *)&islittleendian ? endianswap(n) : n; } template inline void bigswap(T *buf, int len) { if(*(const uchar *)&islittleendian) endianswap(buf, len); } #endif /* workaround for some C platforms that have these two functions as macros - not used anywhere */ #ifdef getchar #undef getchar #endif #ifdef putchar #undef putchar #endif struct stream { #ifdef WIN32 #ifdef __GNUC__ typedef off64_t offset; #else typedef __int64 offset; #endif #else typedef off_t offset; #endif virtual ~stream() {} virtual void close() = 0; virtual bool end() = 0; virtual offset tell() { return -1; } virtual offset rawtell() { return tell(); } virtual bool seek(offset pos, int whence = SEEK_SET) { return false; } virtual offset size(); virtual offset rawsize() { return size(); } virtual int read(void *buf, int len) { return 0; } virtual int write(const void *buf, int len) { return 0; } virtual int getchar() { uchar c; return read(&c, 1) == 1 ? c : -1; } virtual bool putchar(int n) { uchar c = n; return write(&c, 1) == 1; } virtual bool getline(char *str, int len); virtual bool putstring(const char *str) { int len = (int)strlen(str); return write(str, len) == len; } virtual bool putline(const char *str) { return putstring(str) && putchar('\n'); } virtual int printf(const char *fmt, ...) PRINTFARGS(2, 3); virtual uint getcrc() { return 0; } template int put(const T *v, int n) { return write(v, n*sizeof(T))/sizeof(T); } template bool put(T n) { return write(&n, sizeof(n)) == sizeof(n); } template bool putlil(T n) { return put(lilswap(n)); } template bool putbig(T n) { return put(bigswap(n)); } template int get(T *v, int n) { return read(v, n*sizeof(T))/sizeof(T); } template T get() { T n; return read(&n, sizeof(n)) == sizeof(n) ? n : 0; } template T getlil() { return lilswap(get()); } template T getbig() { return bigswap(get()); } #ifndef STANDALONE SDL_RWops *rwops(); #endif }; template struct streambuf { stream *s; streambuf(stream *s) : s(s) {} T get() { return s->get(); } int get(T *vals, int numvals) { return s->get(vals, numvals); } void put(const T &val) { s->put(&val, 1); } void put(const T *vals, int numvals) { s->put(vals, numvals); } int length() { return s->size(); } }; enum { CT_PRINT = 1<<0, CT_SPACE = 1<<1, CT_DIGIT = 1<<2, CT_ALPHA = 1<<3, CT_LOWER = 1<<4, CT_UPPER = 1<<5, CT_UNICODE = 1<<6 }; extern const uchar cubectype[256]; static inline int iscubeprint(uchar c) { return cubectype[c]&CT_PRINT; } static inline int iscubespace(uchar c) { return cubectype[c]&CT_SPACE; } static inline int iscubealpha(uchar c) { return cubectype[c]&CT_ALPHA; } static inline int iscubealnum(uchar c) { return cubectype[c]&(CT_ALPHA|CT_DIGIT); } static inline int iscubelower(uchar c) { return cubectype[c]&CT_LOWER; } static inline int iscubeupper(uchar c) { return cubectype[c]&CT_UPPER; } static inline int cube2uni(uchar c) { extern const int cube2unichars[256]; return cube2unichars[c]; } static inline uchar uni2cube(int c) { extern const int uni2cubeoffsets[8]; extern const uchar uni2cubechars[]; return uint(c) <= 0x7FF ? uni2cubechars[uni2cubeoffsets[c>>8] + (c&0xFF)] : 0; } extern int decodeutf8(uchar *dst, int dstlen, const uchar *src, int srclen, int *carry = NULL); extern int encodeutf8(uchar *dstbuf, int dstlen, const uchar *srcbuf, int srclen, int *carry = NULL); extern char *makerelpath(const char *dir, const char *file, const char *prefix = NULL, const char *cmd = NULL); extern char *path(char *s); extern char *path(const char *s, bool copy); extern const char *parentdir(const char *directory); extern bool fileexists(const char *path, const char *mode); extern bool createdir(const char *path); extern size_t fixpackagedir(char *dir); extern const char *sethomedir(const char *dir); extern const char *addpackagedir(const char *dir); extern const char *findfile(const char *filename, const char *mode); extern stream *openrawfile(const char *filename, const char *mode); extern stream *openzipfile(const char *filename, const char *mode); extern stream *openfile(const char *filename, const char *mode); extern stream *opentempfile(const char *filename, const char *mode); extern stream *opengzfile(const char *filename, const char *mode, stream *file = NULL, int level = Z_BEST_COMPRESSION); extern stream *openutf8file(const char *filename, const char *mode, stream *file = NULL); extern char *loadfile(const char *fn, int *size, bool utf8 = true); extern bool listdir(const char *dir, bool rel, const char *ext, vector &files); extern int listfiles(const char *dir, const char *ext, vector &files); extern int listzipfiles(const char *dir, const char *ext, vector &files); extern void seedMT(uint seed); extern uint randomMT(); extern int guessnumcpus(); extern void putint(ucharbuf &p, int n); extern void putint(packetbuf &p, int n); extern void putint(vector &p, int n); extern int getint(ucharbuf &p); extern void putuint(ucharbuf &p, int n); extern void putuint(packetbuf &p, int n); extern void putuint(vector &p, int n); extern int getuint(ucharbuf &p); extern void putfloat(ucharbuf &p, float f); extern void putfloat(packetbuf &p, float f); extern void putfloat(vector &p, float f); extern float getfloat(ucharbuf &p); extern void sendstring(const char *t, ucharbuf &p); extern void sendstring(const char *t, packetbuf &p); extern void sendstring(const char *t, vector &p); extern void getstring(char *t, ucharbuf &p, int len); template static inline void getstring(char (&t)[N], ucharbuf &p) { getstring(t, p, int(N)); } extern void filtertext(char *dst, const char *src, bool whitespace = true, int len = sizeof(string)-1); #endif sauerbraten-0.0.20130203.dfsg/shared/iengine.h0000644000175000017500000005453012074035705020444 0ustar vincentvincent// the interface the game uses to access the engine extern int curtime; // current frame time extern int lastmillis; // last time extern int totalmillis; // total elapsed time extern uint totalsecs; extern int gamespeed, paused; enum { MATF_INDEX_SHIFT = 0, MATF_VOLUME_SHIFT = 2, MATF_CLIP_SHIFT = 5, MATF_FLAG_SHIFT = 8, MATF_INDEX = 3 << MATF_INDEX_SHIFT, MATF_VOLUME = 7 << MATF_VOLUME_SHIFT, MATF_CLIP = 7 << MATF_CLIP_SHIFT, MATF_FLAGS = 0xFF << MATF_FLAG_SHIFT }; enum // cube empty-space materials { MAT_AIR = 0, // the default, fill the empty space with air MAT_WATER = 1 << MATF_VOLUME_SHIFT, // fill with water, showing waves at the surface MAT_LAVA = 2 << MATF_VOLUME_SHIFT, // fill with lava MAT_GLASS = 3 << MATF_VOLUME_SHIFT, // behaves like clip but is blended blueish MAT_NOCLIP = 1 << MATF_CLIP_SHIFT, // collisions always treat cube as empty MAT_CLIP = 2 << MATF_CLIP_SHIFT, // collisions always treat cube as solid MAT_GAMECLIP = 3 << MATF_CLIP_SHIFT, // game specific clip material MAT_DEATH = 1 << MATF_FLAG_SHIFT, // force player suicide MAT_ALPHA = 4 << MATF_FLAG_SHIFT // alpha blended }; #define isliquid(mat) ((mat)==MAT_WATER || (mat)==MAT_LAVA) #define isclipped(mat) ((mat)==MAT_GLASS) #define isdeadly(mat) ((mat)==MAT_LAVA) extern void lightent(extentity &e, float height = 8.0f); extern void lightreaching(const vec &target, vec &color, vec &dir, bool fast = false, extentity *e = 0, float ambient = 0.4f); extern entity *brightestlight(const vec &target, const vec &dir); enum { RAY_BB = 1, RAY_POLY = 3, RAY_ALPHAPOLY = 7, RAY_ENTS = 9, RAY_CLIPMAT = 16, RAY_SKIPFIRST = 32, RAY_EDITMAT = 64, RAY_SHADOW = 128, RAY_PASS = 256, RAY_SKIPSKY = 512 }; extern float raycube (const vec &o, const vec &ray, float radius = 0, int mode = RAY_CLIPMAT, int size = 0, extentity *t = 0); extern float raycubepos(const vec &o, const vec &ray, vec &hit, float radius = 0, int mode = RAY_CLIPMAT, int size = 0); extern float rayfloor (const vec &o, vec &floor, int mode = 0, float radius = 0); extern bool raycubelos(const vec &o, const vec &dest, vec &hitpos); extern int thirdperson; extern bool isthirdperson(); extern bool settexture(const char *name, int clamp = 0); // octaedit enum { EDIT_FACE = 0, EDIT_TEX, EDIT_MAT, EDIT_FLIP, EDIT_COPY, EDIT_PASTE, EDIT_ROTATE, EDIT_REPLACE, EDIT_DELCUBE, EDIT_REMIP }; struct selinfo { int corner; int cx, cxs, cy, cys; ivec o, s; int grid, orient; selinfo() : corner(0), cx(0), cxs(0), cy(0), cys(0), o(0, 0, 0), s(0, 0, 0), grid(8), orient(0) {} int size() const { return s.x*s.y*s.z; } int us(int d) const { return s[d]*grid; } bool operator==(const selinfo &sel) const { return o==sel.o && s==sel.s && grid==sel.grid && orient==sel.orient; } bool validate() { extern int worldsize; if(grid <= 0 || grid >= worldsize) return false; if(o.x >= worldsize || o.y >= worldsize || o.z >= worldsize) return false; if(o.x < 0) { s.x -= (grid - 1 - o.x)/grid; o.x = 0; } if(o.y < 0) { s.y -= (grid - 1 - o.y)/grid; o.y = 0; } if(o.z < 0) { s.z -= (grid - 1 - o.z)/grid; o.z = 0; } s.x = clamp(s.x, 0, (worldsize - o.x)/grid); s.y = clamp(s.y, 0, (worldsize - o.y)/grid); s.z = clamp(s.z, 0, (worldsize - o.z)/grid); return s.x > 0 && s.y > 0 && s.z > 0; } }; struct editinfo; extern editinfo *localedit; extern bool editmode; extern bool packeditinfo(editinfo *e, int &inlen, uchar *&outbuf, int &outlen); extern bool unpackeditinfo(editinfo *&e, const uchar *inbuf, int inlen, int outlen); extern void freeeditinfo(editinfo *&e); extern void pruneundos(int maxremain = 0); extern bool noedit(bool view = false, bool msg = true); extern void toggleedit(bool force = true); extern void mpeditface(int dir, int mode, selinfo &sel, bool local); extern void mpedittex(int tex, int allfaces, selinfo &sel, bool local); extern void mpeditmat(int matid, int filter, selinfo &sel, bool local); extern void mpflip(selinfo &sel, bool local); extern void mpcopy(editinfo *&e, selinfo &sel, bool local); extern void mppaste(editinfo *&e, selinfo &sel, bool local); extern void mprotate(int cw, selinfo &sel, bool local); extern void mpreplacetex(int oldtex, int newtex, bool insel, selinfo &sel, bool local); extern void mpdelcube(selinfo &sel, bool local); extern void mpremip(bool local); // command extern int variable(const char *name, int min, int cur, int max, int *storage, identfun fun, int flags); extern float fvariable(const char *name, float min, float cur, float max, float *storage, identfun fun, int flags); extern char *svariable(const char *name, const char *cur, char **storage, identfun fun, int flags); extern void setvar(const char *name, int i, bool dofunc = true, bool doclamp = true); extern void setfvar(const char *name, float f, bool dofunc = true, bool doclamp = true); extern void setsvar(const char *name, const char *str, bool dofunc = true); extern void setvarchecked(ident *id, int val); extern void setfvarchecked(ident *id, float val); extern void setsvarchecked(ident *id, const char *val); extern void touchvar(const char *name); extern int getvar(const char *name); extern int getvarmin(const char *name); extern int getvarmax(const char *name); extern bool identexists(const char *name); extern ident *getident(const char *name); extern ident *newident(const char *name, int flags = 0); extern ident *readident(const char *name); extern ident *writeident(const char *name, int flags = 0); extern bool addcommand(const char *name, identfun fun, const char *narg); extern bool addkeyword(int type, const char *name); extern uint *compilecode(const char *p); extern void keepcode(uint *p); extern void freecode(uint *p); extern void executeret(const uint *code, tagval &result = *commandret); extern void executeret(const char *p, tagval &result = *commandret); extern char *executestr(const uint *code); extern char *executestr(const char *p); extern int execute(const uint *code); extern int execute(const char *p); extern bool executebool(const uint *code); extern bool executebool(const char *p); extern bool execfile(const char *cfgfile, bool msg = true); extern void alias(const char *name, const char *action); extern void alias(const char *name, tagval &v); extern const char *getalias(const char *name); extern const char *escapestring(const char *s); extern const char *escapeid(const char *s); static inline const char *escapeid(ident &id) { return escapeid(id.name); } extern bool validateblock(const char *s); extern void explodelist(const char *s, vector &elems, int limit = -1); extern char *indexlist(const char *s, int pos); extern int listlen(const char *s); extern void printvar(ident *id); extern void printvar(ident *id, int i); extern void printfvar(ident *id, float f); extern void printsvar(ident *id, const char *s); extern int clampvar(ident *id, int i, int minval, int maxval); extern float clampfvar(ident *id, float f, float minval, float maxval); // console enum { CON_INFO = 1<<0, CON_WARN = 1<<1, CON_ERROR = 1<<2, CON_DEBUG = 1<<3, CON_INIT = 1<<4, CON_ECHO = 1<<5 }; extern void conoutf(const char *s, ...) PRINTFARGS(1, 2); extern void conoutf(int type, const char *s, ...) PRINTFARGS(2, 3); extern void conoutfv(int type, const char *fmt, va_list args); extern FILE *getlogfile(); extern void setlogfile(const char *fname); extern void closelogfile(); extern void logoutfv(const char *fmt, va_list args); extern void logoutf(const char *fmt, ...) PRINTFARGS(1, 2); // menus extern vec menuinfrontofplayer(); extern void newgui(char *name, char *contents, char *header = NULL, char *init = NULL); extern void showgui(const char *name); extern int cleargui(int n = 0); // octa extern int lookupmaterial(const vec &o); static inline bool insideworld(const vec &o) { extern int worldsize; return o.x>=0 && o.x=0 && o.y=0 && o.z &found); extern void mpeditent(int i, const vec &o, int type, int attr1, int attr2, int attr3, int attr4, int attr5, bool local); extern vec getselpos(); extern int getworldsize(); extern int getmapversion(); extern void renderentcone(const extentity &e, const vec &dir, float radius, float angle); extern void renderentarrow(const extentity &e, const vec &dir, float radius); extern void renderentattachment(const extentity &e); extern void renderentsphere(const extentity &e, float radius); extern void renderentring(const extentity &e, float radius, int axis = 0); // main extern void fatal(const char *s, ...) PRINTFARGS(1, 2); extern void keyrepeat(bool on); // rendertext extern bool setfont(const char *name); extern void pushfont(); extern bool popfont(); extern void gettextres(int &w, int &h); extern void draw_text(const char *str, int left, int top, int r = 255, int g = 255, int b = 255, int a = 255, int cursor = -1, int maxwidth = -1); extern void draw_textf(const char *fstr, int left, int top, ...) PRINTFARGS(1, 4); extern float text_widthf(const char *str); extern void text_boundsf(const char *str, float &width, float &height, int maxwidth = -1); extern int text_visible(const char *str, float hitx, float hity, int maxwidth); extern void text_posf(const char *str, int cursor, float &cx, float &cy, int maxwidth); static inline int text_width(const char *str) { return int(ceil(text_widthf(str))); } static inline void text_bounds(const char *str, int &width, int &height, int maxwidth = -1) { float widthf, heightf; text_boundsf(str, widthf, heightf, maxwidth); width = int(ceil(widthf)); height = int(ceil(heightf)); } static inline void text_pos(const char *str, int cursor, int &cx, int &cy, int maxwidth) { float cxf, cyf; text_posf(str, cursor, cxf, cyf, maxwidth); cx = int(cxf); cy = int(cyf); } // renderva enum { DL_SHRINK = 1<<0, DL_EXPAND = 1<<1, DL_FLASH = 1<<2 }; extern void adddynlight(const vec &o, float radius, const vec &color, int fade = 0, int peak = 0, int flags = 0, float initradius = 0, const vec &initcolor = vec(0, 0, 0), physent *owner = NULL); extern void dynlightreaching(const vec &target, vec &color, vec &dir, bool hud = false); extern void removetrackeddynlights(physent *owner = NULL); // rendergl extern physent *camera1; extern vec worldpos, camdir, camright, camup; extern void disablezoom(); extern vec calcavatarpos(const vec &pos, float dist); extern void damageblend(int n); extern void damagecompass(int n, const vec &loc); extern vec minimapcenter, minimapradius, minimapscale; extern void bindminimap(); // renderparticles enum { PART_BLOOD = 0, PART_WATER, PART_SMOKE, PART_STEAM, PART_FLAME, PART_FIREBALL1, PART_FIREBALL2, PART_FIREBALL3, PART_STREAK, PART_LIGHTNING, PART_EXPLOSION, PART_EXPLOSION_BLUE, PART_SPARK, PART_EDIT, PART_SNOW, PART_MUZZLE_FLASH1, PART_MUZZLE_FLASH2, PART_MUZZLE_FLASH3, PART_HUD_ICON, PART_HUD_ICON_GREY, PART_TEXT, PART_METER, PART_METER_VS, PART_LENS_FLARE }; extern bool canaddparticles(); extern void regular_particle_splash(int type, int num, int fade, const vec &p, int color = 0xFFFFFF, float size = 1.0f, int radius = 150, int gravity = 2, int delay = 0); extern void regular_particle_flame(int type, const vec &p, float radius, float height, int color, int density = 3, float scale = 2.0f, float speed = 200.0f, float fade = 600.0f, int gravity = -15); extern void particle_splash(int type, int num, int fade, const vec &p, int color = 0xFFFFFF, float size = 1.0f, int radius = 150, int gravity = 2); extern void particle_trail(int type, int fade, const vec &from, const vec &to, int color = 0xFFFFFF, float size = 1.0f, int gravity = 20); extern void particle_text(const vec &s, const char *t, int type, int fade = 2000, int color = 0xFFFFFF, float size = 2.0f, int gravity = 0); extern void particle_textcopy(const vec &s, const char *t, int type, int fade = 2000, int color = 0xFFFFFF, float size = 2.0f, int gravity = 0); extern void particle_icon(const vec &s, int ix, int iy, int type, int fade = 2000, int color = 0xFFFFFF, float size = 2.0f, int gravity = 0); extern void particle_meter(const vec &s, float val, int type, int fade = 1, int color = 0xFFFFFF, int color2 = 0xFFFFF, float size = 2.0f); extern void particle_flare(const vec &p, const vec &dest, int fade, int type, int color = 0xFFFFFF, float size = 0.28f, physent *owner = NULL); extern void particle_fireball(const vec &dest, float max, int type, int fade = -1, int color = 0xFFFFFF, float size = 4.0f); extern void removetrackedparticles(physent *owner = NULL); // decal enum { DECAL_SCORCH = 0, DECAL_BLOOD, DECAL_BULLET }; extern void adddecal(int type, const vec ¢er, const vec &surface, float radius, const bvec &color = bvec(0xFF, 0xFF, 0xFF), int info = 0); // worldio extern bool load_world(const char *mname, const char *cname = NULL); extern bool save_world(const char *mname, bool nolms = false); extern void getmapfilenames(const char *fname, const char *cname, char *pakname, char *mapname, char *cfgname); extern uint getmapcrc(); extern void clearmapcrc(); extern bool loadents(const char *fname, vector &ents, uint *crc = NULL); // physics extern void moveplayer(physent *pl, int moveres, bool local); extern bool moveplayer(physent *pl, int moveres, bool local, int curtime); extern bool collide(physent *d, const vec &dir = vec(0, 0, 0), float cutoff = 0.0f, bool playercol = true); extern bool bounce(physent *d, float secs, float elasticity, float waterfric, float grav); extern bool bounce(physent *d, float elasticity, float waterfric, float grav); extern void avoidcollision(physent *d, const vec &dir, physent *obstacle, float space); extern bool overlapsdynent(const vec &o, float radius); extern bool movecamera(physent *pl, const vec &dir, float dist, float stepdist); extern void physicsframe(); extern void dropenttofloor(entity *e); extern bool droptofloor(vec &o, float radius, float height); extern void vecfromyawpitch(float yaw, float pitch, int move, int strafe, vec &m); extern void vectoyawpitch(const vec &v, float &yaw, float &pitch); extern bool moveplatform(physent *p, const vec &dir); extern void updatephysstate(physent *d); extern void cleardynentcache(); extern void updatedynentcache(physent *d); extern bool entinmap(dynent *d, bool avoidplayers = false); extern void findplayerspawn(dynent *d, int forceent = -1, int tag = 0); // sound enum { SND_MAP = 1<<0 }; extern int playsound(int n, const vec *loc = NULL, extentity *ent = NULL, int flags = 0, int loops = 0, int fade = 0, int chanid = -1, int radius = 0, int expire = -1); extern int playsoundname(const char *s, const vec *loc = NULL, int vol = 0, int flags = 0, int loops = 0, int fade = 0, int chanid = -1, int radius = 0, int expire = -1); extern void preloadsound(int n); extern void preloadmapsound(int n); extern bool stopsound(int n, int chanid, int fade = 0); extern void stopsounds(); extern void initsound(); // rendermodel enum { MDL_CULL_VFC = 1<<0, MDL_CULL_DIST = 1<<1, MDL_CULL_OCCLUDED = 1<<2, MDL_CULL_QUERY = 1<<3, MDL_SHADOW = 1<<4, MDL_DYNSHADOW = 1<<5, MDL_LIGHT = 1<<6, MDL_DYNLIGHT = 1<<7, MDL_FULLBRIGHT = 1<<8, MDL_NORENDER = 1<<9, MDL_LIGHT_FAST = 1<<10, MDL_HUD = 1<<11, MDL_GHOST = 1<<12 }; struct model; struct modelattach { const char *tag, *name; int anim, basetime; vec *pos; model *m; modelattach() : tag(NULL), name(NULL), anim(-1), basetime(0), pos(NULL), m(NULL) {} modelattach(const char *tag, const char *name, int anim = -1, int basetime = 0) : tag(tag), name(name), anim(anim), basetime(basetime), pos(NULL), m(NULL) {} modelattach(const char *tag, vec *pos) : tag(tag), name(NULL), anim(-1), basetime(0), pos(pos), m(NULL) {} }; extern void startmodelbatches(); extern void endmodelbatches(); extern void rendermodel(entitylight *light, const char *mdl, int anim, const vec &o, float yaw = 0, float pitch = 0, int cull = MDL_CULL_VFC | MDL_CULL_DIST | MDL_CULL_OCCLUDED | MDL_LIGHT, dynent *d = NULL, modelattach *a = NULL, int basetime = 0, int basetime2 = 0, float trans = 1); extern void abovemodel(vec &o, const char *mdl); extern void rendershadow(dynent *d); extern void renderclient(dynent *d, const char *mdlname, modelattach *attachments, int hold, int attack, int attackdelay, int lastaction, int lastpain, float fade = 1, bool ragdoll = false); extern void interpolateorientation(dynent *d, float &interpyaw, float &interppitch); extern void setbbfrommodel(dynent *d, const char *mdl); extern const char *mapmodelname(int i); extern model *loadmodel(const char *name, int i = -1, bool msg = false); extern void preloadmodel(const char *name); extern void flushpreloadedmodels(bool msg = true); // ragdoll extern void moveragdoll(dynent *d); extern void cleanragdoll(dynent *d); // server #define MAXCLIENTS 128 // DO NOT set this any higher #define MAXTRANS 5000 // max amount of data to swallow in 1 go extern int maxclients; enum { DISC_NONE = 0, DISC_EOP, DISC_LOCAL, DISC_KICK, DISC_MSGERR, DISC_IPBAN, DISC_PRIVATE, DISC_MAXCLIENTS, DISC_TIMEOUT, DISC_OVERFLOW, DISC_PASSWORD, DISC_NUM }; extern void *getclientinfo(int i); extern ENetPeer *getclientpeer(int i); extern ENetPacket *sendf(int cn, int chan, const char *format, ...); extern ENetPacket *sendfile(int cn, int chan, stream *file, const char *format = "", ...); extern void sendpacket(int cn, int chan, ENetPacket *packet, int exclude = -1); extern void flushserver(bool force); extern int getservermtu(); extern int getnumclients(); extern uint getclientip(int n); extern void localconnect(); extern const char *disconnectreason(int reason); extern void disconnect_client(int n, int reason); extern void kicknonlocalclients(int reason = DISC_NONE); extern bool hasnonlocalclients(); extern bool haslocalclients(); extern void sendserverinforeply(ucharbuf &p); extern bool requestmaster(const char *req); extern bool requestmasterf(const char *fmt, ...) PRINTFARGS(1, 2); extern bool isdedicatedserver(); // client extern void sendclientpacket(ENetPacket *packet, int chan); extern void flushclient(); extern void disconnect(bool async = false, bool cleanup = true); extern bool isconnected(bool attempt = false, bool local = true); extern const ENetAddress *connectedpeer(); extern bool multiplayer(bool msg = true); extern void neterr(const char *s, bool disc = true); extern void gets2c(); extern void notifywelcome(); // crypto extern void genprivkey(const char *seed, vector &privstr, vector &pubstr); extern bool hashstring(const char *str, char *result, int maxlen); extern void answerchallenge(const char *privstr, const char *challenge, vector &answerstr); extern void *parsepubkey(const char *pubstr); extern void freepubkey(void *pubkey); extern void *genchallenge(void *pubkey, const void *seed, int seedlen, vector &challengestr); extern void freechallenge(void *answer); extern bool checkchallenge(const char *answerstr, void *correct); // 3dgui struct Texture; struct VSlot; enum { G3D_DOWN = 1, G3D_UP = 2, G3D_PRESSED = 4, G3D_ROLLOVER = 8, G3D_DRAGGED = 16 }; enum { EDITORFOCUSED = 1, EDITORUSED, EDITORFOREVER }; struct g3d_gui { virtual ~g3d_gui() {} virtual void start(int starttime, float basescale, int *tab = NULL, bool allowinput = true) = 0; virtual void end() = 0; virtual int text(const char *text, int color, const char *icon = NULL) = 0; int textf(const char *fmt, int color, const char *icon = NULL, ...) PRINTFARGS(2, 5) { defvformatstring(str, icon, fmt); return text(str, color, icon); } virtual int button(const char *text, int color, const char *icon = NULL) = 0; int buttonf(const char *fmt, int color, const char *icon = NULL, ...) PRINTFARGS(2, 5) { defvformatstring(str, icon, fmt); return button(str, color, icon); } virtual int title(const char *text, int color, const char *icon = NULL) = 0; int titlef(const char *fmt, int color, const char *icon = NULL, ...) PRINTFARGS(2, 5) { defvformatstring(str, icon, fmt); return title(str, color, icon); } virtual void background(int color, int parentw = 0, int parenth = 0) = 0; virtual void pushlist() {} virtual void poplist() {} virtual void allowautotab(bool on) = 0; virtual bool shouldtab() { return false; } virtual void tab(const char *name = NULL, int color = 0) = 0; virtual int image(Texture *t, float scale, bool overlaid = false) = 0; virtual int texture(VSlot &vslot, float scale, bool overlaid = true) = 0; virtual int playerpreview(int model, int team, int weap, float scale, bool overlaid = false) { return 0; } virtual int modelpreview(const char *name, int anim, float scale, bool overlaid = false) { return 0; } virtual void slider(int &val, int vmin, int vmax, int color, const char *label = NULL) = 0; virtual void separator() = 0; virtual void progress(float percent) = 0; virtual void strut(float size) = 0; virtual void space(float size) = 0; virtual void spring(int weight = 1) = 0; virtual void column(int col) = 0; virtual char *keyfield(const char *name, int color, int length, int height = 0, const char *initval = NULL, int initmode = EDITORFOCUSED) = 0; virtual char *field(const char *name, int color, int length, int height = 0, const char *initval = NULL, int initmode = EDITORFOCUSED) = 0; virtual void textbox(const char *text, int width, int height, int color = 0xFFFFFF) = 0; virtual void mergehits(bool on) = 0; }; struct g3d_callback { virtual ~g3d_callback() {} int starttime() { return totalmillis; } virtual void gui(g3d_gui &g, bool firstpass) = 0; }; enum { GUI_2D = 1<<0, GUI_FOLLOW = 1<<1, GUI_FORCE_2D = 1<<2, GUI_BOTTOM = 1<<3 }; extern void g3d_addgui(g3d_callback *cb, vec &origin, int flags = 0); extern bool g3d_movecursor(int dx, int dy); extern void g3d_cursorpos(float &x, float &y); extern void g3d_resetcursor(); extern void g3d_limitscale(float scale); sauerbraten-0.0.20130203.dfsg/shared/pch.cpp0000644000175000017500000000002211164573771020127 0ustar vincentvincent#include "cube.h" sauerbraten-0.0.20130203.dfsg/shared/geom.cpp0000644000175000017500000006732211640673272020320 0ustar vincentvincent #include "cube.h" static inline float det2x2(float a, float b, float c, float d) { return a*d - b*c; } static inline float det3x3(float a1, float a2, float a3, float b1, float b2, float b3, float c1, float c2, float c3) { return a1 * det2x2(b2, b3, c2, c3) - b1 * det2x2(a2, a3, c2, c3) + c1 * det2x2(a2, a3, b2, b3); } float glmatrixf::determinant() const { float a1 = v[0], a2 = v[1], a3 = v[2], a4 = v[3], b1 = v[4], b2 = v[5], b3 = v[6], b4 = v[7], c1 = v[8], c2 = v[9], c3 = v[10], c4 = v[11], d1 = v[12], d2 = v[13], d3 = v[14], d4 = v[15]; return a1 * det3x3(b2, b3, b4, c2, c3, c4, d2, d3, d4) - b1 * det3x3(a2, a3, a4, c2, c3, c4, d2, d3, d4) + c1 * det3x3(a2, a3, a4, b2, b3, b4, d2, d3, d4) - d1 * det3x3(a2, a3, a4, b2, b3, b4, c2, c3, c4); } void glmatrixf::adjoint(const glmatrixf &m) { float a1 = m.v[0], a2 = m.v[1], a3 = m.v[2], a4 = m.v[3], b1 = m.v[4], b2 = m.v[5], b3 = m.v[6], b4 = m.v[7], c1 = m.v[8], c2 = m.v[9], c3 = m.v[10], c4 = m.v[11], d1 = m.v[12], d2 = m.v[13], d3 = m.v[14], d4 = m.v[15]; v[0] = det3x3(b2, b3, b4, c2, c3, c4, d2, d3, d4); v[1] = -det3x3(a2, a3, a4, c2, c3, c4, d2, d3, d4); v[2] = det3x3(a2, a3, a4, b2, b3, b4, d2, d3, d4); v[3] = -det3x3(a2, a3, a4, b2, b3, b4, c2, c3, c4); v[4] = -det3x3(b1, b3, b4, c1, c3, c4, d1, d3, d4); v[5] = det3x3(a1, a3, a4, c1, c3, c4, d1, d3, d4); v[6] = -det3x3(a1, a3, a4, b1, b3, b4, d1, d3, d4); v[7] = det3x3(a1, a3, a4, b1, b3, b4, c1, c3, c4); v[8] = det3x3(b1, b2, b4, c1, c2, c4, d1, d2, d4); v[9] = -det3x3(a1, a2, a4, c1, c2, c4, d1, d2, d4); v[10] = det3x3(a1, a2, a4, b1, b2, b4, d1, d2, d4); v[11] = -det3x3(a1, a2, a4, b1, b2, b4, c1, c2, c4); v[12] = -det3x3(b1, b2, b3, c1, c2, c3, d1, d2, d3); v[13] = det3x3(a1, a2, a3, c1, c2, c3, d1, d2, d3); v[14] = -det3x3(a1, a2, a3, b1, b2, b3, d1, d2, d3); v[15] = det3x3(a1, a2, a3, b1, b2, b3, c1, c2, c3); } bool glmatrixf::invert(const glmatrixf &m, float mindet) { float a1 = m.v[0], b1 = m.v[4], c1 = m.v[8], d1 = m.v[12]; adjoint(m); float det = a1*v[0] + b1*v[1] + c1*v[2] + d1*v[3]; // float det = m.determinant(); if(fabs(det) < mindet) return false; float invdet = 1/det; loopi(16) v[i] *= invdet; return true; } bool raysphereintersect(const vec ¢er, float radius, const vec &o, const vec &ray, float &dist) { vec c(center); c.sub(o); float v = c.dot(ray), inside = radius*radius - c.squaredlen(); if(inside<0 && v<0) return false; float d = inside + v*v; if(d<0) return false; dist = v - sqrt(d); return true; } bool rayrectintersect(const vec &b, const vec &s, const vec &o, const vec &ray, float &dist, int &orient) { loop(d, 3) if(ray[d]) { int dc = ray[d]<0 ? 1 : 0; float pdist = (b[d]+s[d]*dc - o[d]) / ray[d]; vec v(ray); v.mul(pdist).add(o); if(v[R[d]] >= b[R[d]] && v[R[d]] <= b[R[d]]+s[R[d]] && v[C[d]] >= b[C[d]] && v[C[d]] <= b[C[d]]+s[C[d]]) { dist = pdist; orient = 2*d+dc; return true; } } return false; } bool linecylinderintersect(const vec &from, const vec &to, const vec &start, const vec &end, float radius, float &dist) { vec d(end), m(from), n(to); d.sub(start); m.sub(start); n.sub(from); float md = m.dot(d), nd = n.dot(d), dd = d.squaredlen(); if(md < 0 && md + nd < 0) return false; if(md > dd && md + nd > dd) return false; float nn = n.squaredlen(), mn = m.dot(n), a = dd*nn - nd*nd, k = m.squaredlen() - radius*radius, c = dd*k - md*md; if(fabs(a) < 0.005f) { if(c > 0) return false; if(md < 0) dist = -mn / nn; else if(md > dd) dist = (nd - mn) / nn; else dist = 0; return true; } else if(c > 0) { float b = dd*mn - nd*md, discrim = b*b - a*c; if(discrim < 0) return false; dist = (-b - sqrtf(discrim)) / a; } else dist = 0; float offset = md + dist*nd; if(offset < 0) { if(nd <= 0) return false; dist = -md / nd; if(k + dist*(2*mn + dist*nn) > 0) return false; } else if(offset > dd) { if(nd >= 0) return false; dist = (dd - md) / nd; if(k + dd - 2*md + dist*(2*(mn-nd) + dist*nn) > 0) return false; } return dist >= 0 && dist <= 1; } extern const vec2 sincos360[721] = { vec2(1.00000000, 0.00000000), vec2(0.99984770, 0.01745241), vec2(0.99939083, 0.03489950), vec2(0.99862953, 0.05233596), vec2(0.99756405, 0.06975647), vec2(0.99619470, 0.08715574), // 0 vec2(0.99452190, 0.10452846), vec2(0.99254615, 0.12186934), vec2(0.99026807, 0.13917310), vec2(0.98768834, 0.15643447), vec2(0.98480775, 0.17364818), vec2(0.98162718, 0.19080900), // 6 vec2(0.97814760, 0.20791169), vec2(0.97437006, 0.22495105), vec2(0.97029573, 0.24192190), vec2(0.96592583, 0.25881905), vec2(0.96126170, 0.27563736), vec2(0.95630476, 0.29237170), // 12 vec2(0.95105652, 0.30901699), vec2(0.94551858, 0.32556815), vec2(0.93969262, 0.34202014), vec2(0.93358043, 0.35836795), vec2(0.92718385, 0.37460659), vec2(0.92050485, 0.39073113), // 18 vec2(0.91354546, 0.40673664), vec2(0.90630779, 0.42261826), vec2(0.89879405, 0.43837115), vec2(0.89100652, 0.45399050), vec2(0.88294759, 0.46947156), vec2(0.87461971, 0.48480962), // 24 vec2(0.86602540, 0.50000000), vec2(0.85716730, 0.51503807), vec2(0.84804810, 0.52991926), vec2(0.83867057, 0.54463904), vec2(0.82903757, 0.55919290), vec2(0.81915204, 0.57357644), // 30 vec2(0.80901699, 0.58778525), vec2(0.79863551, 0.60181502), vec2(0.78801075, 0.61566148), vec2(0.77714596, 0.62932039), vec2(0.76604444, 0.64278761), vec2(0.75470958, 0.65605903), // 36 vec2(0.74314483, 0.66913061), vec2(0.73135370, 0.68199836), vec2(0.71933980, 0.69465837), vec2(0.70710678, 0.70710678), vec2(0.69465837, 0.71933980), vec2(0.68199836, 0.73135370), // 42 vec2(0.66913061, 0.74314483), vec2(0.65605903, 0.75470958), vec2(0.64278761, 0.76604444), vec2(0.62932039, 0.77714596), vec2(0.61566148, 0.78801075), vec2(0.60181502, 0.79863551), // 48 vec2(0.58778525, 0.80901699), vec2(0.57357644, 0.81915204), vec2(0.55919290, 0.82903757), vec2(0.54463904, 0.83867057), vec2(0.52991926, 0.84804810), vec2(0.51503807, 0.85716730), // 54 vec2(0.50000000, 0.86602540), vec2(0.48480962, 0.87461971), vec2(0.46947156, 0.88294759), vec2(0.45399050, 0.89100652), vec2(0.43837115, 0.89879405), vec2(0.42261826, 0.90630779), // 60 vec2(0.40673664, 0.91354546), vec2(0.39073113, 0.92050485), vec2(0.37460659, 0.92718385), vec2(0.35836795, 0.93358043), vec2(0.34202014, 0.93969262), vec2(0.32556815, 0.94551858), // 66 vec2(0.30901699, 0.95105652), vec2(0.29237170, 0.95630476), vec2(0.27563736, 0.96126170), vec2(0.25881905, 0.96592583), vec2(0.24192190, 0.97029573), vec2(0.22495105, 0.97437006), // 72 vec2(0.20791169, 0.97814760), vec2(0.19080900, 0.98162718), vec2(0.17364818, 0.98480775), vec2(0.15643447, 0.98768834), vec2(0.13917310, 0.99026807), vec2(0.12186934, 0.99254615), // 78 vec2(0.10452846, 0.99452190), vec2(0.08715574, 0.99619470), vec2(0.06975647, 0.99756405), vec2(0.05233596, 0.99862953), vec2(0.03489950, 0.99939083), vec2(0.01745241, 0.99984770), // 84 vec2(0.00000000, 1.00000000), vec2(-0.01745241, 0.99984770), vec2(-0.03489950, 0.99939083), vec2(-0.05233596, 0.99862953), vec2(-0.06975647, 0.99756405), vec2(-0.08715574, 0.99619470), // 90 vec2(-0.10452846, 0.99452190), vec2(-0.12186934, 0.99254615), vec2(-0.13917310, 0.99026807), vec2(-0.15643447, 0.98768834), vec2(-0.17364818, 0.98480775), vec2(-0.19080900, 0.98162718), // 96 vec2(-0.20791169, 0.97814760), vec2(-0.22495105, 0.97437006), vec2(-0.24192190, 0.97029573), vec2(-0.25881905, 0.96592583), vec2(-0.27563736, 0.96126170), vec2(-0.29237170, 0.95630476), // 102 vec2(-0.30901699, 0.95105652), vec2(-0.32556815, 0.94551858), vec2(-0.34202014, 0.93969262), vec2(-0.35836795, 0.93358043), vec2(-0.37460659, 0.92718385), vec2(-0.39073113, 0.92050485), // 108 vec2(-0.40673664, 0.91354546), vec2(-0.42261826, 0.90630779), vec2(-0.43837115, 0.89879405), vec2(-0.45399050, 0.89100652), vec2(-0.46947156, 0.88294759), vec2(-0.48480962, 0.87461971), // 114 vec2(-0.50000000, 0.86602540), vec2(-0.51503807, 0.85716730), vec2(-0.52991926, 0.84804810), vec2(-0.54463904, 0.83867057), vec2(-0.55919290, 0.82903757), vec2(-0.57357644, 0.81915204), // 120 vec2(-0.58778525, 0.80901699), vec2(-0.60181502, 0.79863551), vec2(-0.61566148, 0.78801075), vec2(-0.62932039, 0.77714596), vec2(-0.64278761, 0.76604444), vec2(-0.65605903, 0.75470958), // 126 vec2(-0.66913061, 0.74314483), vec2(-0.68199836, 0.73135370), vec2(-0.69465837, 0.71933980), vec2(-0.70710678, 0.70710678), vec2(-0.71933980, 0.69465837), vec2(-0.73135370, 0.68199836), // 132 vec2(-0.74314483, 0.66913061), vec2(-0.75470958, 0.65605903), vec2(-0.76604444, 0.64278761), vec2(-0.77714596, 0.62932039), vec2(-0.78801075, 0.61566148), vec2(-0.79863551, 0.60181502), // 138 vec2(-0.80901699, 0.58778525), vec2(-0.81915204, 0.57357644), vec2(-0.82903757, 0.55919290), vec2(-0.83867057, 0.54463904), vec2(-0.84804810, 0.52991926), vec2(-0.85716730, 0.51503807), // 144 vec2(-0.86602540, 0.50000000), vec2(-0.87461971, 0.48480962), vec2(-0.88294759, 0.46947156), vec2(-0.89100652, 0.45399050), vec2(-0.89879405, 0.43837115), vec2(-0.90630779, 0.42261826), // 150 vec2(-0.91354546, 0.40673664), vec2(-0.92050485, 0.39073113), vec2(-0.92718385, 0.37460659), vec2(-0.93358043, 0.35836795), vec2(-0.93969262, 0.34202014), vec2(-0.94551858, 0.32556815), // 156 vec2(-0.95105652, 0.30901699), vec2(-0.95630476, 0.29237170), vec2(-0.96126170, 0.27563736), vec2(-0.96592583, 0.25881905), vec2(-0.97029573, 0.24192190), vec2(-0.97437006, 0.22495105), // 162 vec2(-0.97814760, 0.20791169), vec2(-0.98162718, 0.19080900), vec2(-0.98480775, 0.17364818), vec2(-0.98768834, 0.15643447), vec2(-0.99026807, 0.13917310), vec2(-0.99254615, 0.12186934), // 168 vec2(-0.99452190, 0.10452846), vec2(-0.99619470, 0.08715574), vec2(-0.99756405, 0.06975647), vec2(-0.99862953, 0.05233596), vec2(-0.99939083, 0.03489950), vec2(-0.99984770, 0.01745241), // 174 vec2(-1.00000000, 0.00000000), vec2(-0.99984770, -0.01745241), vec2(-0.99939083, -0.03489950), vec2(-0.99862953, -0.05233596), vec2(-0.99756405, -0.06975647), vec2(-0.99619470, -0.08715574), // 180 vec2(-0.99452190, -0.10452846), vec2(-0.99254615, -0.12186934), vec2(-0.99026807, -0.13917310), vec2(-0.98768834, -0.15643447), vec2(-0.98480775, -0.17364818), vec2(-0.98162718, -0.19080900), // 186 vec2(-0.97814760, -0.20791169), vec2(-0.97437006, -0.22495105), vec2(-0.97029573, -0.24192190), vec2(-0.96592583, -0.25881905), vec2(-0.96126170, -0.27563736), vec2(-0.95630476, -0.29237170), // 192 vec2(-0.95105652, -0.30901699), vec2(-0.94551858, -0.32556815), vec2(-0.93969262, -0.34202014), vec2(-0.93358043, -0.35836795), vec2(-0.92718385, -0.37460659), vec2(-0.92050485, -0.39073113), // 198 vec2(-0.91354546, -0.40673664), vec2(-0.90630779, -0.42261826), vec2(-0.89879405, -0.43837115), vec2(-0.89100652, -0.45399050), vec2(-0.88294759, -0.46947156), vec2(-0.87461971, -0.48480962), // 204 vec2(-0.86602540, -0.50000000), vec2(-0.85716730, -0.51503807), vec2(-0.84804810, -0.52991926), vec2(-0.83867057, -0.54463904), vec2(-0.82903757, -0.55919290), vec2(-0.81915204, -0.57357644), // 210 vec2(-0.80901699, -0.58778525), vec2(-0.79863551, -0.60181502), vec2(-0.78801075, -0.61566148), vec2(-0.77714596, -0.62932039), vec2(-0.76604444, -0.64278761), vec2(-0.75470958, -0.65605903), // 216 vec2(-0.74314483, -0.66913061), vec2(-0.73135370, -0.68199836), vec2(-0.71933980, -0.69465837), vec2(-0.70710678, -0.70710678), vec2(-0.69465837, -0.71933980), vec2(-0.68199836, -0.73135370), // 222 vec2(-0.66913061, -0.74314483), vec2(-0.65605903, -0.75470958), vec2(-0.64278761, -0.76604444), vec2(-0.62932039, -0.77714596), vec2(-0.61566148, -0.78801075), vec2(-0.60181502, -0.79863551), // 228 vec2(-0.58778525, -0.80901699), vec2(-0.57357644, -0.81915204), vec2(-0.55919290, -0.82903757), vec2(-0.54463904, -0.83867057), vec2(-0.52991926, -0.84804810), vec2(-0.51503807, -0.85716730), // 234 vec2(-0.50000000, -0.86602540), vec2(-0.48480962, -0.87461971), vec2(-0.46947156, -0.88294759), vec2(-0.45399050, -0.89100652), vec2(-0.43837115, -0.89879405), vec2(-0.42261826, -0.90630779), // 240 vec2(-0.40673664, -0.91354546), vec2(-0.39073113, -0.92050485), vec2(-0.37460659, -0.92718385), vec2(-0.35836795, -0.93358043), vec2(-0.34202014, -0.93969262), vec2(-0.32556815, -0.94551858), // 246 vec2(-0.30901699, -0.95105652), vec2(-0.29237170, -0.95630476), vec2(-0.27563736, -0.96126170), vec2(-0.25881905, -0.96592583), vec2(-0.24192190, -0.97029573), vec2(-0.22495105, -0.97437006), // 252 vec2(-0.20791169, -0.97814760), vec2(-0.19080900, -0.98162718), vec2(-0.17364818, -0.98480775), vec2(-0.15643447, -0.98768834), vec2(-0.13917310, -0.99026807), vec2(-0.12186934, -0.99254615), // 258 vec2(-0.10452846, -0.99452190), vec2(-0.08715574, -0.99619470), vec2(-0.06975647, -0.99756405), vec2(-0.05233596, -0.99862953), vec2(-0.03489950, -0.99939083), vec2(-0.01745241, -0.99984770), // 264 vec2(-0.00000000, -1.00000000), vec2(0.01745241, -0.99984770), vec2(0.03489950, -0.99939083), vec2(0.05233596, -0.99862953), vec2(0.06975647, -0.99756405), vec2(0.08715574, -0.99619470), // 270 vec2(0.10452846, -0.99452190), vec2(0.12186934, -0.99254615), vec2(0.13917310, -0.99026807), vec2(0.15643447, -0.98768834), vec2(0.17364818, -0.98480775), vec2(0.19080900, -0.98162718), // 276 vec2(0.20791169, -0.97814760), vec2(0.22495105, -0.97437006), vec2(0.24192190, -0.97029573), vec2(0.25881905, -0.96592583), vec2(0.27563736, -0.96126170), vec2(0.29237170, -0.95630476), // 282 vec2(0.30901699, -0.95105652), vec2(0.32556815, -0.94551858), vec2(0.34202014, -0.93969262), vec2(0.35836795, -0.93358043), vec2(0.37460659, -0.92718385), vec2(0.39073113, -0.92050485), // 288 vec2(0.40673664, -0.91354546), vec2(0.42261826, -0.90630779), vec2(0.43837115, -0.89879405), vec2(0.45399050, -0.89100652), vec2(0.46947156, -0.88294759), vec2(0.48480962, -0.87461971), // 294 vec2(0.50000000, -0.86602540), vec2(0.51503807, -0.85716730), vec2(0.52991926, -0.84804810), vec2(0.54463904, -0.83867057), vec2(0.55919290, -0.82903757), vec2(0.57357644, -0.81915204), // 300 vec2(0.58778525, -0.80901699), vec2(0.60181502, -0.79863551), vec2(0.61566148, -0.78801075), vec2(0.62932039, -0.77714596), vec2(0.64278761, -0.76604444), vec2(0.65605903, -0.75470958), // 306 vec2(0.66913061, -0.74314483), vec2(0.68199836, -0.73135370), vec2(0.69465837, -0.71933980), vec2(0.70710678, -0.70710678), vec2(0.71933980, -0.69465837), vec2(0.73135370, -0.68199836), // 312 vec2(0.74314483, -0.66913061), vec2(0.75470958, -0.65605903), vec2(0.76604444, -0.64278761), vec2(0.77714596, -0.62932039), vec2(0.78801075, -0.61566148), vec2(0.79863551, -0.60181502), // 318 vec2(0.80901699, -0.58778525), vec2(0.81915204, -0.57357644), vec2(0.82903757, -0.55919290), vec2(0.83867057, -0.54463904), vec2(0.84804810, -0.52991926), vec2(0.85716730, -0.51503807), // 324 vec2(0.86602540, -0.50000000), vec2(0.87461971, -0.48480962), vec2(0.88294759, -0.46947156), vec2(0.89100652, -0.45399050), vec2(0.89879405, -0.43837115), vec2(0.90630779, -0.42261826), // 330 vec2(0.91354546, -0.40673664), vec2(0.92050485, -0.39073113), vec2(0.92718385, -0.37460659), vec2(0.93358043, -0.35836795), vec2(0.93969262, -0.34202014), vec2(0.94551858, -0.32556815), // 336 vec2(0.95105652, -0.30901699), vec2(0.95630476, -0.29237170), vec2(0.96126170, -0.27563736), vec2(0.96592583, -0.25881905), vec2(0.97029573, -0.24192190), vec2(0.97437006, -0.22495105), // 342 vec2(0.97814760, -0.20791169), vec2(0.98162718, -0.19080900), vec2(0.98480775, -0.17364818), vec2(0.98768834, -0.15643447), vec2(0.99026807, -0.13917310), vec2(0.99254615, -0.12186934), // 348 vec2(0.99452190, -0.10452846), vec2(0.99619470, -0.08715574), vec2(0.99756405, -0.06975647), vec2(0.99862953, -0.05233596), vec2(0.99939083, -0.03489950), vec2(0.99984770, -0.01745241), // 354 vec2(1.00000000, 0.00000000), vec2(0.99984770, 0.01745241), vec2(0.99939083, 0.03489950), vec2(0.99862953, 0.05233596), vec2(0.99756405, 0.06975647), vec2(0.99619470, 0.08715574), // 360 vec2(0.99452190, 0.10452846), vec2(0.99254615, 0.12186934), vec2(0.99026807, 0.13917310), vec2(0.98768834, 0.15643447), vec2(0.98480775, 0.17364818), vec2(0.98162718, 0.19080900), // 366 vec2(0.97814760, 0.20791169), vec2(0.97437006, 0.22495105), vec2(0.97029573, 0.24192190), vec2(0.96592583, 0.25881905), vec2(0.96126170, 0.27563736), vec2(0.95630476, 0.29237170), // 372 vec2(0.95105652, 0.30901699), vec2(0.94551858, 0.32556815), vec2(0.93969262, 0.34202014), vec2(0.93358043, 0.35836795), vec2(0.92718385, 0.37460659), vec2(0.92050485, 0.39073113), // 378 vec2(0.91354546, 0.40673664), vec2(0.90630779, 0.42261826), vec2(0.89879405, 0.43837115), vec2(0.89100652, 0.45399050), vec2(0.88294759, 0.46947156), vec2(0.87461971, 0.48480962), // 384 vec2(0.86602540, 0.50000000), vec2(0.85716730, 0.51503807), vec2(0.84804810, 0.52991926), vec2(0.83867057, 0.54463904), vec2(0.82903757, 0.55919290), vec2(0.81915204, 0.57357644), // 390 vec2(0.80901699, 0.58778525), vec2(0.79863551, 0.60181502), vec2(0.78801075, 0.61566148), vec2(0.77714596, 0.62932039), vec2(0.76604444, 0.64278761), vec2(0.75470958, 0.65605903), // 396 vec2(0.74314483, 0.66913061), vec2(0.73135370, 0.68199836), vec2(0.71933980, 0.69465837), vec2(0.70710678, 0.70710678), vec2(0.69465837, 0.71933980), vec2(0.68199836, 0.73135370), // 402 vec2(0.66913061, 0.74314483), vec2(0.65605903, 0.75470958), vec2(0.64278761, 0.76604444), vec2(0.62932039, 0.77714596), vec2(0.61566148, 0.78801075), vec2(0.60181502, 0.79863551), // 408 vec2(0.58778525, 0.80901699), vec2(0.57357644, 0.81915204), vec2(0.55919290, 0.82903757), vec2(0.54463904, 0.83867057), vec2(0.52991926, 0.84804810), vec2(0.51503807, 0.85716730), // 414 vec2(0.50000000, 0.86602540), vec2(0.48480962, 0.87461971), vec2(0.46947156, 0.88294759), vec2(0.45399050, 0.89100652), vec2(0.43837115, 0.89879405), vec2(0.42261826, 0.90630779), // 420 vec2(0.40673664, 0.91354546), vec2(0.39073113, 0.92050485), vec2(0.37460659, 0.92718385), vec2(0.35836795, 0.93358043), vec2(0.34202014, 0.93969262), vec2(0.32556815, 0.94551858), // 426 vec2(0.30901699, 0.95105652), vec2(0.29237170, 0.95630476), vec2(0.27563736, 0.96126170), vec2(0.25881905, 0.96592583), vec2(0.24192190, 0.97029573), vec2(0.22495105, 0.97437006), // 432 vec2(0.20791169, 0.97814760), vec2(0.19080900, 0.98162718), vec2(0.17364818, 0.98480775), vec2(0.15643447, 0.98768834), vec2(0.13917310, 0.99026807), vec2(0.12186934, 0.99254615), // 438 vec2(0.10452846, 0.99452190), vec2(0.08715574, 0.99619470), vec2(0.06975647, 0.99756405), vec2(0.05233596, 0.99862953), vec2(0.03489950, 0.99939083), vec2(0.01745241, 0.99984770), // 444 vec2(0.00000000, 1.00000000), vec2(-0.01745241, 0.99984770), vec2(-0.03489950, 0.99939083), vec2(-0.05233596, 0.99862953), vec2(-0.06975647, 0.99756405), vec2(-0.08715574, 0.99619470), // 450 vec2(-0.10452846, 0.99452190), vec2(-0.12186934, 0.99254615), vec2(-0.13917310, 0.99026807), vec2(-0.15643447, 0.98768834), vec2(-0.17364818, 0.98480775), vec2(-0.19080900, 0.98162718), // 456 vec2(-0.20791169, 0.97814760), vec2(-0.22495105, 0.97437006), vec2(-0.24192190, 0.97029573), vec2(-0.25881905, 0.96592583), vec2(-0.27563736, 0.96126170), vec2(-0.29237170, 0.95630476), // 462 vec2(-0.30901699, 0.95105652), vec2(-0.32556815, 0.94551858), vec2(-0.34202014, 0.93969262), vec2(-0.35836795, 0.93358043), vec2(-0.37460659, 0.92718385), vec2(-0.39073113, 0.92050485), // 468 vec2(-0.40673664, 0.91354546), vec2(-0.42261826, 0.90630779), vec2(-0.43837115, 0.89879405), vec2(-0.45399050, 0.89100652), vec2(-0.46947156, 0.88294759), vec2(-0.48480962, 0.87461971), // 474 vec2(-0.50000000, 0.86602540), vec2(-0.51503807, 0.85716730), vec2(-0.52991926, 0.84804810), vec2(-0.54463904, 0.83867057), vec2(-0.55919290, 0.82903757), vec2(-0.57357644, 0.81915204), // 480 vec2(-0.58778525, 0.80901699), vec2(-0.60181502, 0.79863551), vec2(-0.61566148, 0.78801075), vec2(-0.62932039, 0.77714596), vec2(-0.64278761, 0.76604444), vec2(-0.65605903, 0.75470958), // 486 vec2(-0.66913061, 0.74314483), vec2(-0.68199836, 0.73135370), vec2(-0.69465837, 0.71933980), vec2(-0.70710678, 0.70710678), vec2(-0.71933980, 0.69465837), vec2(-0.73135370, 0.68199836), // 492 vec2(-0.74314483, 0.66913061), vec2(-0.75470958, 0.65605903), vec2(-0.76604444, 0.64278761), vec2(-0.77714596, 0.62932039), vec2(-0.78801075, 0.61566148), vec2(-0.79863551, 0.60181502), // 498 vec2(-0.80901699, 0.58778525), vec2(-0.81915204, 0.57357644), vec2(-0.82903757, 0.55919290), vec2(-0.83867057, 0.54463904), vec2(-0.84804810, 0.52991926), vec2(-0.85716730, 0.51503807), // 504 vec2(-0.86602540, 0.50000000), vec2(-0.87461971, 0.48480962), vec2(-0.88294759, 0.46947156), vec2(-0.89100652, 0.45399050), vec2(-0.89879405, 0.43837115), vec2(-0.90630779, 0.42261826), // 510 vec2(-0.91354546, 0.40673664), vec2(-0.92050485, 0.39073113), vec2(-0.92718385, 0.37460659), vec2(-0.93358043, 0.35836795), vec2(-0.93969262, 0.34202014), vec2(-0.94551858, 0.32556815), // 516 vec2(-0.95105652, 0.30901699), vec2(-0.95630476, 0.29237170), vec2(-0.96126170, 0.27563736), vec2(-0.96592583, 0.25881905), vec2(-0.97029573, 0.24192190), vec2(-0.97437006, 0.22495105), // 522 vec2(-0.97814760, 0.20791169), vec2(-0.98162718, 0.19080900), vec2(-0.98480775, 0.17364818), vec2(-0.98768834, 0.15643447), vec2(-0.99026807, 0.13917310), vec2(-0.99254615, 0.12186934), // 528 vec2(-0.99452190, 0.10452846), vec2(-0.99619470, 0.08715574), vec2(-0.99756405, 0.06975647), vec2(-0.99862953, 0.05233596), vec2(-0.99939083, 0.03489950), vec2(-0.99984770, 0.01745241), // 534 vec2(-1.00000000, 0.00000000), vec2(-0.99984770, -0.01745241), vec2(-0.99939083, -0.03489950), vec2(-0.99862953, -0.05233596), vec2(-0.99756405, -0.06975647), vec2(-0.99619470, -0.08715574), // 540 vec2(-0.99452190, -0.10452846), vec2(-0.99254615, -0.12186934), vec2(-0.99026807, -0.13917310), vec2(-0.98768834, -0.15643447), vec2(-0.98480775, -0.17364818), vec2(-0.98162718, -0.19080900), // 546 vec2(-0.97814760, -0.20791169), vec2(-0.97437006, -0.22495105), vec2(-0.97029573, -0.24192190), vec2(-0.96592583, -0.25881905), vec2(-0.96126170, -0.27563736), vec2(-0.95630476, -0.29237170), // 552 vec2(-0.95105652, -0.30901699), vec2(-0.94551858, -0.32556815), vec2(-0.93969262, -0.34202014), vec2(-0.93358043, -0.35836795), vec2(-0.92718385, -0.37460659), vec2(-0.92050485, -0.39073113), // 558 vec2(-0.91354546, -0.40673664), vec2(-0.90630779, -0.42261826), vec2(-0.89879405, -0.43837115), vec2(-0.89100652, -0.45399050), vec2(-0.88294759, -0.46947156), vec2(-0.87461971, -0.48480962), // 564 vec2(-0.86602540, -0.50000000), vec2(-0.85716730, -0.51503807), vec2(-0.84804810, -0.52991926), vec2(-0.83867057, -0.54463904), vec2(-0.82903757, -0.55919290), vec2(-0.81915204, -0.57357644), // 570 vec2(-0.80901699, -0.58778525), vec2(-0.79863551, -0.60181502), vec2(-0.78801075, -0.61566148), vec2(-0.77714596, -0.62932039), vec2(-0.76604444, -0.64278761), vec2(-0.75470958, -0.65605903), // 576 vec2(-0.74314483, -0.66913061), vec2(-0.73135370, -0.68199836), vec2(-0.71933980, -0.69465837), vec2(-0.70710678, -0.70710678), vec2(-0.69465837, -0.71933980), vec2(-0.68199836, -0.73135370), // 582 vec2(-0.66913061, -0.74314483), vec2(-0.65605903, -0.75470958), vec2(-0.64278761, -0.76604444), vec2(-0.62932039, -0.77714596), vec2(-0.61566148, -0.78801075), vec2(-0.60181502, -0.79863551), // 588 vec2(-0.58778525, -0.80901699), vec2(-0.57357644, -0.81915204), vec2(-0.55919290, -0.82903757), vec2(-0.54463904, -0.83867057), vec2(-0.52991926, -0.84804810), vec2(-0.51503807, -0.85716730), // 594 vec2(-0.50000000, -0.86602540), vec2(-0.48480962, -0.87461971), vec2(-0.46947156, -0.88294759), vec2(-0.45399050, -0.89100652), vec2(-0.43837115, -0.89879405), vec2(-0.42261826, -0.90630779), // 600 vec2(-0.40673664, -0.91354546), vec2(-0.39073113, -0.92050485), vec2(-0.37460659, -0.92718385), vec2(-0.35836795, -0.93358043), vec2(-0.34202014, -0.93969262), vec2(-0.32556815, -0.94551858), // 606 vec2(-0.30901699, -0.95105652), vec2(-0.29237170, -0.95630476), vec2(-0.27563736, -0.96126170), vec2(-0.25881905, -0.96592583), vec2(-0.24192190, -0.97029573), vec2(-0.22495105, -0.97437006), // 612 vec2(-0.20791169, -0.97814760), vec2(-0.19080900, -0.98162718), vec2(-0.17364818, -0.98480775), vec2(-0.15643447, -0.98768834), vec2(-0.13917310, -0.99026807), vec2(-0.12186934, -0.99254615), // 618 vec2(-0.10452846, -0.99452190), vec2(-0.08715574, -0.99619470), vec2(-0.06975647, -0.99756405), vec2(-0.05233596, -0.99862953), vec2(-0.03489950, -0.99939083), vec2(-0.01745241, -0.99984770), // 624 vec2(-0.00000000, -1.00000000), vec2(0.01745241, -0.99984770), vec2(0.03489950, -0.99939083), vec2(0.05233596, -0.99862953), vec2(0.06975647, -0.99756405), vec2(0.08715574, -0.99619470), // 630 vec2(0.10452846, -0.99452190), vec2(0.12186934, -0.99254615), vec2(0.13917310, -0.99026807), vec2(0.15643447, -0.98768834), vec2(0.17364818, -0.98480775), vec2(0.19080900, -0.98162718), // 636 vec2(0.20791169, -0.97814760), vec2(0.22495105, -0.97437006), vec2(0.24192190, -0.97029573), vec2(0.25881905, -0.96592583), vec2(0.27563736, -0.96126170), vec2(0.29237170, -0.95630476), // 642 vec2(0.30901699, -0.95105652), vec2(0.32556815, -0.94551858), vec2(0.34202014, -0.93969262), vec2(0.35836795, -0.93358043), vec2(0.37460659, -0.92718385), vec2(0.39073113, -0.92050485), // 648 vec2(0.40673664, -0.91354546), vec2(0.42261826, -0.90630779), vec2(0.43837115, -0.89879405), vec2(0.45399050, -0.89100652), vec2(0.46947156, -0.88294759), vec2(0.48480962, -0.87461971), // 654 vec2(0.50000000, -0.86602540), vec2(0.51503807, -0.85716730), vec2(0.52991926, -0.84804810), vec2(0.54463904, -0.83867057), vec2(0.55919290, -0.82903757), vec2(0.57357644, -0.81915204), // 660 vec2(0.58778525, -0.80901699), vec2(0.60181502, -0.79863551), vec2(0.61566148, -0.78801075), vec2(0.62932039, -0.77714596), vec2(0.64278761, -0.76604444), vec2(0.65605903, -0.75470958), // 666 vec2(0.66913061, -0.74314483), vec2(0.68199836, -0.73135370), vec2(0.69465837, -0.71933980), vec2(0.70710678, -0.70710678), vec2(0.71933980, -0.69465837), vec2(0.73135370, -0.68199836), // 672 vec2(0.74314483, -0.66913061), vec2(0.75470958, -0.65605903), vec2(0.76604444, -0.64278761), vec2(0.77714596, -0.62932039), vec2(0.78801075, -0.61566148), vec2(0.79863551, -0.60181502), // 678 vec2(0.80901699, -0.58778525), vec2(0.81915204, -0.57357644), vec2(0.82903757, -0.55919290), vec2(0.83867057, -0.54463904), vec2(0.84804810, -0.52991926), vec2(0.85716730, -0.51503807), // 684 vec2(0.86602540, -0.50000000), vec2(0.87461971, -0.48480962), vec2(0.88294759, -0.46947156), vec2(0.89100652, -0.45399050), vec2(0.89879405, -0.43837115), vec2(0.90630779, -0.42261826), // 690 vec2(0.91354546, -0.40673664), vec2(0.92050485, -0.39073113), vec2(0.92718385, -0.37460659), vec2(0.93358043, -0.35836795), vec2(0.93969262, -0.34202014), vec2(0.94551858, -0.32556815), // 696 vec2(0.95105652, -0.30901699), vec2(0.95630476, -0.29237170), vec2(0.96126170, -0.27563736), vec2(0.96592583, -0.25881905), vec2(0.97029573, -0.24192190), vec2(0.97437006, -0.22495105), // 702 vec2(0.97814760, -0.20791169), vec2(0.98162718, -0.19080900), vec2(0.98480775, -0.17364818), vec2(0.98768834, -0.15643447), vec2(0.99026807, -0.13917310), vec2(0.99254615, -0.12186934), // 708 vec2(0.99452190, -0.10452846), vec2(0.99619470, -0.08715574), vec2(0.99756405, -0.06975647), vec2(0.99862953, -0.05233596), vec2(0.99939083, -0.03489950), vec2(0.99984770, -0.01745241), // 714 vec2(1.00000000, 0.00000000) // 720 }; sauerbraten-0.0.20130203.dfsg/shared/stream.cpp0000644000175000017500000010740712103333460020646 0ustar vincentvincent#include "cube.h" ///////////////////////// character conversion /////////////// #define CUBECTYPE(s, p, d, a, A, u, U) \ 0, U, U, U, U, U, U, U, U, s, s, s, s, s, U, U, \ U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, \ s, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, \ d, d, d, d, d, d, d, d, d, d, p, p, p, p, p, p, \ p, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, \ A, A, A, A, A, A, A, A, A, A, A, p, p, p, p, p, \ p, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, \ a, a, a, a, a, a, a, a, a, a, a, p, p, p, p, U, \ U, u, u, u, u, u, u, u, u, u, u, u, u, u, u, u, \ u, u, u, u, u, u, u, u, u, u, u, u, u, u, u, U, \ u, U, u, U, u, U, u, U, u, U, u, U, u, U, u, U, \ u, U, u, U, u, U, u, U, u, U, u, U, u, U, u, U, \ u, U, u, U, u, U, u, U, U, u, U, u, U, u, U, U, \ U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, \ U, U, U, U, u, u, u, u, u, u, u, u, u, u, u, u, \ u, u, u, u, u, u, u, u, u, u, u, u, u, u, U, u extern const uchar cubectype[256] = { CUBECTYPE(CT_SPACE, CT_PRINT, CT_PRINT|CT_DIGIT, CT_PRINT|CT_ALPHA|CT_LOWER, CT_PRINT|CT_ALPHA|CT_UPPER, CT_PRINT|CT_UNICODE|CT_ALPHA|CT_LOWER, CT_PRINT|CT_UNICODE|CT_ALPHA|CT_UPPER) }; extern const int cube2unichars[256] = { 0, 192, 193, 194, 195, 196, 197, 198, 199, 9, 10, 11, 12, 13, 200, 201, 202, 203, 204, 205, 206, 207, 209, 210, 211, 212, 213, 214, 216, 217, 218, 219, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 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, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 220, 221, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 241, 242, 243, 244, 245, 246, 248, 249, 250, 251, 252, 253, 255, 0x104, 0x105, 0x106, 0x107, 0x10C, 0x10D, 0x10E, 0x10F, 0x118, 0x119, 0x11A, 0x11B, 0x11E, 0x11F, 0x130, 0x131, 0x141, 0x142, 0x143, 0x144, 0x147, 0x148, 0x150, 0x151, 0x152, 0x153, 0x158, 0x159, 0x15A, 0x15B, 0x15E, 0x15F, 0x160, 0x161, 0x164, 0x165, 0x16E, 0x16F, 0x170, 0x171, 0x178, 0x179, 0x17A, 0x17B, 0x17C, 0x17D, 0x17E, 0x404, 0x411, 0x413, 0x414, 0x416, 0x417, 0x418, 0x419, 0x41B, 0x41F, 0x423, 0x424, 0x426, 0x427, 0x428, 0x429, 0x42A, 0x42B, 0x42C, 0x42D, 0x42E, 0x42F, 0x431, 0x432, 0x433, 0x434, 0x436, 0x437, 0x438, 0x439, 0x43A, 0x43B, 0x43C, 0x43D, 0x43F, 0x442, 0x444, 0x446, 0x447, 0x448, 0x449, 0x44A, 0x44B, 0x44C, 0x44D, 0x44E, 0x44F, 0x454, 0x490, 0x491 }; extern const int uni2cubeoffsets[8] = { 0, 256, 658, 658, 512, 658, 658, 658 }; extern const uchar uni2cubechars[878] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 11, 12, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 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, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 14, 15, 16, 17, 18, 19, 20, 21, 0, 22, 23, 24, 25, 26, 27, 0, 28, 29, 30, 31, 127, 128, 0, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 0, 146, 147, 148, 149, 150, 151, 0, 152, 153, 154, 155, 156, 157, 0, 158, 0, 0, 0, 0, 159, 160, 161, 162, 0, 0, 0, 0, 163, 164, 165, 166, 0, 0, 0, 0, 0, 0, 0, 0, 167, 168, 169, 170, 0, 0, 171, 172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 173, 174, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 175, 176, 177, 178, 0, 0, 179, 180, 0, 0, 0, 0, 0, 0, 0, 181, 182, 183, 184, 0, 0, 0, 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, 192, 0, 0, 193, 194, 0, 0, 0, 0, 0, 0, 0, 0, 195, 196, 197, 198, 0, 0, 0, 0, 0, 0, 199, 200, 201, 202, 203, 204, 205, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 0, 206, 83, 73, 21, 74, 0, 0, 0, 0, 0, 0, 0, 65, 207, 66, 208, 209, 69, 210, 211, 212, 213, 75, 214, 77, 72, 79, 215, 80, 67, 84, 216, 217, 88, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 97, 228, 229, 230, 231, 101, 232, 233, 234, 235, 236, 237, 238, 239, 111, 240, 112, 99, 241, 121, 242, 120, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 0, 141, 0, 0, 253, 115, 105, 145, 106, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 254, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int decodeutf8(uchar *dstbuf, int dstlen, const uchar *srcbuf, int srclen, int *carry) { uchar *dst = dstbuf, *dstend = &dstbuf[dstlen]; const uchar *src = srcbuf, *srcend = &srcbuf[srclen]; if(dstbuf == srcbuf) { int len = min(dstlen, srclen); for(const uchar *end4 = &srcbuf[len&~3]; src < end4; src += 4) if(*(const int *)src & 0x80808080) goto decode; for(const uchar *end = &srcbuf[len]; src < end; src++) if(*src & 0x80) goto decode; if(carry) *carry += len; return len; } decode: dst += src - srcbuf; while(src < srcend && dst < dstend) { int c = *src++; if(c < 0x80) *dst++ = c; else if(c >= 0xC0) { int uni; if(c >= 0xE0) { if(c >= 0xF0) { if(c >= 0xF8) { if(c >= 0xFC) { if(c >= 0xFE) continue; uni = c&1; if(srcend - src < 5) break; c = *src; if((c&0xC0) != 0x80) continue; src++; uni = (uni<<6) | (c&0x3F); } else { uni = c&3; if(srcend - src < 4) break; } c = *src; if((c&0xC0) != 0x80) continue; src++; uni = (uni<<6) | (c&0x3F); } else { uni = c&7; if(srcend - src < 3) break; } c = *src; if((c&0xC0) != 0x80) continue; src++; uni = (uni<<6) | (c&0x3F); } else { uni = c&0xF; if(srcend - src < 2) break; } c = *src; if((c&0xC0) != 0x80) continue; src++; uni = (uni<<6) | (c&0x3F); } else { uni = c&0x1F; if(srcend - src < 1) break; } c = *src; if((c&0xC0) != 0x80) continue; src++; uni = (uni<<6) | (c&0x3F); c = uni2cube(uni); if(!c) continue; *dst++ = c; } } if(carry) *carry += src - srcbuf; return dst - dstbuf; } int encodeutf8(uchar *dstbuf, int dstlen, const uchar *srcbuf, int srclen, int *carry) { uchar *dst = dstbuf, *dstend = &dstbuf[dstlen]; const uchar *src = srcbuf, *srcend = &srcbuf[srclen]; if(src < srcend && dst < dstend) do { int uni = cube2uni(*src); if(uni <= 0x7F) { if(dst >= dstend) goto done; const uchar *end = min(srcend, &src[dstend-dst]); do { *dst++ = uni; if(++src >= end) goto done; uni = cube2uni(*src); } while(uni <= 0x7F); } if(uni <= 0x7FF) { if(dst + 2 > dstend) goto done; *dst++ = 0xC0 | (uni>>6); goto uni2; } else if(uni <= 0xFFFF) { if(dst + 3 > dstend) goto done; *dst++ = 0xE0 | (uni>>12); goto uni3; } else if(uni <= 0x1FFFFF) { if(dst + 4 > dstend) goto done; *dst++ = 0xF0 | (uni>>18); goto uni4; } else if(uni <= 0x3FFFFFF) { if(dst + 5 > dstend) goto done; *dst++ = 0xF8 | (uni>>24); goto uni5; } else if(uni <= 0x7FFFFFFF) { if(dst + 6 > dstend) goto done; *dst++ = 0xFC | (uni>>30); goto uni6; } else goto uni1; uni6: *dst++ = 0x80 | ((uni>>24)&0x3F); uni5: *dst++ = 0x80 | ((uni>>18)&0x3F); uni4: *dst++ = 0x80 | ((uni>>12)&0x3F); uni3: *dst++ = 0x80 | ((uni>>6)&0x3F); uni2: *dst++ = 0x80 | (uni&0x3F); uni1:; } while(++src < srcend); done: if(carry) *carry += src - srcbuf; return dst - dstbuf; } ///////////////////////// file system /////////////////////// #ifdef WIN32 #include #else #include #include #include #include #endif string homedir = ""; struct packagedir { char *dir, *filter; int dirlen, filterlen; }; vector packagedirs; char *makerelpath(const char *dir, const char *file, const char *prefix, const char *cmd) { static string tmp; if(prefix) copystring(tmp, prefix); else tmp[0] = '\0'; if(file[0]=='<') { const char *end = strrchr(file, '>'); if(end) { size_t len = strlen(tmp); copystring(&tmp[len], file, min(sizeof(tmp)-len, size_t(end+2-file))); file = end+1; } } if(cmd) concatstring(tmp, cmd); if(dir) { defformatstring(pname)("%s/%s", dir, file); concatstring(tmp, pname); } else concatstring(tmp, file); return tmp; } char *path(char *s) { for(char *curpart = s;;) { char *endpart = strchr(curpart, '&'); if(endpart) *endpart = '\0'; if(curpart[0]=='<') { char *file = strrchr(curpart, '>'); if(!file) return s; curpart = file+1; } for(char *t = curpart; (t = strpbrk(t, "/\\")); *t++ = PATHDIV); for(char *prevdir = NULL, *curdir = curpart;;) { prevdir = curdir[0]==PATHDIV ? curdir+1 : curdir; curdir = strchr(prevdir, PATHDIV); if(!curdir) break; if(prevdir+1==curdir && prevdir[0]=='.') { memmove(prevdir, curdir+1, strlen(curdir+1)+1); curdir = prevdir; } else if(curdir[1]=='.' && curdir[2]=='.' && curdir[3]==PATHDIV) { if(prevdir+2==curdir && prevdir[0]=='.' && prevdir[1]=='.') continue; memmove(prevdir, curdir+4, strlen(curdir+4)+1); curdir = prevdir; } } if(endpart) { *endpart = '&'; curpart = endpart+1; } else break; } return s; } char *path(const char *s, bool copy) { static string tmp; copystring(tmp, s); path(tmp); return tmp; } const char *parentdir(const char *directory) { const char *p = directory + strlen(directory); while(p > directory && *p != '/' && *p != '\\') p--; static string parent; size_t len = p-directory+1; copystring(parent, directory, len); return parent; } bool fileexists(const char *path, const char *mode) { bool exists = true; if(mode[0]=='w' || mode[0]=='a') path = parentdir(path); #ifdef WIN32 if(GetFileAttributes(path) == INVALID_FILE_ATTRIBUTES) exists = false; #else if(access(path, R_OK | (mode[0]=='w' || mode[0]=='a' ? W_OK : 0)) == -1) exists = false; #endif return exists; } bool createdir(const char *path) { size_t len = strlen(path); if(path[len-1]==PATHDIV) { static string strip; path = copystring(strip, path, len); } #ifdef WIN32 return CreateDirectory(path, NULL)!=0; #else return mkdir(path, 0777)==0; #endif } size_t fixpackagedir(char *dir) { path(dir); size_t len = strlen(dir); if(len > 0 && dir[len-1] != PATHDIV) { dir[len] = PATHDIV; dir[len+1] = '\0'; } return len; } bool subhomedir(char *dst, int len, const char *src) { const char *sub = strstr(src, "$HOME"); if(!sub) sub = strchr(src, '~'); if(sub && sub-src < len) { #ifdef WIN32 char home[MAX_PATH+1]; home[0] = '\0'; if(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, home) != S_OK || !home[0]) return false; #else const char *home = getenv("HOME"); if(!home || !home[0]) return false; #endif dst[sub-src] = '\0'; concatstring(dst, home); concatstring(dst, sub+(*sub == '~' ? 1 : strlen("$HOME"))); } return true; } const char *sethomedir(const char *dir) { string pdir; copystring(pdir, dir); if(!subhomedir(pdir, sizeof(pdir), dir) || !fixpackagedir(pdir)) return NULL; copystring(homedir, pdir); return homedir; } const char *addpackagedir(const char *dir) { string pdir; copystring(pdir, dir); if(!subhomedir(pdir, sizeof(pdir), dir) || !fixpackagedir(pdir)) return NULL; char *filter = pdir; for(;;) { static int len = strlen("packages"); filter = strstr(filter, "packages"); if(!filter) break; if(filter > pdir && filter[-1] == PATHDIV && filter[len] == PATHDIV) break; filter += len; } packagedir &pf = packagedirs.add(); pf.dir = filter ? newstring(pdir, filter-pdir) : newstring(pdir); pf.dirlen = filter ? filter-pdir : strlen(pdir); pf.filter = filter ? newstring(filter) : NULL; pf.filterlen = filter ? strlen(filter) : 0; return pf.dir; } const char *findfile(const char *filename, const char *mode) { static string s; if(homedir[0]) { formatstring(s)("%s%s", homedir, filename); if(fileexists(s, mode)) return s; if(mode[0]=='w' || mode[0]=='a') { string dirs; copystring(dirs, s); char *dir = strchr(dirs[0]==PATHDIV ? dirs+1 : dirs, PATHDIV); while(dir) { *dir = '\0'; if(!fileexists(dirs, "r") && !createdir(dirs)) return s; *dir = PATHDIV; dir = strchr(dir+1, PATHDIV); } return s; } } if(mode[0]=='w' || mode[0]=='a') return filename; loopv(packagedirs) { packagedir &pf = packagedirs[i]; if(pf.filter && strncmp(filename, pf.filter, pf.filterlen)) continue; formatstring(s)("%s%s", pf.dir, filename); if(fileexists(s, mode)) return s; } return filename; } bool listdir(const char *dirname, bool rel, const char *ext, vector &files) { int extsize = ext ? (int)strlen(ext)+1 : 0; #ifdef WIN32 defformatstring(pathname)(rel ? ".\\%s\\*.%s" : "%s\\*.%s", dirname, ext ? ext : "*"); WIN32_FIND_DATA FindFileData; HANDLE Find = FindFirstFile(pathname, &FindFileData); if(Find != INVALID_HANDLE_VALUE) { do { if(!ext) files.add(newstring(FindFileData.cFileName)); else { int namelength = (int)strlen(FindFileData.cFileName) - extsize; if(namelength > 0 && FindFileData.cFileName[namelength] == '.' && strncmp(FindFileData.cFileName+namelength+1, ext, extsize-1)==0) files.add(newstring(FindFileData.cFileName, namelength)); } } while(FindNextFile(Find, &FindFileData)); FindClose(Find); return true; } #else defformatstring(pathname)(rel ? "./%s" : "%s", dirname); DIR *d = opendir(pathname); if(d) { struct dirent *de; while((de = readdir(d)) != NULL) { if(!ext) files.add(newstring(de->d_name)); else { int namelength = (int)strlen(de->d_name) - extsize; if(namelength > 0 && de->d_name[namelength] == '.' && strncmp(de->d_name+namelength+1, ext, extsize-1)==0) files.add(newstring(de->d_name, namelength)); } } closedir(d); return true; } #endif else return false; } int listfiles(const char *dir, const char *ext, vector &files) { string dirname; copystring(dirname, dir); path(dirname); int dirlen = (int)strlen(dirname); while(dirlen > 1 && dirname[dirlen-1] == PATHDIV) dirname[--dirlen] = '\0'; int dirs = 0; if(listdir(dirname, true, ext, files)) dirs++; string s; if(homedir[0]) { formatstring(s)("%s%s", homedir, dirname); if(listdir(s, false, ext, files)) dirs++; } loopv(packagedirs) { packagedir &pf = packagedirs[i]; if(pf.filter && strncmp(dirname, pf.filter, dirlen == pf.filterlen-1 ? dirlen : pf.filterlen)) continue; formatstring(s)("%s%s", pf.dir, dirname); if(listdir(s, false, ext, files)) dirs++; } #ifndef STANDALONE dirs += listzipfiles(dirname, ext, files); #endif return dirs; } #ifndef STANDALONE static int rwopsseek(SDL_RWops *rw, int pos, int whence) { stream *f = (stream *)rw->hidden.unknown.data1; if((!pos && whence==SEEK_CUR) || f->seek(pos, whence)) return (int)f->tell(); return -1; } static int rwopsread(SDL_RWops *rw, void *buf, int size, int nmemb) { stream *f = (stream *)rw->hidden.unknown.data1; return f->read(buf, size*nmemb)/size; } static int rwopswrite(SDL_RWops *rw, const void *buf, int size, int nmemb) { stream *f = (stream *)rw->hidden.unknown.data1; return f->write(buf, size*nmemb)/size; } static int rwopsclose(SDL_RWops *rw) { return 0; } SDL_RWops *stream::rwops() { SDL_RWops *rw = SDL_AllocRW(); if(!rw) return NULL; rw->hidden.unknown.data1 = this; rw->seek = rwopsseek; rw->read = rwopsread; rw->write = rwopswrite; rw->close = rwopsclose; return rw; } #endif stream::offset stream::size() { offset pos = tell(), endpos; if(pos < 0 || !seek(0, SEEK_END)) return -1; endpos = tell(); return pos == endpos || seek(pos, SEEK_SET) ? endpos : -1; } bool stream::getline(char *str, int len) { loopi(len-1) { if(read(&str[i], 1) != 1) { str[i] = '\0'; return i > 0; } else if(str[i] == '\n') { str[i+1] = '\0'; return true; } } if(len > 0) str[len-1] = '\0'; return true; } int stream::printf(const char *fmt, ...) { char buf[512]; char *str = buf; va_list args; #if defined(WIN32) && !defined(__GNUC__) va_start(args, fmt); size_t len = _vscprintf(fmt, args); if(len >= sizeof(buf)) str = new char[len+1]; _vsnprintf(str, len+1, fmt, args); va_end(args); #else va_start(args, fmt); size_t len = vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); if(len >= sizeof(buf)) { str = new char[len+1]; va_start(args, fmt); vsnprintf(str, len+1, fmt, args); va_end(args); } #endif int n = write(str, len); if(str != buf) delete[] str; return n; } struct filestream : stream { FILE *file; filestream() : file(NULL) {} ~filestream() { close(); } bool open(const char *name, const char *mode) { if(file) return false; file = fopen(name, mode); return file!=NULL; } bool opentemp(const char *name, const char *mode) { if(file) return false; #ifdef WIN32 file = fopen(name, mode); #else file = tmpfile(); #endif return file!=NULL; } void close() { if(file) { fclose(file); file = NULL; } } bool end() { return feof(file)!=0; } offset tell() { #ifdef WIN32 #ifdef __GNUC__ return ftello64(file); #else return _ftelli64(file); #endif #else return ftello(file); #endif } bool seek(offset pos, int whence) { #ifdef WIN32 #ifdef __GNUC__ return fseeko64(file, pos, whence) >= 0; #else return _fseeki64(file, pos, whence) >= 0; #endif #else return fseeko(file, pos, whence) >= 0; #endif } int read(void *buf, int len) { return (int)fread(buf, 1, len, file); } int write(const void *buf, int len) { return (int)fwrite(buf, 1, len, file); } int getchar() { return fgetc(file); } bool putchar(int c) { return fputc(c, file)!=EOF; } bool getline(char *str, int len) { return fgets(str, len, file)!=NULL; } bool putstring(const char *str) { return fputs(str, file)!=EOF; } int printf(const char *fmt, ...) { va_list v; va_start(v, fmt); int result = vfprintf(file, fmt, v); va_end(v); return result; } }; #ifndef STANDALONE VAR(dbggz, 0, 0, 1); #endif struct gzstream : stream { enum { MAGIC1 = 0x1F, MAGIC2 = 0x8B, BUFSIZE = 16384, OS_UNIX = 0x03 }; enum { F_ASCII = 0x01, F_CRC = 0x02, F_EXTRA = 0x04, F_NAME = 0x08, F_COMMENT = 0x10, F_RESERVED = 0xE0 }; stream *file; z_stream zfile; uchar *buf; bool reading, writing, autoclose; uint crc; int headersize; gzstream() : file(NULL), buf(NULL), reading(false), writing(false), autoclose(false), crc(0), headersize(0) { zfile.zalloc = NULL; zfile.zfree = NULL; zfile.opaque = NULL; zfile.next_in = zfile.next_out = NULL; zfile.avail_in = zfile.avail_out = 0; } ~gzstream() { close(); } void writeheader() { uchar header[] = { MAGIC1, MAGIC2, Z_DEFLATED, 0, 0, 0, 0, 0, 0, OS_UNIX }; file->write(header, sizeof(header)); } void readbuf(int size = BUFSIZE) { if(!zfile.avail_in) zfile.next_in = (Bytef *)buf; size = min(size, int(&buf[BUFSIZE] - &zfile.next_in[zfile.avail_in])); int n = file->read(zfile.next_in + zfile.avail_in, size); if(n > 0) zfile.avail_in += n; } int readbyte(int size = BUFSIZE) { if(!zfile.avail_in) readbuf(size); if(!zfile.avail_in) return 0; zfile.avail_in--; return *(uchar *)zfile.next_in++; } void skipbytes(int n) { while(n > 0 && zfile.avail_in > 0) { int skipped = min(n, (int)zfile.avail_in); zfile.avail_in -= skipped; zfile.next_in += skipped; n -= skipped; } if(n <= 0) return; file->seek(n, SEEK_CUR); } bool checkheader() { readbuf(10); if(readbyte() != MAGIC1 || readbyte() != MAGIC2 || readbyte() != Z_DEFLATED) return false; int flags = readbyte(); if(flags & F_RESERVED) return false; skipbytes(6); if(flags & F_EXTRA) { int len = readbyte(512); len |= readbyte(512)<<8; skipbytes(len); } if(flags & F_NAME) while(readbyte(512)); if(flags & F_COMMENT) while(readbyte(512)); if(flags & F_CRC) skipbytes(2); headersize = int(file->tell() - zfile.avail_in); return zfile.avail_in > 0 || !file->end(); } bool open(stream *f, const char *mode, bool needclose, int level) { if(file) return false; for(; *mode; mode++) { if(*mode=='r') { reading = true; break; } else if(*mode=='w') { writing = true; break; } } if(reading) { if(inflateInit2(&zfile, -MAX_WBITS) != Z_OK) reading = false; } else if(writing && deflateInit2(&zfile, level, Z_DEFLATED, -MAX_WBITS, min(MAX_MEM_LEVEL, 8), Z_DEFAULT_STRATEGY) != Z_OK) writing = false; if(!reading && !writing) return false; autoclose = needclose; file = f; crc = crc32(0, NULL, 0); buf = new uchar[BUFSIZE]; if(reading) { if(!checkheader()) { stopreading(); return false; } } else if(writing) writeheader(); return true; } uint getcrc() { return crc; } void finishreading() { if(!reading) return; #ifndef STANDALONE if(dbggz) { uint checkcrc = 0, checksize = 0; loopi(4) checkcrc |= uint(readbyte()) << (i*8); loopi(4) checksize |= uint(readbyte()) << (i*8); if(checkcrc != crc) conoutf(CON_DEBUG, "gzip crc check failed: read %X, calculated %X", checkcrc, crc); if(checksize != zfile.total_out) conoutf(CON_DEBUG, "gzip size check failed: read %u, calculated %u", checksize, uint(zfile.total_out)); } #endif } void stopreading() { if(!reading) return; inflateEnd(&zfile); reading = false; } void finishwriting() { if(!writing) return; for(;;) { int err = zfile.avail_out > 0 ? deflate(&zfile, Z_FINISH) : Z_OK; if(err != Z_OK && err != Z_STREAM_END) break; flush(); if(err == Z_STREAM_END) break; } uchar trailer[8] = { uchar(crc&0xFF), uchar((crc>>8)&0xFF), uchar((crc>>16)&0xFF), uchar((crc>>24)&0xFF), uchar(zfile.total_in&0xFF), uchar((zfile.total_in>>8)&0xFF), uchar((zfile.total_in>>16)&0xFF), uchar((zfile.total_in>>24)&0xFF) }; file->write(trailer, sizeof(trailer)); } void stopwriting() { if(!writing) return; deflateEnd(&zfile); writing = false; } void close() { if(reading) finishreading(); stopreading(); if(writing) finishwriting(); stopwriting(); DELETEA(buf); if(autoclose) DELETEP(file); } bool end() { return !reading && !writing; } offset tell() { return reading ? zfile.total_out : (writing ? zfile.total_in : -1); } offset rawtell() { return file ? file->tell() : -1; } offset size() { if(!file) return -1; offset pos = tell(); if(!file->seek(-4, SEEK_END)) return -1; uint isize = file->getlil(); return file->seek(pos, SEEK_SET) ? isize : -1; } offset rawsize() { return file ? file->size() : -1; } bool seek(offset pos, int whence) { if(writing || !reading) return false; if(whence == SEEK_END) { uchar skip[512]; while(read(skip, sizeof(skip)) == sizeof(skip)); return !pos; } else if(whence == SEEK_CUR) pos += zfile.total_out; if(pos >= (offset)zfile.total_out) pos -= zfile.total_out; else if(pos < 0 || !file->seek(headersize, SEEK_SET)) return false; else { if(zfile.next_in && zfile.total_in <= uint(zfile.next_in - buf)) { zfile.avail_in += zfile.total_in; zfile.next_in -= zfile.total_in; } else { zfile.avail_in = 0; zfile.next_in = NULL; } inflateReset(&zfile); crc = crc32(0, NULL, 0); } uchar skip[512]; while(pos > 0) { int skipped = (int)min(pos, (offset)sizeof(skip)); if(read(skip, skipped) != skipped) { stopreading(); return false; } pos -= skipped; } return true; } int read(void *buf, int len) { if(!reading || !buf || !len) return 0; zfile.next_out = (Bytef *)buf; zfile.avail_out = len; while(zfile.avail_out > 0) { if(!zfile.avail_in) { readbuf(BUFSIZE); if(!zfile.avail_in) { stopreading(); break; } } int err = inflate(&zfile, Z_NO_FLUSH); if(err == Z_STREAM_END) { crc = crc32(crc, (Bytef *)buf, len - zfile.avail_out); finishreading(); stopreading(); return len - zfile.avail_out; } else if(err != Z_OK) { stopreading(); break; } } crc = crc32(crc, (Bytef *)buf, len - zfile.avail_out); return len - zfile.avail_out; } bool flush() { if(zfile.next_out && zfile.avail_out < BUFSIZE) { if(file->write(buf, BUFSIZE - zfile.avail_out) != int(BUFSIZE - zfile.avail_out)) return false; } zfile.next_out = buf; zfile.avail_out = BUFSIZE; return true; } int write(const void *buf, int len) { if(!writing || !buf || !len) return 0; zfile.next_in = (Bytef *)buf; zfile.avail_in = len; while(zfile.avail_in > 0) { if(!zfile.avail_out && !flush()) { stopwriting(); break; } int err = deflate(&zfile, Z_NO_FLUSH); if(err != Z_OK) { stopwriting(); break; } } crc = crc32(crc, (Bytef *)buf, len - zfile.avail_in); return len - zfile.avail_in; } }; struct utf8stream : stream { enum { BUFSIZE = 4096 }; stream *file; offset pos; int bufread, bufcarry, buflen; bool reading, writing, autoclose; uchar buf[BUFSIZE]; utf8stream() : file(NULL), pos(0), bufread(0), bufcarry(0), buflen(0), reading(false), writing(false), autoclose(false) { } ~utf8stream() { close(); } bool readbuf(int size = BUFSIZE) { if(bufread >= bufcarry) { if(bufcarry > 0 && bufcarry < buflen) memmove(buf, &buf[bufcarry], buflen - bufcarry); buflen -= bufcarry; bufread = bufcarry = 0; } int n = file->read(&buf[buflen], min(size, BUFSIZE - buflen)); if(n <= 0) return false; buflen += n; int carry = bufcarry; bufcarry += decodeutf8(&buf[bufcarry], BUFSIZE-bufcarry, &buf[bufcarry], buflen-bufcarry, &carry); if(carry > bufcarry && carry < buflen) { memmove(&buf[bufcarry], &buf[carry], buflen - carry); buflen -= carry - bufcarry; } return true; } bool checkheader() { int n = file->read(buf, 3); if(n == 3 && buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF) return true; buflen = n; return false; } bool open(stream *f, const char *mode, bool needclose) { if(file) return false; for(; *mode; mode++) { if(*mode=='r') { reading = true; break; } else if(*mode=='w') { writing = true; break; } } if(!reading && !writing) return false; autoclose = needclose; file = f; if(reading) checkheader(); return true; } void finishreading() { if(!reading) return; } void stopreading() { if(!reading) return; reading = false; } void stopwriting() { if(!writing) return; writing = false; } void close() { stopreading(); stopwriting(); if(autoclose) DELETEP(file); } bool end() { return !reading && !writing; } offset tell() { return reading || writing ? pos : -1; } bool seek(offset off, int whence) { if(writing || !reading) return false; if(whence == SEEK_END) { uchar skip[512]; while(read(skip, sizeof(skip)) == sizeof(skip)); return !off; } else if(whence == SEEK_CUR) off += pos; if(off >= pos) off -= pos; else if(off < 0 || !file->seek(0, SEEK_SET)) return false; else { bufread = bufcarry = buflen = 0; pos = 0; checkheader(); } uchar skip[512]; while(off > 0) { int skipped = (int)min(off, (offset)sizeof(skip)); if(read(skip, skipped) != skipped) { stopreading(); return false; } off -= skipped; } return true; } int read(void *dst, int len) { if(!reading || !dst || !len) return 0; int next = 0; while(next < len) { if(bufread >= bufcarry) { if(readbuf(BUFSIZE)) continue; stopreading(); break; } int n = min(len - next, bufcarry - bufread); memcpy(&((uchar *)dst)[next], &buf[bufread], n); next += n; bufread += n; } pos += next; return next; } bool getline(char *dst, int len) { if(!reading || !dst || !len) return false; --len; int next = 0; while(next < len) { if(bufread >= bufcarry) { if(readbuf(BUFSIZE)) continue; stopreading(); if(!next) return false; break; } int n = min(len - next, bufcarry - bufread); uchar *endline = (uchar *)memchr(&buf[bufread], '\n', n); if(endline) { n = endline+1 - &buf[bufread]; len = next + n; } memcpy(&((uchar *)dst)[next], &buf[bufread], n); next += n; bufread += n; } dst[next] = '\0'; pos += next; return true; } int write(const void *src, int len) { if(!writing || !src || !len) return 0; uchar dst[512]; int next = 0; while(next < len) { int carry = 0, n = encodeutf8(dst, sizeof(dst), &((uchar *)src)[next], len - next, &carry); if(n > 0 && file->write(dst, n) != n) { stopwriting(); break; } next += carry; } pos += next; return next; } }; stream *openrawfile(const char *filename, const char *mode) { const char *found = findfile(filename, mode); if(!found) return NULL; filestream *file = new filestream; if(!file->open(found, mode)) { delete file; return NULL; } return file; } stream *openfile(const char *filename, const char *mode) { #ifndef STANDALONE stream *s = openzipfile(filename, mode); if(s) return s; #endif return openrawfile(filename, mode); } stream *opentempfile(const char *name, const char *mode) { const char *found = findfile(name, mode); filestream *file = new filestream; if(!file->opentemp(found ? found : name, mode)) { delete file; return NULL; } return file; } stream *opengzfile(const char *filename, const char *mode, stream *file, int level) { stream *source = file ? file : openfile(filename, mode); if(!source) return NULL; gzstream *gz = new gzstream; if(!gz->open(source, mode, !file, level)) { if(!file) delete source; return NULL; } return gz; } stream *openutf8file(const char *filename, const char *mode, stream *file) { stream *source = file ? file : openfile(filename, mode); if(!source) return NULL; utf8stream *utf8 = new utf8stream; if(!utf8->open(source, mode, !file)) { if(!file) delete source; return NULL; } return utf8; } char *loadfile(const char *fn, int *size, bool utf8) { stream *f = openfile(fn, "rb"); if(!f) return NULL; int len = (int)f->size(); if(len <= 0) { delete f; return NULL; } char *buf = new char[len+1]; if(!buf) { delete f; return NULL; } int offset = 0; if(utf8 && len >= 3) { if(f->read(buf, 3) != 3) { delete f; delete[] buf; return NULL; } if(((uchar *)buf)[0] == 0xEF && ((uchar *)buf)[1] == 0xBB && ((uchar *)buf)[2] == 0xBF) len -= 3; else offset += 3; } int rlen = f->read(&buf[offset], len-offset); delete f; if(rlen != len-offset) { delete[] buf; return NULL; } if(utf8) len = decodeutf8((uchar *)buf, len, (uchar *)buf, len); buf[len] = '\0'; if(size!=NULL) *size = len; return buf; } sauerbraten-0.0.20130203.dfsg/shared/igame.h0000644000175000017500000001166012067542067020113 0ustar vincentvincent// the interface the engine uses to run the gameplay module namespace entities { extern void editent(int i, bool local); extern const char *entnameinfo(entity &e); extern const char *entname(int i); extern int extraentinfosize(); extern void writeent(entity &e, char *buf); extern void readent(entity &e, char *buf, int ver); extern float dropheight(entity &e); extern void fixentity(extentity &e); extern void entradius(extentity &e, bool color); extern bool mayattach(extentity &e); extern bool attachent(extentity &e, extentity &a); extern bool printent(extentity &e, char *buf); extern extentity *newentity(); extern void deleteentity(extentity *e); extern void clearents(); extern vector &getents(); extern const char *entmodel(const entity &e); extern void animatemapmodel(const extentity &e, int &anim, int &basetime); } namespace game { extern void parseoptions(vector &args); extern void gamedisconnect(bool cleanup); extern void parsepacketclient(int chan, packetbuf &p); extern void connectattempt(const char *name, const char *password, const ENetAddress &address); extern void connectfail(); extern void gameconnect(bool _remote); extern bool allowedittoggle(); extern void edittoggled(bool on); extern void writeclientinfo(stream *f); extern void toserver(char *text); extern void changemap(const char *name); extern void forceedit(const char *name); extern bool ispaused(); extern int scaletime(int t); extern bool allowmouselook(); extern const char *gameident(); extern const char *savedconfig(); extern const char *restoreconfig(); extern const char *defaultconfig(); extern const char *autoexec(); extern const char *savedservers(); extern void loadconfigs(); extern void updateworld(); extern void initclient(); extern void physicstrigger(physent *d, bool local, int floorlevel, int waterlevel, int material = 0); extern void bounced(physent *d, const vec &surface); extern void edittrigger(const selinfo &sel, int op, int arg1 = 0, int arg2 = 0, int arg3 = 0); extern void vartrigger(ident *id); extern void dynentcollide(physent *d, physent *o, const vec &dir); extern const char *getclientmap(); extern const char *getmapinfo(); extern void resetgamestate(); extern void suicide(physent *d); extern void newmap(int size); extern void startmap(const char *name); extern void preload(); extern float abovegameplayhud(int w, int h); extern void gameplayhud(int w, int h); extern bool canjump(); extern bool allowmove(physent *d); extern void doattack(bool on); extern dynent *iterdynents(int i); extern int numdynents(); extern void rendergame(bool mainpass); extern void renderavatar(); extern void renderplayerpreview(int model, int team, int weap); extern void writegamedata(vector &extras); extern void readgamedata(vector &extras); extern int clipconsole(int w, int h); extern void g3d_gamemenus(); extern const char *defaultcrosshair(int index); extern int selectcrosshair(float &r, float &g, float &b); extern void lighteffects(dynent *d, vec &color, vec &dir); extern void setupcamera(); extern bool detachcamera(); extern bool collidecamera(); extern void adddynlights(); extern void particletrack(physent *owner, vec &o, vec &d); extern void dynlighttrack(physent *owner, vec &o, vec &hud); extern bool serverinfostartcolumn(g3d_gui *g, int i); extern void serverinfoendcolumn(g3d_gui *g, int i); extern bool serverinfoentry(g3d_gui *g, int i, const char *name, int port, const char *desc, const char *map, int ping, const vector &attr, int np); extern bool needminimap(); } namespace server { extern void *newclientinfo(); extern void deleteclientinfo(void *ci); extern void serverinit(); extern int reserveclients(); extern int numchannels(); extern void clientdisconnect(int n); extern int clientconnect(int n, uint ip); extern void localdisconnect(int n); extern void localconnect(int n); extern bool allowbroadcast(int n); extern void recordpacket(int chan, void *data, int len); extern void parsepacket(int sender, int chan, packetbuf &p); extern void sendservmsg(const char *s); extern bool sendpackets(bool force = false); extern void serverinforeply(ucharbuf &req, ucharbuf &p); extern void serverupdate(); extern bool servercompatible(char *name, char *sdec, char *map, int ping, const vector &attr, int np); extern int laninfoport(); extern int serverinfoport(int servport = -1); extern int serverport(int infoport = -1); extern const char *defaultmaster(); extern int masterport(); extern void processmasterinput(const char *cmd, int cmdlen, const char *args); extern bool ispaused(); extern int scaletime(int t); } sauerbraten-0.0.20130203.dfsg/rpggame/0000755000175000017500000000000012100771027017014 5ustar vincentvincentsauerbraten-0.0.20130203.dfsg/rpggame/entities.cpp0000644000175000017500000000471411525201056021352 0ustar vincentvincent#include "rpg.h" namespace entities { using namespace game; vector ents; vector &getents() { return ents; } bool mayattach(extentity &e) { return false; } bool attachent(extentity &e, extentity &a) { return false; } const char *entnameinfo(entity &e) { return ""; } const char *entname(int i) { static const char *entnames[] = { "none?", "light", "mapmodel", "playerstart", "envmap", "particles", "sound", "spotlight", "spawn" }; return i>=0 && size_t(i)yaw; break; } } void entradius(extentity &e, bool color) { switch(e.type) { case ETR_SPAWN: { vec dir; vecfromyawpitch(e.attr1, 0, 1, 0, dir); renderentarrow(e, dir, 4); break; } } } bool printent(extentity &e, char *buf) { return false; } void startmap() { lastcreated = NULL; loopv(ents) if(ents[i]->type==ETR_SPAWN) spawnfroment(*(rpgentity *)ents[i]); } ICOMMAND(spawnname, "s", (char *s), { if(lastcreated) { copystring(lastcreated->name, s, SPAWNNAMELEN); spawnfroment(*lastcreated); } }); void animatemapmodel(const extentity &e, int &anim, int &basetime) { } const char *entmodel(const entity &e) { return NULL; } } sauerbraten-0.0.20130203.dfsg/rpggame/rpgobj.h0000644000175000017500000002752211370371071020463 0ustar vincentvincentstruct rpgobj; struct rpgaction { rpgaction *next; char *initiate, *script; rpgquest *q; bool used; rpgaction(char *_i = NULL, char *_s = NULL, rpgaction *_n = NULL) : next(_n), initiate(_i), script(_s), q(NULL), used(false) {} ~rpgaction() { DELETEP(next); } void exec(rpgobj *obj, rpgobj *target, rpgobj *user) { if(!*script) return; pushobj(user); pushobj(target); pushobj(obj); execute(script); used = true; } }; struct rpgobj : g3d_callback, stats { rpgobj *parent; // container object, if not top level rpgobj *inventory; // contained objects, if any rpgobj *sibling; // used for linking, if contained rpgent *ent; // representation in the world, if top level const char *name; // name it was spawned as const char *model; // what to display it as enum { IF_INVENTORY = 1, // parent owns this object, will contribute to parent stats IF_LOOT = 2, // if parent dies, this object should drop to the ground IF_TRADE = 4, // parent has this item available for trade, for player, all currently unused weapons etc are of this type }; enum { MENU_DEFAULT, MENU_BUY, MENU_SELL }; int itemflags; rpgaction *actions, action_use; char *abovetext; int menutime, menutab, menuwhich; #define loopinventory() for(rpgobj *o = inventory; o; o = o->sibling) #define loopinventorytype(T) loopinventory() if(o->itemflags&(T)) rpgobj(const char *_name) : parent(NULL), inventory(NULL), sibling(NULL), ent(NULL), name(_name), model(NULL), itemflags(IF_INVENTORY), actions(NULL), abovetext(NULL), menutime(0), menutab(1), menuwhich(MENU_DEFAULT) {} ~rpgobj() { DELETEP(inventory); DELETEP(sibling); DELETEP(ent); DELETEP(actions); } void scriptinit() { DELETEP(inventory); defformatstring(aliasname)("spawn_%s", name); if(identexists(aliasname)) execute(aliasname); } void decontain() { if(parent) parent->remove(this); } void add(rpgobj *o, int itemflags) { o->sibling = inventory; o->parent = this; inventory = o; o->itemflags = itemflags; if(itemflags&IF_INVENTORY) recalcstats(); } void remove(rpgobj *o) { for(rpgobj **l = &inventory; *l; ) if(*l==o) { *l = o->sibling; o->sibling = o->parent = NULL; } else l = &(*l)->sibling; if(o->itemflags&IF_INVENTORY) recalcstats(); } void recalcstats() { st_reset(); loopinventorytype(IF_INVENTORY) st_accumulate(*o); } rpgobj &selectedweapon() { if(this==playerobj) return selected ? *selected : *this; else { loopinventorytype(IF_INVENTORY) if(o->s_usetype) return *o; }; return *this; } void placedinworld(rpgent *_ent) { if(!model) model = "tentus/moneybag"; ent = _ent; setbbfrommodel(ent, model); entinmap(ent); //ASSERT(!(ent->o.x<0 || ent->o.y<0 || ent->o.z<0 || ent->o.x>4096 || ent->o.y>4096 || ent->o.z>4096)); st_init(); } void render() { if(s_ai) { float sink = 0; if(ent->physstate>=PHYS_SLIDE) sink = raycube(ent->o, vec(0, 0, -1), 2*ent->eyeheight)-ent->eyeheight; ent->sink = ent->sink*0.8 + sink*0.2; //if(ent->blocked) particle_splash(PART_SPARK, 100, 100, ent->o, 0xB49B4B, 0.24f); float oldheight = ent->eyeheight; ent->eyeheight += ent->sink; renderclient(ent, model, NULL, 0, ANIM_ATTACK1, 300, ent->lastaction, 0); ent->eyeheight = oldheight; if(s_hpstate==CS_ALIVE) particle_meter(ent->abovehead(), s_hp/(float)eff_maxhp(), PART_METER, 1, 0xFF1932, 0xFFFFFF, 2.0f); } else { rendermodel(NULL, model, ANIM_MAPMODEL|ANIM_LOOP, vec(ent->o).sub(vec(0, 0, ent->eyeheight)), ent->yaw+90, 0, MDL_CULL_VFC | MDL_CULL_DIST | MDL_CULL_OCCLUDED | MDL_LIGHT, ent); } } void update() { float dist = ent->o.dist(player1->o); if(s_ai) { ent->update(dist); st_update(); }; moveplayer(ent, 1, true); // 10 or above gets blocked less, because physics accuracy doesn't need extra tests //ASSERT(!(ent->o.x<0 || ent->o.y<0 || ent->o.z<0 || ent->o.x>4096 || ent->o.y>4096 || ent->o.z>4096)); if(!menutime && dist<(s_ai ? 40 : 24) && ent->state==CS_ALIVE && s_ai<2) { menutime = starttime(); menuwhich = MENU_DEFAULT; } else if(dist>(s_ai ? 96 : 48)) menutime = 0; } void addaction(char *initiate, char *script, bool startquest) { for(rpgaction *a = actions; a; a = a->next) if(strcmp(a->initiate, initiate)==0) return; actions = new rpgaction(initiate, script, actions); if(startquest) actions->q = addquest(abovetext, name); } void droploot() { loopinventorytype(IF_LOOT) { o->decontain(); pushobj(o); placeinworld(ent->o, rnd(360)); droploot(); return; } } rpgobj *take(char *name) { loopinventory() if(strcmp(o->name, name)==0) { o->decontain(); return o; } return NULL; } void takedamage(int damage, rpgobj &attacker) { ent->enemy = attacker.ent; particle_splash(PART_BLOOD, max(damage/10, 1), 1000, ent->o, 0x60FFFF, 2.96f); defformatstring(ds)("%d", damage); particle_textcopy(ent->abovehead(), ds, PART_TEXT, 2000, 0xFF4B19, 4.0f, -8); if((s_hp -= damage)<=0) { s_hp = 0; ent->state = CS_DEAD; ent->attacking = false; ent->lastaction = lastmillis; menutime = 0; conoutf("%s killed: %s", attacker.name, name); droploot(); } } void usesound(rpgent *user) { if(s_usesound) playsound(s_usesound, &user->o); } bool usemana(rpgobj &o) { if(o.s_manacost>s_mana) { if(this==playerobj) conoutf("\f2not enough mana"); return false; }; s_mana -= o.s_manacost; o.usesound(ent); return true; } void useaction(rpgobj &target, rpgent &initiator, bool chargemana) { if(action_use.script && (!chargemana || initiator.ro->usemana(*this))) { action_use.exec(this, &target, initiator.ro); if(s_useamount && !--s_useamount) removefromsystem(this); } } void selectuse() { if(s_usetype) { conoutf("\f2using: %s", name); selected = this; } else { useaction(*playerobj, *playerobj->ent, true); } } void guiaction(g3d_gui &g, rpgaction *a) { if(!a) return; guiaction(g, a->next); if(g.button(a->initiate, a->used ? 0xAAAAAA : 0xFFFFFF, "chat")&G3D_UP) { currentquest = a->q; a->exec(this, playerobj, playerobj); currentquest = NULL; } } void gui(g3d_gui &g, bool firstpass) { g.start(menutime, 0.015f, &menutab); switch(menuwhich) { case MENU_DEFAULT: { g.tab(name, 0xFFFFFF); if(abovetext) g.text(abovetext, 0xDDFFDD); guiaction(g, actions); if(s_ai) { bool trader = false; loopinventorytype(IF_TRADE) trader = true; if(trader) { if(g.button("buy", 0xFFFFFF, "coins")&G3D_UP) menuwhich = MENU_BUY; if(g.button("sell", 0xFFFFFF, "coins")&G3D_UP) menuwhich = MENU_SELL; } } else { defformatstring(wtext)("worth %d", s_worth); g.text(wtext, 0xAAAAAA, "coins"); if(g.button("take", 0xFFFFFF, "hand")&G3D_UP) { conoutf("\f2you take a %s (worth %d gold)", name, s_worth); taken(this, playerobj); } if(!s_usetype && g.button("use", 0xFFFFFF, "hand")&G3D_UP) { selectuse(); } } break; } case MENU_BUY: { defformatstring(info)("buying from: %s", name); g.tab(info, 0xFFFFFF); loopinventorytype(IF_TRADE) { int price = o->s_worth; defformatstring(info)("%s (%d)", o->name, price); int ret = g.button(info, 0xFFFFFF, "coins"); if(ret&G3D_UP) { if(playerobj->s_gold>=price) { conoutf("\f2you bought %s for %d gold", o->name, price); playerobj->s_gold -= price; s_gold += price; o->decontain(); playerobj->add(o, IF_INVENTORY); } else { conoutf("\f2you cannot afford this item!"); } } } formatstring(info)("you have %d gold", playerobj->s_gold); g.text(info, 0xAAAAAA, "info"); if(g.button("done buying", 0xFFFFFF, "coins")&G3D_UP) menuwhich = MENU_DEFAULT; break; } case MENU_SELL: { defformatstring(info)("selling to: %s", name); g.tab(info, 0xFFFFFF); playerobj->invgui(g, this); if(g.button("done selling", 0xFFFFFF, "coins")&G3D_UP) menuwhich = MENU_DEFAULT; break; } } g.end(); } void invgui(g3d_gui &g, rpgobj *buyer = NULL) { loopinventory() { int price = o->s_worth/2; defformatstring(info)("%s (%d)", o->name, price); int ret = g.button(info, 0xFFFFFF, "coins"); if(ret&G3D_UP) { if(buyer) { if(price>buyer->s_gold) { conoutf("\f2%s cannot afford to buy %s from you!", buyer->name, o->name); } else { if(price) { conoutf("\f2you sold %s for %d gold", o->name, price); s_gold += price; buyer->s_gold -= price; o->decontain(); buyer->add(o, IF_TRADE); } else { conoutf("\f2you cannot sell %s", o->name); } } } else // player wants to use this item { o->selectuse(); } } } defformatstring(info)("you have %d gold", playerobj->s_gold); g.text(info, 0xAAAAAA, "info"); } void g3d_menu() { if(!menutime) return; g3d_addgui(this, vec(ent->o).add(vec(0, 0, 2))); } }; sauerbraten-0.0.20130203.dfsg/rpggame/Makefile0000644000175000017500000005171012071447250020465 0ustar vincentvincentCXXFLAGS= -Os override CXXFLAGS+= -Wall -fsigned-char -fno-exceptions -fno-rtti PLATFORM= $(shell uname -s) PLATFORM_PREFIX= native INCLUDES= -I../shared -I../engine -I../rpggame -I../enet/include STRIP= ifeq (,$(findstring -g,$(CXXFLAGS))) ifeq (,$(findstring -pg,$(CXXFLAGS))) STRIP=strip endif endif MV=mv ifneq (,$(findstring MINGW,$(PLATFORM))) WINDRES= windres ifneq (,$(findstring 64,$(PLATFORM))) WINLIB=lib64 WINBIN=../bin64 override CXX+= -m64 override WINDRES+= -F pe-x86-64 else WINLIB=lib WINBIN=../bin override CXX+= -m32 override WINDRES+= -F pe-i386 endif CLIENT_INCLUDES= $(INCLUDES) -I../include ifneq (,$(findstring TDM,$(PLATFORM))) STD_LIBS= else STD_LIBS= -static-libgcc -static-libstdc++ endif CLIENT_LIBS= -mwindows $(STD_LIBS) -L../$(WINBIN) -L../$(WINLIB) -lSDL -lSDL_image -lSDL_mixer -lzlib1 -lopengl32 -lenet -lws2_32 -lwinmm else CLIENT_INCLUDES= $(INCLUDES) -I/usr/X11R6/include `sdl-config --cflags` CLIENT_LIBS= -L../enet/.libs -lenet -L/usr/X11R6/lib -lX11 `sdl-config --libs` -lSDL_image -lSDL_mixer -lz -lGL endif ifeq ($(PLATFORM),Linux) CLIENT_LIBS+= -lrt endif CLIENT_OBJS= \ ../shared/crypto.o \ ../shared/geom.o \ ../shared/stream.o \ ../shared/tools.o \ ../shared/zip.o \ ../engine/3dgui.o \ ../engine/bih.o \ ../engine/blend.o \ ../engine/blob.o \ ../engine/client.o \ ../engine/command.o \ ../engine/console.o \ ../engine/cubeloader.o \ ../engine/decal.o \ ../engine/dynlight.o \ ../engine/glare.o \ ../engine/grass.o \ ../engine/lightmap.o \ ../engine/main.o \ ../engine/material.o \ ../engine/menus.o \ ../engine/movie.o \ ../engine/normal.o \ ../engine/octa.o \ ../engine/octaedit.o \ ../engine/octarender.o \ ../engine/physics.o \ ../engine/pvs.o \ ../engine/rendergl.o \ ../engine/rendermodel.o \ ../engine/renderparticles.o \ ../engine/rendersky.o \ ../engine/rendertext.o \ ../engine/renderva.o \ ../engine/server.o \ ../engine/serverbrowser.o \ ../engine/shader.o \ ../engine/shadowmap.o \ ../engine/sound.o \ ../engine/texture.o \ ../engine/water.o \ ../engine/world.o \ ../engine/worldio.o \ ../rpggame/ent.o \ ../rpggame/entities.o \ ../rpggame/objset.o \ ../rpggame/rpg.o CLIENT_PCH= ../shared/cube.h.gch ../engine.h.gch ../rpggame/rpg.h.gch ifeq ($(PLATFORM),SunOS) CLIENT_LIBS+= -lsocket -lnsl -lX11 endif default: all all: client ../enet/Makefile: cd ../enet; ./configure --enable-shared=no --enable-static=yes libenet: ../enet/Makefile $(MAKE) -C ../enet/ all clean-enet: enet/Makefile $(MAKE) -C ../enet/ clean clean: -$(RM) $(CLIENT_PCH) $(CLIENT_OBJS) rpg_client %.h.gch: %.h $(CXX) $(CXXFLAGS) -o $@.tmp $(subst .h.gch,.h,$@) $(MV) $@.tmp $@ $(CLIENT_OBJS): CXXFLAGS += $(CLIENT_INCLUDES) $(filter ../shared/%,$(CLIENT_OBJS)): $(filter ../shared/%,$(CLIENT_PCH)) $(filter ../engine/%,$(CLIENT_OBJS)): $(filter ../engine/%,$(CLIENT_PCH)) $(filter ../rpggame/%,$(CLIENT_OBJS)): $(filter ../rpggame/%,$(CLIENT_PCH)) ifneq (,$(findstring MINGW,$(PLATFORM))) client: $(CLIENT_OBJS) $(WINDRES) -I ../vcpp -i ../vcpp/mingw.rc -J rc -o ../vcpp/mingw.res -O coff $(CXX) $(CXXFLAGS) -o ../$(WINBIN)/rpg.exe ../vcpp/mingw.res $(CLIENT_OBJS) $(CLIENT_LIBS) ifneq (,$(STRIP)) $(STRIP) ../../bin/rpg.exe endif else client: libenet $(CLIENT_OBJS) $(CXX) $(CXXFLAGS) -o rpg_client $(CLIENT_OBJS) $(CLIENT_LIBS) endif depend: makedepend -Y -I../shared -I../engine -I../rpggame $(subst .o,.cpp,$(CLIENT_OBJS)) makedepend -a -o.h.gch -Y -I../shared -I../engine -I../rpggame $(subst .h.gch,.h,$(CLIENT_PCH)) # DO NOT DELETE ../shared/crypto.o: ../shared/cube.h ../shared/tools.h ../shared/geom.h ../shared/crypto.o: ../shared/ents.h ../shared/command.h ../shared/iengine.h ../shared/crypto.o: ../shared/igame.h ../shared/geom.o: ../shared/cube.h ../shared/tools.h ../shared/geom.h ../shared/geom.o: ../shared/ents.h ../shared/command.h ../shared/iengine.h ../shared/geom.o: ../shared/igame.h ../shared/stream.o: ../shared/cube.h ../shared/tools.h ../shared/geom.h ../shared/stream.o: ../shared/ents.h ../shared/command.h ../shared/iengine.h ../shared/stream.o: ../shared/igame.h ../shared/tools.o: ../shared/cube.h ../shared/tools.h ../shared/geom.h ../shared/tools.o: ../shared/ents.h ../shared/command.h ../shared/iengine.h ../shared/tools.o: ../shared/igame.h ../shared/zip.o: ../shared/cube.h ../shared/tools.h ../shared/geom.h ../shared/zip.o: ../shared/ents.h ../shared/command.h ../shared/iengine.h ../shared/zip.o: ../shared/igame.h ../engine/3dgui.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/3dgui.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/3dgui.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/3dgui.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/3dgui.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/3dgui.o: ../engine/textedit.h ../engine/bih.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/bih.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/bih.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/bih.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/bih.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/blend.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/blend.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/blend.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/blend.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/blend.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/blob.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/blob.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/blob.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/blob.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/blob.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/client.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/client.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/client.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/client.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/client.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/command.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/command.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/command.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/command.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/command.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/console.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/console.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/console.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/console.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/console.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/cubeloader.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/cubeloader.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/cubeloader.o: ../shared/iengine.h ../shared/igame.h ../engine/cubeloader.o: ../engine/world.h ../engine/octa.h ../engine/cubeloader.o: ../engine/lightmap.h ../engine/bih.h ../engine/cubeloader.o: ../engine/texture.h ../engine/model.h ../engine/cubeloader.o: ../engine/varray.h ../engine/decal.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/decal.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/decal.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/decal.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/decal.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/dynlight.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/dynlight.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/dynlight.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/dynlight.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/dynlight.o: ../engine/texture.h ../engine/model.h ../engine/dynlight.o: ../engine/varray.h ../engine/glare.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/glare.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/glare.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/glare.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/glare.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/glare.o: ../engine/rendertarget.h ../engine/grass.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/grass.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/grass.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/grass.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/grass.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/lightmap.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/lightmap.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/lightmap.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/lightmap.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/lightmap.o: ../engine/texture.h ../engine/model.h ../engine/lightmap.o: ../engine/varray.h ../engine/main.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/main.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/main.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/main.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/main.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/material.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/material.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/material.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/material.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/material.o: ../engine/texture.h ../engine/model.h ../engine/material.o: ../engine/varray.h ../engine/menus.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/menus.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/menus.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/menus.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/menus.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/movie.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/movie.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/movie.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/movie.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/movie.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/normal.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/normal.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/normal.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/normal.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/normal.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/octa.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/octa.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/octa.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/octa.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/octa.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/octaedit.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/octaedit.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/octaedit.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/octaedit.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/octaedit.o: ../engine/texture.h ../engine/model.h ../engine/octaedit.o: ../engine/varray.h ../engine/octarender.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/octarender.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/octarender.o: ../shared/iengine.h ../shared/igame.h ../engine/octarender.o: ../engine/world.h ../engine/octa.h ../engine/octarender.o: ../engine/lightmap.h ../engine/bih.h ../engine/octarender.o: ../engine/texture.h ../engine/model.h ../engine/octarender.o: ../engine/varray.h ../engine/physics.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/physics.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/physics.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/physics.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/physics.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/physics.o: ../engine/mpr.h ../engine/pvs.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/pvs.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/pvs.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/pvs.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/pvs.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/rendergl.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/rendergl.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/rendergl.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/rendergl.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/rendergl.o: ../engine/texture.h ../engine/model.h ../engine/rendergl.o: ../engine/varray.h ../engine/rendermodel.o: ../engine/engine.h ../shared/cube.h ../engine/rendermodel.o: ../shared/tools.h ../shared/geom.h ../shared/ents.h ../engine/rendermodel.o: ../shared/command.h ../shared/iengine.h ../engine/rendermodel.o: ../shared/igame.h ../engine/world.h ../engine/octa.h ../engine/rendermodel.o: ../engine/lightmap.h ../engine/bih.h ../engine/rendermodel.o: ../engine/texture.h ../engine/model.h ../engine/rendermodel.o: ../engine/varray.h ../engine/ragdoll.h ../engine/rendermodel.o: ../engine/animmodel.h ../engine/vertmodel.h ../engine/rendermodel.o: ../engine/skelmodel.h ../engine/md2.h ../engine/rendermodel.o: ../engine/md3.h ../engine/md5.h ../engine/obj.h ../engine/rendermodel.o: ../engine/smd.h ../engine/iqm.h ../engine/renderparticles.o: ../engine/engine.h ../shared/cube.h ../engine/renderparticles.o: ../shared/tools.h ../shared/geom.h ../engine/renderparticles.o: ../shared/ents.h ../shared/command.h ../engine/renderparticles.o: ../shared/iengine.h ../shared/igame.h ../engine/renderparticles.o: ../engine/world.h ../engine/octa.h ../engine/renderparticles.o: ../engine/lightmap.h ../engine/bih.h ../engine/renderparticles.o: ../engine/texture.h ../engine/model.h ../engine/renderparticles.o: ../engine/varray.h ../engine/rendertarget.h ../engine/renderparticles.o: ../engine/depthfx.h ../engine/explosion.h ../engine/renderparticles.o: ../engine/lensflare.h ../engine/lightning.h ../engine/rendersky.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/rendersky.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/rendersky.o: ../shared/iengine.h ../shared/igame.h ../engine/rendersky.o: ../engine/world.h ../engine/octa.h ../engine/rendersky.o: ../engine/lightmap.h ../engine/bih.h ../engine/rendersky.o: ../engine/texture.h ../engine/model.h ../engine/rendersky.o: ../engine/varray.h ../engine/rendertext.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/rendertext.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/rendertext.o: ../shared/iengine.h ../shared/igame.h ../engine/rendertext.o: ../engine/world.h ../engine/octa.h ../engine/rendertext.o: ../engine/lightmap.h ../engine/bih.h ../engine/rendertext.o: ../engine/texture.h ../engine/model.h ../engine/rendertext.o: ../engine/varray.h ../engine/renderva.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/renderva.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/renderva.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/renderva.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/renderva.o: ../engine/texture.h ../engine/model.h ../engine/renderva.o: ../engine/varray.h ../engine/server.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/server.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/server.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/server.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/server.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/serverbrowser.o: ../engine/engine.h ../shared/cube.h ../engine/serverbrowser.o: ../shared/tools.h ../shared/geom.h ../engine/serverbrowser.o: ../shared/ents.h ../shared/command.h ../engine/serverbrowser.o: ../shared/iengine.h ../shared/igame.h ../engine/serverbrowser.o: ../engine/world.h ../engine/octa.h ../engine/serverbrowser.o: ../engine/lightmap.h ../engine/bih.h ../engine/serverbrowser.o: ../engine/texture.h ../engine/model.h ../engine/serverbrowser.o: ../engine/varray.h ../engine/shader.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/shader.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/shader.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/shader.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/shader.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/shadowmap.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/shadowmap.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/shadowmap.o: ../shared/iengine.h ../shared/igame.h ../engine/shadowmap.o: ../engine/world.h ../engine/octa.h ../engine/shadowmap.o: ../engine/lightmap.h ../engine/bih.h ../engine/shadowmap.o: ../engine/texture.h ../engine/model.h ../engine/shadowmap.o: ../engine/varray.h ../engine/rendertarget.h ../engine/sound.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/sound.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/sound.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/sound.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/sound.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/texture.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/texture.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/texture.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/texture.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/texture.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/texture.o: ../engine/scale.h ../engine/water.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/water.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/water.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/water.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/water.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/world.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/world.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/world.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/world.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/world.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../engine/worldio.o: ../engine/engine.h ../shared/cube.h ../shared/tools.h ../engine/worldio.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../engine/worldio.o: ../shared/iengine.h ../shared/igame.h ../engine/world.h ../engine/worldio.o: ../engine/octa.h ../engine/lightmap.h ../engine/bih.h ../engine/worldio.o: ../engine/texture.h ../engine/model.h ../engine/varray.h ../rpggame/ent.o: rpg.h ../shared/cube.h ../shared/tools.h ../shared/geom.h ../rpggame/ent.o: ../shared/ents.h ../shared/command.h ../shared/iengine.h ../rpggame/ent.o: ../shared/igame.h stats.h rpgent.h rpgobj.h ../rpggame/entities.o: rpg.h ../shared/cube.h ../shared/tools.h ../rpggame/entities.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../rpggame/entities.o: ../shared/iengine.h ../shared/igame.h stats.h rpgent.h ../rpggame/entities.o: rpgobj.h ../rpggame/objset.o: rpg.h ../shared/cube.h ../shared/tools.h ../rpggame/objset.o: ../shared/geom.h ../shared/ents.h ../shared/command.h ../rpggame/objset.o: ../shared/iengine.h ../shared/igame.h stats.h rpgent.h ../rpggame/objset.o: rpgobj.h ../rpggame/rpg.o: rpg.h ../shared/cube.h ../shared/tools.h ../shared/geom.h ../rpggame/rpg.o: ../shared/ents.h ../shared/command.h ../shared/iengine.h ../rpggame/rpg.o: ../shared/igame.h stats.h rpgent.h rpgobj.h ../shared/cube.h.gch: ../shared/tools.h ../shared/geom.h ../shared/ents.h ../shared/cube.h.gch: ../shared/command.h ../shared/iengine.h ../shared/cube.h.gch: ../shared/igame.h ../rpggame/rpg.h.gch: ../shared/cube.h ../shared/tools.h ../shared/geom.h ../rpggame/rpg.h.gch: ../shared/ents.h ../shared/command.h ../rpggame/rpg.h.gch: ../shared/iengine.h ../shared/igame.h stats.h rpgent.h ../rpggame/rpg.h.gch: rpgobj.h sauerbraten-0.0.20130203.dfsg/rpggame/rpgent.h0000644000175000017500000000267011370357712020502 0ustar vincentvincentstruct rpgent : dynent { rpgobj *ro; int lastaction, lastpain; bool attacking; bool magicprojectile; vec mppos, mpdir; rpgobj *mpweapon; float mpdist; rpgent *enemy; float targetyaw, rotspeed; enum { R_STARE, R_ROAM, R_SEEK, R_ATTACK, R_BLOCKED, R_BACKHOME }; int npcstate; int trigger; float sink; vec home; enum { ROTSPEED = 200 }; rpgent(rpgobj *_ro, const vec &_pos, float _yaw, int _maxspeed = 40, int _type = ENT_AI) : ro(_ro), lastaction(0), lastpain(0), attacking(false), magicprojectile(false), enemy(NULL), rotspeed(0), npcstate(R_STARE), trigger(0), sink(0) { o = _pos; home = _pos; targetyaw = yaw = _yaw; maxspeed = _maxspeed; type = _type; enemy = player1; } float relyaw(vec &t) { return -(float)atan2(t.x-o.x, t.y-o.y)/RAD; }; void normalize_yaw(float angle) { while(yawangle+180.0f) yaw -= 360.0f; } void tryattackobj(rpgobj &eo, rpgobj &weapon); void tryattack(vec &lookatpos, rpgobj &weapon); void updateprojectile(); bool allowmove(); void transition(int _state, int _moving, int n); void gotoyaw(float yaw, int s, int m, int t); void gotopos(vec &pos, int s, int m, int t); void goroam(); void stareorroam(); void update(float playerdist); void updateplayer(); }; sauerbraten-0.0.20130203.dfsg/rpggame/objset.cpp0000644000175000017500000001262011370357712021020 0ustar vincentvincent#include "rpg.h" namespace game { vector objects, stack; hashtable names; rpgobj *pointingat = NULL; rpgobj *playerobj = NULL; rpgobj *selected = NULL; rpgquest *quests = NULL; rpgquest *currentquest = NULL; void resetstack() { stack.setsize(0); loopi(10) stack.add(playerobj); // determines the stack depth } void clearworld() { if(playerobj) { playerobj->ent = NULL; delete playerobj; } playerobj = new rpgobj("player"); playerobj->ent = player1; player1->ro = playerobj; pointingat = NULL; objects.deletecontents(); resetstack(); playerobj->scriptinit(); // will fail when this is called from emptymap(), which is ok } void removefromsystem(rpgobj *o) { removefromworld(o); o->decontain(); if(pointingat==o) pointingat = NULL; if(selected==o) selected = NULL; resetstack(); DELETEP(o); } void updateobjects() { pointingat = NULL; loopv(objects) { objects[i]->update(); float dist = player1->o.dist(objects[i]->ent->o); if(dist<50 && intersect(objects[i]->ent, player1->o, worldpos) && (!pointingat || player1->o.dist(pointingat->ent->o)>dist)) { pointingat = objects[i]; } } } void spawn(char *name) { rpgobj *o = new rpgobj(name); pushobj(o); o->scriptinit(); } void placeinworld(vec &pos, float yaw) { stack[0]->placedinworld(new rpgent(stack[0], pos, yaw)); objects.add(stack[0]); } void spawnfroment(rpgentity &e) { spawn(e.name); placeinworld(e.o, e.attr1); } void pushobj(rpgobj *o) { stack.pop(); stack.insert(0, o); } // never overflows, just removes bottom void popobj() { stack.add(stack.remove(0)); } // never underflows, just puts it at the bottom void removefromworld(rpgobj *worldobj) { objects.removeobj(worldobj); DELETEP(worldobj->ent); } void taken(rpgobj *worldobj, rpgobj *newowner) { removefromworld(worldobj); newowner->add(worldobj, false); } void takefromplayer(char *name, char *ok, char *notok) { rpgobj *o = playerobj->take(name); if(o) { stack[0]->add(o, false); conoutf("\f2you hand over a %s", o->name); if(currentquest) { conoutf("\f2you finish a quest for %s", currentquest->npc); currentquest->completed = true; } } execute(o ? ok : notok); } void givetoplayer(char *name) { rpgobj *o = stack[0]->take(name); if(o) { conoutf("\f2you receive a %s", o->name); playerobj->add(o, false); } } rpgquest *addquest(const char *questline, const char *npc) { quests = new rpgquest(quests, npc, questline); conoutf("\f2you have accepted a quest for %s", npc); return quests; } void listquests(bool completed, g3d_gui &g) { for(rpgquest *q = quests; q; q = q->next) if(q->completed==completed) { defformatstring(info)("%s: %s", q->npc, q->questline); g.text(info, 0xAAAAAA, "info"); } } char *stringpool(char *name) { char **n = names.access(name); if(n) return *n; name = newstring(name); names[name] = name; return name; } void renderobjects() { loopv(objects) objects[i]->render(); } void g3d_npcmenus() { loopv(objects) objects[i]->g3d_menu(); } #define N(n) ICOMMAND(r_##n, "i", (int *val), { stack[0]->s_##n = *val; }); \ ICOMMAND(r_get_##n, "", (), { intret(stack[0]->s_##n); }); RPGNAMES #undef N #define N(n) ICOMMAND(r_def_##n, "ii", (int *i1, int *i2), { stats::def_##n(*i1, *i2); }); \ ICOMMAND(r_eff_##n, "", (), { intret(stack[0]->eff_##n()); }); RPGSTATNAMES #undef N ICOMMAND(r_model, "s", (char *s), { stack[0]->model = stringpool(s); }); ICOMMAND(r_spawn, "s", (char *s), { spawn(stringpool(s)); }); ICOMMAND(r_contain, "s", (char *s), { stack[0]->decontain(); stack[1]->add(stack[0], atoi(s)); }); ICOMMAND(r_pop, "", (), { popobj(); }); ICOMMAND(r_swap, "", (), { swap(stack[0], stack[1]); }); ICOMMAND(r_say, "s", (char *s), { stack[0]->abovetext = stringpool(s); }); ICOMMAND(r_quest, "ss", (char *s, char *a), { stack[0]->addaction(stringpool(s), stringpool(a), true); }); ICOMMAND(r_action, "ss", (char *s, char *a), { stack[0]->addaction(stringpool(s), stringpool(a), false); }); ICOMMAND(r_action_use, "s", (char *s), { stack[0]->action_use.script = stringpool(s); }); ICOMMAND(r_take, "sss", (char *name, char *ok, char *notok), { takefromplayer(name, ok, notok); }); ICOMMAND(r_give, "s", (char *s), { givetoplayer(s); }); ICOMMAND(r_use, "", (), { stack[0]->selectuse(); }); ICOMMAND(r_applydamage, "i", (int *d), { stack[0]->takedamage(*d, *stack[1]); }); } sauerbraten-0.0.20130203.dfsg/rpggame/rpg.vcproj0000644000175000017500000014153311525535131021044 0ustar vincentvincent sauerbraten-0.0.20130203.dfsg/rpggame/stats.h0000644000175000017500000000601611370371071020331 0ustar vincentvincent // all of these stats are the total "points" an object has // points are converted into efficiency = log(points/pointscale+1)*percentscale+100 // efficiency is by default 100% and rises logarithmically from that, according to the two scale vars, which are set in script // efficiency is used with a base value, i.e. a sword that does 10 damage used by a player with 150% melee efficiency does 15 damage // with this define, we can uses these names to define vars, strings, functions etc // see rpg.html for detailed explanation as to their meaning #define RPGSTATNAMES \ N(melee) \ N(ranged) \ N(magic) \ \ N(hpregen) \ N(manaregen) \ \ N(maxhp) \ N(maxmana) \ \ N(attackspeed) \ N(movespeed) \ N(jumpheight) \ N(tradeskill) \ N(feared) \ N(stealth) \ N(hostility) \ \ N(stata) \ N(statb) \ N(statc) \ #define RPGATTRNAMES \ N(ai) \ N(hp) \ N(mana) \ N(gold) \ N(worth) \ N(useamount) \ N(usetype) \ N(damage) \ N(maxrange) \ N(maxangle) \ N(attackrate) \ N(manacost) \ N(effectparticle) \ N(effectcolor) \ N(effectsize) \ \ N(attra) \ N(attrb) \ N(attrc) \ \ N(usesound) #define RPGNAMES RPGSTATNAMES RPGATTRNAMES struct stats { #define N(n) static int pointscale_##n, percentscale_##n; \ static void def_##n(int a, int b) { pointscale_##n = a; percentscale_##n = b; } \ int eff_##n() { return int(logf(s_##n/pointscale_##n+1)*percentscale_##n)+100; } RPGSTATNAMES #undef N #define N(n) int s_##n; RPGNAMES #undef N int statupdatetime; stats() : statupdatetime(0) { st_reset(); #define N(n) s_##n = 0; RPGATTRNAMES #undef N } void st_reset() { #define N(n) s_##n = 0; RPGSTATNAMES #undef N } template void st_accumulate(T &o) { #define N(n) s_##n += o.s_##n; RPGSTATNAMES #undef N } void st_show(g3d_gui &g) { #define N(n) if(s_##n) { defformatstring(s)(#n ": %d => %d%%", s_##n, eff_##n()); g.text(s, 0xFFFFFF, "info"); } RPGSTATNAMES #undef N #define N(n) if(s_##n) { defformatstring(s)(#n ": %d", s_##n); g.text(s, 0xFFAAAA, "info"); } RPGATTRNAMES #undef N } void st_init() { s_hp = eff_maxhp(); s_mana = eff_maxmana(); } void st_respawn() // player only { s_hp = 10; } void st_update() { if(lastmillis-statupdatetime>1000) { statupdatetime += 1000; const int base_hp_regen_rate = 2, base_mana_regen_rate = 3; // in script? s_hp += eff_hpregen() *base_hp_regen_rate /100; s_mana += eff_manaregen()*base_mana_regen_rate/100; if(s_hp >eff_maxhp()) s_hp = eff_maxhp(); if(s_mana>eff_maxmana()) s_mana = eff_maxmana(); } } }; sauerbraten-0.0.20130203.dfsg/rpggame/rpg.cpp0000644000175000017500000002121012067542067020320 0ustar vincentvincent#include "rpg.h" namespace game { #define N(n) int stats::pointscale_##n, stats::percentscale_##n; RPGSTATNAMES #undef N rpgent *player1 = NULL; int maptime = 0; string mapname = ""; void updateworld() { if(!maptime) { maptime = lastmillis; return; } if(!curtime) return; physicsframe(); updateobjects(); player1->updateplayer(); } bool connected = false; void gameconnect(bool _remote) { connected = true; if(editmode) toggleedit(); } void gamedisconnect(bool cleanup) { connected = false; } void changemap(const char *name) { if(!connected) localconnect(); if(editmode) toggleedit(); if(!load_world(name)) emptymap(0, true, name); } void forceedit(const char *name) { changemap(name); } ICOMMAND(map, "s", (char *s), changemap(s)); struct rpgmenu : g3d_callback { int time, tab, which; vec pos; rpgmenu() : time(0), tab(1), which(0), pos(0, 0, 0) {} void show(int n) { if((time && n==which) || !n) time = 0; else { time = starttime(); pos = menuinfrontofplayer(); which = n; } } void gui(g3d_gui &g, bool firstpass) { g.start(time, 0.03f, &tab); switch(which) { default: case 1: g.tab("inventory", 0xFFFFF); playerobj->invgui(g); break; case 2: g.tab("stats", 0xFFFFF); playerobj->st_show(g); break; case 3: g.tab("active quests", 0xFFFFF); listquests(false, g); g.tab("completed quests", 0xFFFFF); listquests(true, g); break; } g.end(); } void render() { if(time) g3d_addgui(this, pos, GUI_2D); } } menu; ICOMMAND(showplayergui, "i", (int *which), menu.show(*which)); void initclient() { player1 = new rpgent(playerobj, vec(0, 0, 0), 0, 100, ENT_PLAYER); clearworld(); } void physicstrigger(physent *d, bool local, int floorlevel, int waterlevel, int material) { if (waterlevel>0) playsoundname("free/splash1", d==player1 ? NULL : &d->o); else if(waterlevel<0) playsoundname("free/splash2", d==player1 ? NULL : &d->o); if (floorlevel>0) { if(local) playsoundname("aard/jump"); else if(d->type==ENT_AI) playsoundname("aard/jump", &d->o); } else if(floorlevel<0) { if(local) playsoundname("aard/land"); else if(d->type==ENT_AI) playsoundname("aard/land", &d->o); } } void dynentcollide(physent *d, physent *o, const vec &dir) {} void bounced(physent *d, const vec &surface) {} void edittrigger(const selinfo &sel, int op, int arg1, int arg2, int arg3) {} void vartrigger(ident *id) {} const char *getclientmap() { return mapname; } const char *getmapinfo() { return NULL; } void resetgamestate() {} void suicide(physent *d) {} void newmap(int size) {} void startmap(const char *name) { clearworld(); copystring(mapname, name ? name : ""); maptime = 0; findplayerspawn(player1); if(name) playerobj->st_init(); entities::startmap(); } void quad(int x, int y, int xs, int ys) { glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2i(x, y); glTexCoord2f(1, 0); glVertex2i(x+xs, y); glTexCoord2f(0, 1); glVertex2i(x, y+ys); glTexCoord2f(1, 1); glVertex2i(x+xs, y+ys); glEnd(); } bool needminimap() { return false; } float abovegameplayhud(int w, int h) { switch(player1->state) { case CS_EDITING: return 1; default: return (h-min(128, h))/float(h); } } void gameplayhud(int w, int h) { glPushMatrix(); glScalef(0.5f, 0.5f, 1); draw_textf("using: %s", 636*2, h*2-256+149, selected ? selected->name : "(none)"); // temp glPopMatrix(); settexture("packages/hud/hud_rpg.png", 3); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); quad(0, h-128, 768, 128); settexture("packages/hud/hbar.png", 3); glColor4f(1, 0, 0, 0.5f); quad(130, h-128+57, 193*playerobj->s_hp/playerobj->eff_maxhp(), 17); glColor4f(0, 0, 1, 0.5f); quad(130, h-128+87, 193*playerobj->s_mana/playerobj->eff_maxmana(), 17); } int clipconsole(int w, int h) { return 0; } void preload() {} void renderavatar() { } void renderplayerpreview(int model, int team, int weap) { } bool canjump() { return true; } bool allowmove(physent *d) { return d->type!=ENT_AI || ((rpgent *)d)->allowmove(); } void doattack(bool on) { player1->attacking = on; } dynent *iterdynents(int i) { return i ? objects[i-1]->ent : player1; } int numdynents() { return objects.length()+1; } void rendergame(bool mainpass) { if(isthirdperson()) renderclient(player1, "ogro", NULL, 0, ANIM_ATTACK1, 300, player1->lastaction, player1->lastpain); renderobjects(); } void g3d_gamemenus() { g3d_npcmenus(); menu.render(); } const char *defaultcrosshair(int index) { return "data/crosshair.png"; } int selectcrosshair(float &r, float &g, float &b) { if(player1->state==CS_DEAD) return -1; return 0; } bool serverinfostartcolumn(g3d_gui *g, int i) { return false; } void serverinfoendcolumn(g3d_gui *g, int i) {} bool serverinfoentry(g3d_gui *g, int i, const char *name, int port, const char *sdesc, const char *map, int ping, const vector &attr, int np) { return false; } void setupcamera() { } bool detachcamera() { return player1->state==CS_DEAD; } bool collidecamera() { return player1->state!=CS_EDITING; } void lighteffects(dynent *e, vec &color, vec &dir) { } void adddynlights() { } void dynlighttrack(physent *owner, vec &o, vec &hud) { } void particletrack(physent *owner, vec &o, vec &d) { } void writegamedata(vector &extras) {} void readgamedata (vector &extras) {} const char *gameident() { return "rpg"; } const char *savedconfig() { return "rpg_config.cfg"; } const char *restoreconfig() { return "rpg_restore.cfg"; } const char *defaultconfig() { return "data/defaults.cfg"; } const char *autoexec() { return "rpg_autoexec.cfg"; } const char *savedservers() { return NULL; } void loadconfigs() {} void parseoptions(vector &args) {} void connectattempt(const char *name, const char *password, const ENetAddress &address) {} void connectfail() {} void parsepacketclient(int chan, packetbuf &p) {} bool allowedittoggle() { return true; } void edittoggled(bool on) {} void writeclientinfo(stream *f) {} void toserver(char *text) {} bool ispaused() { return false; } int scaletime(int t) { return t*100; } bool allowmouselook() { return true; } } namespace server { void *newclientinfo() { return NULL; } void deleteclientinfo(void *ci) {} void serverinit() {} int reserveclients() { return 0; } int numchannels() { return 0; } void clientdisconnect(int n) {} int clientconnect(int n, uint ip) { return DISC_NONE; } void localdisconnect(int n) {} void localconnect(int n) {} bool allowbroadcast(int n) { return true; } void recordpacket(int chan, void *data, int len) {} void parsepacket(int sender, int chan, packetbuf &p) {} void sendservmsg(const char *s) {} bool sendpackets(bool force) { return false; } void serverinforeply(ucharbuf &req, ucharbuf &p) {} void serverupdate() {} bool servercompatible(char *name, char *sdec, char *map, int ping, const vector &attr, int np) { return true; } int serverinfoport(int servport) { return 0; } int serverport(int infoport) { return 0; } const char *defaultmaster() { return ""; } int masterport() { return 0; } int laninfoport() { return 0; } void processmasterinput(const char *cmd, int cmdlen, const char *args) {} bool ispaused() { return false; } int scaletime(int t) { return t*100; } } sauerbraten-0.0.20130203.dfsg/rpggame/rpg.sln0000644000175000017500000000205111422343360020321 0ustar vincentvincent Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "rpg", "rpg.vcproj", "{06594C6D-6DA9-49DC-9A91-8F47221DDCFD}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Profile|Win32 = Profile|Win32 Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {06594C6D-6DA9-49DC-9A91-8F47221DDCFD}.Debug|Win32.ActiveCfg = Debug|Win32 {06594C6D-6DA9-49DC-9A91-8F47221DDCFD}.Debug|Win32.Build.0 = Debug|Win32 {06594C6D-6DA9-49DC-9A91-8F47221DDCFD}.Profile|Win32.ActiveCfg = Profile|Win32 {06594C6D-6DA9-49DC-9A91-8F47221DDCFD}.Profile|Win32.Build.0 = Profile|Win32 {06594C6D-6DA9-49DC-9A91-8F47221DDCFD}.Release|Win32.ActiveCfg = Release|Win32 {06594C6D-6DA9-49DC-9A91-8F47221DDCFD}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal sauerbraten-0.0.20130203.dfsg/rpggame/ent.cpp0000644000175000017500000002031511370371071020312 0ustar vincentvincent#include "rpg.h" namespace game { static const int ATTACKSAMPLES = 32; void rpgent::tryattackobj(rpgobj &eo, rpgobj &weapon) { if(!eo.s_ai || (eo.s_ai==ro->s_ai && eo.ent!=enemy)) return; rpgent &e = *eo.ent; if(e.state!=CS_ALIVE) return; vec d = e.o; d.sub(o); d.z = 0; if(d.magnitude()>e.radius+weapon.s_maxrange) return; if(o.z+aboveeye<=e.o.z-e.eyeheight || o.z-eyeheight>=e.o.z+e.aboveeye) return; vec p(0, 0, 0), closep; float closedist = 1e10f; loopj(ATTACKSAMPLES) { p.x = e.xradius * cosf(2*M_PI*j/ATTACKSAMPLES); p.y = e.yradius * sinf(2*M_PI*j/ATTACKSAMPLES); p.rotate_around_z((e.yaw+90)*RAD); p.x += e.o.x; p.y += e.o.y; float tyaw = relyaw(p); normalize_yaw(tyaw); if(fabs(tyaw-yaw)>weapon.s_maxangle) continue; float dx = p.x-o.x, dy = p.y-o.y, dist = dx*dx + dy*dy; if(distweapon.s_maxrange*weapon.s_maxrange) return; weapon.useaction(eo, *this, true); } float intersectdist; bool intersect(dynent *d, const vec &from, const vec &to, float &dist) { vec bottom(d->o), top(d->o); bottom.z -= d->eyeheight; top.z += d->aboveeye; return linecylinderintersect(from, to, bottom, top, d->radius, dist); } #define loopallrpgobjsexcept(ro) loop(i, objects.length()+1) for(rpgobj *eo = i ? objects[i-1] : playerobj; eo; eo = NULL) if((ro)!=eo) void rpgent::tryattack(vec &lookatpos, rpgobj &weapon) { if(lastmillis-lastactionent->state!=CS_ALIVE) continue; if(!intersect(eo->ent, o, lookatpos)) continue; float dist = o.dist(eo->ent->o); if(distusemana(weapon)) return; magicprojectile = true; mpweapon = &weapon; mppos = o; //mpdir = vec(yaw*RAD, pitch*RAD); float worlddist = lookatpos.dist(o, mpdir); mpdir.normalize(); mpdist = min(float(weapon.s_maxrange), worlddist); } else { weapon.useaction(*ro, *this, true); // cast on self } break; } } void rpgent::updateprojectile() { if(!magicprojectile) return; regular_particle_splash(PART_SMOKE, 2, 300, mppos, 0x404040, 0.6f, 150, -20); particle_splash(PART_FIREBALL1+mpweapon->s_effectparticle, 1, 1, mppos, mpweapon->s_effectcolor, mpweapon->s_effectsize/100.0f); float dist = curtime/5.0f; if((mpdist -= dist)<0) { magicprojectile = false; return; }; vec mpto = vec(mpdir).mul(dist).add(mppos); loopallrpgobjsexcept(ro) // FIXME: make fast "give me all rpgobs in range R that are not X" function { if(eo->ent->o.dist(mppos)<32 && intersect(eo->ent, mppos, mpto)) // quick reject, for now { magicprojectile = false; mpweapon->useaction(*eo, *this, false); // cast on target } } mppos = mpto; } bool rpgent::allowmove() { if(rotspeed && yaw!=targetyaw) { float diff = rotspeed*curtime/1000.0f, maxdiff = fabs(targetyaw-yaw); if(diff >= maxdiff) { yaw = targetyaw; rotspeed = 0; } else yaw += (targetyaw>yaw ? 1 : -1) * min(diff, maxdiff); normalize_yaw(targetyaw); } return true; } void rpgent::transition(int _state, int _moving, int n) { npcstate = _state; move = _moving; trigger = lastmillis+n; } void rpgent::gotoyaw(float yaw, int s, int m, int t) { targetyaw = yaw; rotspeed = ROTSPEED; transition(s, m, t); } void rpgent::gotopos(vec &pos, int s, int m, int t) { gotoyaw(relyaw(pos), s, m, t); } void rpgent::goroam() { if(home.dist(o)>128 && npcstate!=R_BACKHOME) gotopos(home, R_ROAM, 1, 1000); else gotoyaw(targetyaw+90+rnd(180), R_ROAM, 1, 1000); } void rpgent::stareorroam() { if(rnd(10)) transition(R_STARE, 0, 500); else goroam(); } void rpgent::update(float playerdist) { updateprojectile(); if(state==CS_DEAD) { stopmoving(); return; }; if(blocked && npcstate!=R_BLOCKED && npcstate!=R_SEEK) { blocked = false; gotoyaw(targetyaw+90+rnd(180), R_BLOCKED, 1, 1000); } if(ro->s_hpeff_maxhp() && npcstate!=R_SEEK) gotopos(enemy->o, R_SEEK, 1, 200); #define ifnextstate if(triggers_ai==2) { gotopos(player1->o, R_SEEK, 1, 200); enemy = player1; } else { gotopos(player1->o, R_STARE, 0, 500); } } else ifnextstate stareorroam(); break; case R_ROAM: ifplayerclose transition(R_STARE, 0, 500); else ifnextstate stareorroam(); break; case R_SEEK: ifnextstate { vec target; if(raycubelos(o, enemy->o, target)) { rpgobj &weapon = ro->selectedweapon(); if(target.dist(o)o.dist(o)>256) goroam(); else gotopos(enemy->o, R_SEEK, 1, 100); } } #undef ifnextstate #undef ifplayerclose } void rpgent::updateplayer() // alternative version of update() if this ent is the main player { updateprojectile(); if(state==CS_DEAD) { //lastaction = lastmillis; if(lastmillis-lastaction>5000) { conoutf("\f2you were found unconscious, and have been carried back home"); findplayerspawn(this); state = CS_ALIVE; ro->st_respawn(); attacking = false; particle_splash(PART_SPARK, 1000, 500, o, 0x3232FF, 0.32f); } } else { moveplayer(this, 10, true); ro->st_update(); if(attacking) tryattack(worldpos, ro->selectedweapon()); } } } sauerbraten-0.0.20130203.dfsg/rpggame/rpg.cbp0000644000175000017500000002152112017225415020275 0ustar vincentvincent sauerbraten-0.0.20130203.dfsg/rpggame/pch.cpp0000644000175000017500000000002211422343360020265 0ustar vincentvincent#include "rpg.h" sauerbraten-0.0.20130203.dfsg/rpggame/rpg.h0000644000175000017500000000320711370357712017770 0ustar vincentvincent#include "cube.h" enum { ETR_SPAWN = ET_GAMESPECIFIC, }; static const int SPAWNNAMELEN = 64; struct rpgentity : extentity { char name[SPAWNNAMELEN]; rpgentity() { memset(name, 0, SPAWNNAMELEN); } }; namespace entities { extern vector ents; extern void startmap(); } namespace game { struct rpgent; struct rpgobj; struct rpgaction; struct rpgquest { rpgquest *next; const char *npc; const char *questline; bool completed; rpgquest(rpgquest *_n, const char *_npc, const char *_ql) : next(_n), npc(_npc), questline(_ql), completed(false) {} }; extern rpgent *player1; extern vector objects, stack; extern rpgobj *pointingat; extern rpgobj *playerobj; extern rpgobj *selected; extern rpgquest *quest; extern rpgquest *currentquest; extern void pushobj(rpgobj *o); extern void popobj(); extern void spawn(char *name); extern void placeinworld(vec &pos, float yaw); extern void spawnfroment(rpgentity &e); extern void removefromworld(rpgobj *worldobj); extern void removefromsystem(rpgobj *o); extern void taken(rpgobj *worldobj, rpgobj *newowner); extern void clearworld(); extern void updateobjects(); extern void renderobjects(); extern void listquests(bool completed, g3d_gui &g); extern rpgquest *addquest(const char *questline, const char *npc); extern void g3d_npcmenus(); extern float intersectdist; extern bool intersect(dynent *d, const vec &from, const vec &to, float &dist = intersectdist); #include "stats.h" #include "rpgent.h" #include "rpgobj.h" } sauerbraten-0.0.20130203.dfsg/include/0000755000175000017500000000000012100771031017010 5ustar vincentvincentsauerbraten-0.0.20130203.dfsg/include/SDL_config_macosx.h0000644000175000017500000001014111706600205022504 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 /* 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_copying.h0000644000175000017500000000154511706600205021345 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_main.h0000644000175000017500000000546211706600205020623 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_cdrom.h0000644000175000017500000001364011706600205021000 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_quit.h0000644000175000017500000000373111706600205020656 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/GL/0000755000175000017500000000000012100771031017312 5ustar vincentvincentsauerbraten-0.0.20130203.dfsg/include/GL/glext.h0000644000175000017500000121467011164573771020645 0ustar vincentvincent#ifndef __glext_h_ #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 #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 #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 sauerbraten-0.0.20130203.dfsg/include/zconf.h0000644000175000017500000003207711706600205020316 0ustar vincentvincent/* 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 /* 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 /* 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 /* for SEEK_* and off_t */ # ifdef VMS # include /* 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL.h0000644000175000017500000000624111706600205017613 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/close_code.h0000644000175000017500000000271211706600205021267 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_events.h0000644000175000017500000003136111706600205021200 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_mixer.h0000644000175000017500000006613311706600205021025 0ustar vincentvincent/* SDL_mixer: An audio mixer library based on the SDL library Copyright (C) 1997-2012 Sam Lantinga 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. */ /* $Id$ */ #ifndef _SDL_MIXER_H #define _SDL_MIXER_H #include "SDL_types.h" #include "SDL_rwops.h" #include "SDL_audio.h" #include "SDL_endian.h" #include "SDL_version.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL */ #define SDL_MIXER_MAJOR_VERSION 1 #define SDL_MIXER_MINOR_VERSION 2 #define SDL_MIXER_PATCHLEVEL 12 /* This macro can be used to fill a version structure with the compile-time * version of the SDL_mixer library. */ #define SDL_MIXER_VERSION(X) \ { \ (X)->major = SDL_MIXER_MAJOR_VERSION; \ (X)->minor = SDL_MIXER_MINOR_VERSION; \ (X)->patch = SDL_MIXER_PATCHLEVEL; \ } /* Backwards compatibility */ #define MIX_MAJOR_VERSION SDL_MIXER_MAJOR_VERSION #define MIX_MINOR_VERSION SDL_MIXER_MINOR_VERSION #define MIX_PATCHLEVEL SDL_MIXER_PATCHLEVEL #define MIX_VERSION(X) SDL_MIXER_VERSION(X) /* This function gets the version of the dynamically linked SDL_mixer library. it should NOT be used to fill a version structure, instead you should use the SDL_MIXER_VERSION() macro. */ extern DECLSPEC const SDL_version * SDLCALL Mix_Linked_Version(void); typedef enum { MIX_INIT_FLAC = 0x00000001, MIX_INIT_MOD = 0x00000002, MIX_INIT_MP3 = 0x00000004, MIX_INIT_OGG = 0x00000008, MIX_INIT_FLUIDSYNTH = 0x00000010 } MIX_InitFlags; /* Loads dynamic libraries and prepares them for use. Flags should be one or more flags from MIX_InitFlags OR'd together. It returns the flags successfully initialized, or 0 on failure. */ extern DECLSPEC int SDLCALL Mix_Init(int flags); /* Unloads libraries loaded with Mix_Init */ extern DECLSPEC void SDLCALL Mix_Quit(void); /* The default mixer has 8 simultaneous mixing channels */ #ifndef MIX_CHANNELS #define MIX_CHANNELS 8 #endif /* Good default values for a PC soundcard */ #define MIX_DEFAULT_FREQUENCY 22050 #if SDL_BYTEORDER == SDL_LIL_ENDIAN #define MIX_DEFAULT_FORMAT AUDIO_S16LSB #else #define MIX_DEFAULT_FORMAT AUDIO_S16MSB #endif #define MIX_DEFAULT_CHANNELS 2 #define MIX_MAX_VOLUME 128 /* Volume of a chunk */ /* The internal format for an audio chunk */ typedef struct Mix_Chunk { int allocated; Uint8 *abuf; Uint32 alen; Uint8 volume; /* Per-sample volume, 0-128 */ } Mix_Chunk; /* The different fading types supported */ typedef enum { MIX_NO_FADING, MIX_FADING_OUT, MIX_FADING_IN } Mix_Fading; typedef enum { MUS_NONE, MUS_CMD, MUS_WAV, MUS_MOD, MUS_MID, MUS_OGG, MUS_MP3, MUS_MP3_MAD, MUS_FLAC, MUS_MODPLUG } Mix_MusicType; /* The internal format for a music chunk interpreted via mikmod */ typedef struct _Mix_Music Mix_Music; /* Open the mixer with a certain audio format */ extern DECLSPEC int SDLCALL Mix_OpenAudio(int frequency, Uint16 format, int channels, int chunksize); /* Dynamically change the number of channels managed by the mixer. If decreasing the number of channels, the upper channels are stopped. This function returns the new number of allocated channels. */ extern DECLSPEC int SDLCALL Mix_AllocateChannels(int numchans); /* Find out what the actual audio device parameters are. This function returns 1 if the audio has been opened, 0 otherwise. */ extern DECLSPEC int SDLCALL Mix_QuerySpec(int *frequency,Uint16 *format,int *channels); /* Load a wave file or a music (.mod .s3m .it .xm) file */ extern DECLSPEC Mix_Chunk * SDLCALL Mix_LoadWAV_RW(SDL_RWops *src, int freesrc); #define Mix_LoadWAV(file) Mix_LoadWAV_RW(SDL_RWFromFile(file, "rb"), 1) extern DECLSPEC Mix_Music * SDLCALL Mix_LoadMUS(const char *file); /* Load a music file from an SDL_RWop object (Ogg and MikMod specific currently) Matt Campbell (matt@campbellhome.dhs.org) April 2000 */ extern DECLSPEC Mix_Music * SDLCALL Mix_LoadMUS_RW(SDL_RWops *rw); /* Load a music file from an SDL_RWop object assuming a specific format */ extern DECLSPEC Mix_Music * SDLCALL Mix_LoadMUSType_RW(SDL_RWops *rw, Mix_MusicType type, int freesrc); /* Load a wave file of the mixer format from a memory buffer */ extern DECLSPEC Mix_Chunk * SDLCALL Mix_QuickLoad_WAV(Uint8 *mem); /* Load raw audio data of the mixer format from a memory buffer */ extern DECLSPEC Mix_Chunk * SDLCALL Mix_QuickLoad_RAW(Uint8 *mem, Uint32 len); /* Free an audio chunk previously loaded */ extern DECLSPEC void SDLCALL Mix_FreeChunk(Mix_Chunk *chunk); extern DECLSPEC void SDLCALL Mix_FreeMusic(Mix_Music *music); /* Get a list of chunk/music decoders that this build of SDL_mixer provides. This list can change between builds AND runs of the program, if external libraries that add functionality become available. You must successfully call Mix_OpenAudio() before calling these functions. This API is only available in SDL_mixer 1.2.9 and later. // usage... int i; const int total = Mix_GetNumChunkDecoders(); for (i = 0; i < total; i++) printf("Supported chunk decoder: [%s]\n", Mix_GetChunkDecoder(i)); Appearing in this list doesn't promise your specific audio file will decode...but it's handy to know if you have, say, a functioning Timidity install. These return values are static, read-only data; do not modify or free it. The pointers remain valid until you call Mix_CloseAudio(). */ extern DECLSPEC int SDLCALL Mix_GetNumChunkDecoders(void); extern DECLSPEC const char * SDLCALL Mix_GetChunkDecoder(int index); extern DECLSPEC int SDLCALL Mix_GetNumMusicDecoders(void); extern DECLSPEC const char * SDLCALL Mix_GetMusicDecoder(int index); /* Find out the music format of a mixer music, or the currently playing music, if 'music' is NULL. */ extern DECLSPEC Mix_MusicType SDLCALL Mix_GetMusicType(const Mix_Music *music); /* Set a function that is called after all mixing is performed. This can be used to provide real-time visual display of the audio stream or add a custom mixer filter for the stream data. */ extern DECLSPEC void SDLCALL Mix_SetPostMix(void (*mix_func) (void *udata, Uint8 *stream, int len), void *arg); /* Add your own music player or additional mixer function. If 'mix_func' is NULL, the default music player is re-enabled. */ extern DECLSPEC void SDLCALL Mix_HookMusic(void (*mix_func) (void *udata, Uint8 *stream, int len), void *arg); /* Add your own callback when the music has finished playing. This callback is only called if the music finishes naturally. */ extern DECLSPEC void SDLCALL Mix_HookMusicFinished(void (*music_finished)(void)); /* Get a pointer to the user data for the current music hook */ extern DECLSPEC void * SDLCALL Mix_GetMusicHookData(void); /* * Add your own callback when a channel has finished playing. NULL * to disable callback. The callback may be called from the mixer's audio * callback or it could be called as a result of Mix_HaltChannel(), etc. * do not call SDL_LockAudio() from this callback; you will either be * inside the audio callback, or SDL_mixer will explicitly lock the audio * before calling your callback. */ extern DECLSPEC void SDLCALL Mix_ChannelFinished(void (*channel_finished)(int channel)); /* Special Effects API by ryan c. gordon. (icculus@icculus.org) */ #define MIX_CHANNEL_POST -2 /* This is the format of a special effect callback: * * myeffect(int chan, void *stream, int len, void *udata); * * (chan) is the channel number that your effect is affecting. (stream) is * the buffer of data to work upon. (len) is the size of (stream), and * (udata) is a user-defined bit of data, which you pass as the last arg of * Mix_RegisterEffect(), and is passed back unmolested to your callback. * Your effect changes the contents of (stream) based on whatever parameters * are significant, or just leaves it be, if you prefer. You can do whatever * you like to the buffer, though, and it will continue in its changed state * down the mixing pipeline, through any other effect functions, then finally * to be mixed with the rest of the channels and music for the final output * stream. * * DO NOT EVER call SDL_LockAudio() from your callback function! */ typedef void (*Mix_EffectFunc_t)(int chan, void *stream, int len, void *udata); /* * This is a callback that signifies that a channel has finished all its * loops and has completed playback. This gets called if the buffer * plays out normally, or if you call Mix_HaltChannel(), implicitly stop * a channel via Mix_AllocateChannels(), or unregister a callback while * it's still playing. * * DO NOT EVER call SDL_LockAudio() from your callback function! */ typedef void (*Mix_EffectDone_t)(int chan, void *udata); /* Register a special effect function. At mixing time, the channel data is * copied into a buffer and passed through each registered effect function. * After it passes through all the functions, it is mixed into the final * output stream. The copy to buffer is performed once, then each effect * function performs on the output of the previous effect. Understand that * this extra copy to a buffer is not performed if there are no effects * registered for a given chunk, which saves CPU cycles, and any given * effect will be extra cycles, too, so it is crucial that your code run * fast. Also note that the data that your function is given is in the * format of the sound device, and not the format you gave to Mix_OpenAudio(), * although they may in reality be the same. This is an unfortunate but * necessary speed concern. Use Mix_QuerySpec() to determine if you can * handle the data before you register your effect, and take appropriate * actions. * You may also specify a callback (Mix_EffectDone_t) that is called when * the channel finishes playing. This gives you a more fine-grained control * than Mix_ChannelFinished(), in case you need to free effect-specific * resources, etc. If you don't need this, you can specify NULL. * You may set the callbacks before or after calling Mix_PlayChannel(). * Things like Mix_SetPanning() are just internal special effect functions, * so if you are using that, you've already incurred the overhead of a copy * to a separate buffer, and that these effects will be in the queue with * any functions you've registered. The list of registered effects for a * channel is reset when a chunk finishes playing, so you need to explicitly * set them with each call to Mix_PlayChannel*(). * You may also register a special effect function that is to be run after * final mixing occurs. The rules for these callbacks are identical to those * in Mix_RegisterEffect, but they are run after all the channels and the * music have been mixed into a single stream, whereas channel-specific * effects run on a given channel before any other mixing occurs. These * global effect callbacks are call "posteffects". Posteffects only have * their Mix_EffectDone_t function called when they are unregistered (since * the main output stream is never "done" in the same sense as a channel). * You must unregister them manually when you've had enough. Your callback * will be told that the channel being mixed is (MIX_CHANNEL_POST) if the * processing is considered a posteffect. * * After all these effects have finished processing, the callback registered * through Mix_SetPostMix() runs, and then the stream goes to the audio * device. * * DO NOT EVER call SDL_LockAudio() from your callback function! * * returns zero if error (no such channel), nonzero if added. * Error messages can be retrieved from Mix_GetError(). */ extern DECLSPEC int SDLCALL Mix_RegisterEffect(int chan, Mix_EffectFunc_t f, Mix_EffectDone_t d, void *arg); /* You may not need to call this explicitly, unless you need to stop an * effect from processing in the middle of a chunk's playback. * Posteffects are never implicitly unregistered as they are for channels, * but they may be explicitly unregistered through this function by * specifying MIX_CHANNEL_POST for a channel. * returns zero if error (no such channel or effect), nonzero if removed. * Error messages can be retrieved from Mix_GetError(). */ extern DECLSPEC int SDLCALL Mix_UnregisterEffect(int channel, Mix_EffectFunc_t f); /* You may not need to call this explicitly, unless you need to stop all * effects from processing in the middle of a chunk's playback. Note that * this will also shut off some internal effect processing, since * Mix_SetPanning() and others may use this API under the hood. This is * called internally when a channel completes playback. * Posteffects are never implicitly unregistered as they are for channels, * but they may be explicitly unregistered through this function by * specifying MIX_CHANNEL_POST for a channel. * returns zero if error (no such channel), nonzero if all effects removed. * Error messages can be retrieved from Mix_GetError(). */ extern DECLSPEC int SDLCALL Mix_UnregisterAllEffects(int channel); #define MIX_EFFECTSMAXSPEED "MIX_EFFECTSMAXSPEED" /* * These are the internally-defined mixing effects. They use the same API that * effects defined in the application use, but are provided here as a * convenience. Some effects can reduce their quality or use more memory in * the name of speed; to enable this, make sure the environment variable * MIX_EFFECTSMAXSPEED (see above) is defined before you call * Mix_OpenAudio(). */ /* Set the panning of a channel. The left and right channels are specified * as integers between 0 and 255, quietest to loudest, respectively. * * Technically, this is just individual volume control for a sample with * two (stereo) channels, so it can be used for more than just panning. * If you want real panning, call it like this: * * Mix_SetPanning(channel, left, 255 - left); * * ...which isn't so hard. * * Setting (channel) to MIX_CHANNEL_POST registers this as a posteffect, and * the panning will be done to the final mixed stream before passing it on * to the audio device. * * This uses the Mix_RegisterEffect() API internally, and returns without * registering the effect function if the audio device is not configured * for stereo output. Setting both (left) and (right) to 255 causes this * effect to be unregistered, since that is the data's normal state. * * returns zero if error (no such channel or Mix_RegisterEffect() fails), * nonzero if panning effect enabled. Note that an audio device in mono * mode is a no-op, but this call will return successful in that case. * Error messages can be retrieved from Mix_GetError(). */ extern DECLSPEC int SDLCALL Mix_SetPanning(int channel, Uint8 left, Uint8 right); /* Set the position of a channel. (angle) is an integer from 0 to 360, that * specifies the location of the sound in relation to the listener. (angle) * will be reduced as neccesary (540 becomes 180 degrees, -100 becomes 260). * Angle 0 is due north, and rotates clockwise as the value increases. * For efficiency, the precision of this effect may be limited (angles 1 * through 7 might all produce the same effect, 8 through 15 are equal, etc). * (distance) is an integer between 0 and 255 that specifies the space * between the sound and the listener. The larger the number, the further * away the sound is. Using 255 does not guarantee that the channel will be * culled from the mixing process or be completely silent. For efficiency, * the precision of this effect may be limited (distance 0 through 5 might * all produce the same effect, 6 through 10 are equal, etc). Setting (angle) * and (distance) to 0 unregisters this effect, since the data would be * unchanged. * * If you need more precise positional audio, consider using OpenAL for * spatialized effects instead of SDL_mixer. This is only meant to be a * basic effect for simple "3D" games. * * If the audio device is configured for mono output, then you won't get * any effectiveness from the angle; however, distance attenuation on the * channel will still occur. While this effect will function with stereo * voices, it makes more sense to use voices with only one channel of sound, * so when they are mixed through this effect, the positioning will sound * correct. You can convert them to mono through SDL before giving them to * the mixer in the first place if you like. * * Setting (channel) to MIX_CHANNEL_POST registers this as a posteffect, and * the positioning will be done to the final mixed stream before passing it * on to the audio device. * * This is a convenience wrapper over Mix_SetDistance() and Mix_SetPanning(). * * returns zero if error (no such channel or Mix_RegisterEffect() fails), * nonzero if position effect is enabled. * Error messages can be retrieved from Mix_GetError(). */ extern DECLSPEC int SDLCALL Mix_SetPosition(int channel, Sint16 angle, Uint8 distance); /* Set the "distance" of a channel. (distance) is an integer from 0 to 255 * that specifies the location of the sound in relation to the listener. * Distance 0 is overlapping the listener, and 255 is as far away as possible * A distance of 255 does not guarantee silence; in such a case, you might * want to try changing the chunk's volume, or just cull the sample from the * mixing process with Mix_HaltChannel(). * For efficiency, the precision of this effect may be limited (distances 1 * through 7 might all produce the same effect, 8 through 15 are equal, etc). * (distance) is an integer between 0 and 255 that specifies the space * between the sound and the listener. The larger the number, the further * away the sound is. * Setting (distance) to 0 unregisters this effect, since the data would be * unchanged. * If you need more precise positional audio, consider using OpenAL for * spatialized effects instead of SDL_mixer. This is only meant to be a * basic effect for simple "3D" games. * * Setting (channel) to MIX_CHANNEL_POST registers this as a posteffect, and * the distance attenuation will be done to the final mixed stream before * passing it on to the audio device. * * This uses the Mix_RegisterEffect() API internally. * * returns zero if error (no such channel or Mix_RegisterEffect() fails), * nonzero if position effect is enabled. * Error messages can be retrieved from Mix_GetError(). */ extern DECLSPEC int SDLCALL Mix_SetDistance(int channel, Uint8 distance); /* * !!! FIXME : Haven't implemented, since the effect goes past the * end of the sound buffer. Will have to think about this. * --ryan. */ #if 0 /* Causes an echo effect to be mixed into a sound. (echo) is the amount * of echo to mix. 0 is no echo, 255 is infinite (and probably not * what you want). * * Setting (channel) to MIX_CHANNEL_POST registers this as a posteffect, and * the reverbing will be done to the final mixed stream before passing it on * to the audio device. * * This uses the Mix_RegisterEffect() API internally. If you specify an echo * of zero, the effect is unregistered, as the data is already in that state. * * returns zero if error (no such channel or Mix_RegisterEffect() fails), * nonzero if reversing effect is enabled. * Error messages can be retrieved from Mix_GetError(). */ extern no_parse_DECLSPEC int SDLCALL Mix_SetReverb(int channel, Uint8 echo); #endif /* Causes a channel to reverse its stereo. This is handy if the user has his * speakers hooked up backwards, or you would like to have a minor bit of * psychedelia in your sound code. :) Calling this function with (flip) * set to non-zero reverses the chunks's usual channels. If (flip) is zero, * the effect is unregistered. * * This uses the Mix_RegisterEffect() API internally, and thus is probably * more CPU intensive than having the user just plug in his speakers * correctly. Mix_SetReverseStereo() returns without registering the effect * function if the audio device is not configured for stereo output. * * If you specify MIX_CHANNEL_POST for (channel), then this the effect is used * on the final mixed stream before sending it on to the audio device (a * posteffect). * * returns zero if error (no such channel or Mix_RegisterEffect() fails), * nonzero if reversing effect is enabled. Note that an audio device in mono * mode is a no-op, but this call will return successful in that case. * Error messages can be retrieved from Mix_GetError(). */ extern DECLSPEC int SDLCALL Mix_SetReverseStereo(int channel, int flip); /* end of effects API. --ryan. */ /* Reserve the first channels (0 -> n-1) for the application, i.e. don't allocate them dynamically to the next sample if requested with a -1 value below. Returns the number of reserved channels. */ extern DECLSPEC int SDLCALL Mix_ReserveChannels(int num); /* Channel grouping functions */ /* Attach a tag to a channel. A tag can be assigned to several mixer channels, to form groups of channels. If 'tag' is -1, the tag is removed (actually -1 is the tag used to represent the group of all the channels). Returns true if everything was OK. */ extern DECLSPEC int SDLCALL Mix_GroupChannel(int which, int tag); /* Assign several consecutive channels to a group */ extern DECLSPEC int SDLCALL Mix_GroupChannels(int from, int to, int tag); /* Finds the first available channel in a group of channels, returning -1 if none are available. */ extern DECLSPEC int SDLCALL Mix_GroupAvailable(int tag); /* Returns the number of channels in a group. This is also a subtle way to get the total number of channels when 'tag' is -1 */ extern DECLSPEC int SDLCALL Mix_GroupCount(int tag); /* Finds the "oldest" sample playing in a group of channels */ extern DECLSPEC int SDLCALL Mix_GroupOldest(int tag); /* Finds the "most recent" (i.e. last) sample playing in a group of channels */ extern DECLSPEC int SDLCALL Mix_GroupNewer(int tag); /* Play an audio chunk on a specific channel. If the specified channel is -1, play on the first free channel. If 'loops' is greater than zero, loop the sound that many times. If 'loops' is -1, loop inifinitely (~65000 times). Returns which channel was used to play the sound. */ #define Mix_PlayChannel(channel,chunk,loops) Mix_PlayChannelTimed(channel,chunk,loops,-1) /* The same as above, but the sound is played at most 'ticks' milliseconds */ extern DECLSPEC int SDLCALL Mix_PlayChannelTimed(int channel, Mix_Chunk *chunk, int loops, int ticks); extern DECLSPEC int SDLCALL Mix_PlayMusic(Mix_Music *music, int loops); /* Fade in music or a channel over "ms" milliseconds, same semantics as the "Play" functions */ extern DECLSPEC int SDLCALL Mix_FadeInMusic(Mix_Music *music, int loops, int ms); extern DECLSPEC int SDLCALL Mix_FadeInMusicPos(Mix_Music *music, int loops, int ms, double position); #define Mix_FadeInChannel(channel,chunk,loops,ms) Mix_FadeInChannelTimed(channel,chunk,loops,ms,-1) extern DECLSPEC int SDLCALL Mix_FadeInChannelTimed(int channel, Mix_Chunk *chunk, int loops, int ms, int ticks); /* Set the volume in the range of 0-128 of a specific channel or chunk. If the specified channel is -1, set volume for all channels. Returns the original volume. If the specified volume is -1, just return the current volume. */ extern DECLSPEC int SDLCALL Mix_Volume(int channel, int volume); extern DECLSPEC int SDLCALL Mix_VolumeChunk(Mix_Chunk *chunk, int volume); extern DECLSPEC int SDLCALL Mix_VolumeMusic(int volume); /* Halt playing of a particular channel */ extern DECLSPEC int SDLCALL Mix_HaltChannel(int channel); extern DECLSPEC int SDLCALL Mix_HaltGroup(int tag); extern DECLSPEC int SDLCALL Mix_HaltMusic(void); /* Change the expiration delay for a particular channel. The sample will stop playing after the 'ticks' milliseconds have elapsed, or remove the expiration if 'ticks' is -1 */ extern DECLSPEC int SDLCALL Mix_ExpireChannel(int channel, int ticks); /* Halt a channel, fading it out progressively till it's silent The ms parameter indicates the number of milliseconds the fading will take. */ extern DECLSPEC int SDLCALL Mix_FadeOutChannel(int which, int ms); extern DECLSPEC int SDLCALL Mix_FadeOutGroup(int tag, int ms); extern DECLSPEC int SDLCALL Mix_FadeOutMusic(int ms); /* Query the fading status of a channel */ extern DECLSPEC Mix_Fading SDLCALL Mix_FadingMusic(void); extern DECLSPEC Mix_Fading SDLCALL Mix_FadingChannel(int which); /* Pause/Resume a particular channel */ extern DECLSPEC void SDLCALL Mix_Pause(int channel); extern DECLSPEC void SDLCALL Mix_Resume(int channel); extern DECLSPEC int SDLCALL Mix_Paused(int channel); /* Pause/Resume the music stream */ extern DECLSPEC void SDLCALL Mix_PauseMusic(void); extern DECLSPEC void SDLCALL Mix_ResumeMusic(void); extern DECLSPEC void SDLCALL Mix_RewindMusic(void); extern DECLSPEC int SDLCALL Mix_PausedMusic(void); /* Set the current position in the music stream. This returns 0 if successful, or -1 if it failed or isn't implemented. This function is only implemented for MOD music formats (set pattern order number) and for OGG, FLAC, MP3_MAD, and MODPLUG music (set position in seconds), at the moment. */ extern DECLSPEC int SDLCALL Mix_SetMusicPosition(double position); /* Check the status of a specific channel. If the specified channel is -1, check all channels. */ extern DECLSPEC int SDLCALL Mix_Playing(int channel); extern DECLSPEC int SDLCALL Mix_PlayingMusic(void); /* Stop music and set external music playback command */ extern DECLSPEC int SDLCALL Mix_SetMusicCMD(const char *command); /* Synchro value is set by MikMod from modules while playing */ extern DECLSPEC int SDLCALL Mix_SetSynchroValue(int value); extern DECLSPEC int SDLCALL Mix_GetSynchroValue(void); /* Set/Get/Iterate SoundFonts paths to use by supported MIDI backends */ extern DECLSPEC int SDLCALL Mix_SetSoundFonts(const char *paths); extern DECLSPEC const char* SDLCALL Mix_GetSoundFonts(void); extern DECLSPEC int SDLCALL Mix_EachSoundFont(int (*function)(const char*, void*), void *data); /* Get the Mix_Chunk currently associated with a mixer channel Returns NULL if it's an invalid channel, or there's no chunk associated. */ extern DECLSPEC Mix_Chunk * SDLCALL Mix_GetChunk(int channel); /* Close the mixer, halting all playing audio */ extern DECLSPEC void SDLCALL Mix_CloseAudio(void); /* We'll use SDL for reporting errors */ #define Mix_SetError SDL_SetError #define Mix_GetError SDL_GetError /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_MIXER_H */ sauerbraten-0.0.20130203.dfsg/include/SDL_thread.h0000644000175000017500000001022211706600205021134 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 /* 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); #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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_mouse.h0000644000175000017500000001122211706600205021016 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_name.h0000644000175000017500000000026711164573771020634 0ustar vincentvincent #ifndef _SDLname_h_ #define _SDLname_h_ #if defined(__STDC__) || defined(__cplusplus) #define NeedFunctionPrototypes 1 #endif #define SDL_NAME(X) SDL_##X #endif /* _SDLname_h_ */ sauerbraten-0.0.20130203.dfsg/include/SDL_joystick.h0000644000175000017500000001263411706600205021535 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_opengl.h0000644000175000017500000122124011706600205021156 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 #endif #ifndef NO_SDL_GLEXT #define __glext_h_ /* Don't let gl.h include glext.h */ #endif #if defined(__MACOSX__) #include /* Header File For The OpenGL Library */ #include /* Header File For The GLU Library */ #elif defined(__MACOS__) #include /* Header File For The OpenGL Library */ #include /* Header File For The GLU Library */ #else #include /* Header File For The OpenGL Library */ #include /* 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 #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 #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 */ #ifdef __APPLE__ typedef long GLintptr; typedef long GLsizeiptr; #else typedef ptrdiff_t GLintptr; typedef ptrdiff_t GLsizeiptr; #endif #endif #ifndef GL_ARB_vertex_buffer_object /* GL types for handling large vertex buffer objects */ #ifdef __APPLE__ typedef long GLintptrARB; typedef long GLsizeiptrARB; #else typedef ptrdiff_t GLintptrARB; typedef ptrdiff_t GLsizeiptrARB; #endif #endif #ifndef GL_ARB_shader_objects /* GL types for handling shader object handles and program/shader text */ typedef char GLcharARB; /* native character */ #if defined(__APPLE__) typedef void *GLhandleARB; /* shader object handle */ #else typedef unsigned int GLhandleARB; /* shader object handle */ #endif #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 */ /*@}*/ sauerbraten-0.0.20130203.dfsg/include/SDL_syswm.h0000644000175000017500000001425711706600205021063 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 #include #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 /** 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 /** 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 #include /** 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 0 if the function is not implemented, 1 if the function is * implemented and no error occurred, and -1 if the version member of * the 'info' structure is not filled in or not supported. * * 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_audio.h0000644000175000017500000002571711706600205021005 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_keysym.h0000644000175000017500000001650411706600205021217 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_mutex.h0000644000175000017500000001334411706600205021037 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_config.h0000644000175000017500000000270211706600205021136 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_getenv.h0000644000175000017500000000172311706600205021163 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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" sauerbraten-0.0.20130203.dfsg/include/SDL_rwops.h0000644000175000017500000001153611706600205021050 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_video.h0000644000175000017500000011220211706600205020774 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_config_win32.h0000644000175000017500000001073611706600205022166 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_loadso.h0000644000175000017500000000526311706600205021157 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_version.h0000644000175000017500000000511511706600205021357 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 15 /*@}*/ 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_keyboard.h0000644000175000017500000001000211706600205021461 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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] ) //... \ 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 */ sauerbraten-0.0.20130203.dfsg/include/begin_code.h0000644000175000017500000001215611706600205021251 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 # 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 = 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 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_image.h0000644000175000017500000001261111723115741020760 0ustar vincentvincent/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2012 Sam Lantinga 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. */ /* A simple library to load images of various formats as SDL surfaces */ #ifndef _SDL_IMAGE_H #define _SDL_IMAGE_H #include "SDL.h" #include "SDL_version.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL */ #define SDL_IMAGE_MAJOR_VERSION 1 #define SDL_IMAGE_MINOR_VERSION 2 #define SDL_IMAGE_PATCHLEVEL 12 /* This macro can be used to fill a version structure with the compile-time * version of the SDL_image library. */ #define SDL_IMAGE_VERSION(X) \ { \ (X)->major = SDL_IMAGE_MAJOR_VERSION; \ (X)->minor = SDL_IMAGE_MINOR_VERSION; \ (X)->patch = SDL_IMAGE_PATCHLEVEL; \ } /* This function gets the version of the dynamically linked SDL_image library. it should NOT be used to fill a version structure, instead you should use the SDL_IMAGE_VERSION() macro. */ extern DECLSPEC const SDL_version * SDLCALL IMG_Linked_Version(void); typedef enum { IMG_INIT_JPG = 0x00000001, IMG_INIT_PNG = 0x00000002, IMG_INIT_TIF = 0x00000004, IMG_INIT_WEBP = 0x00000008 } IMG_InitFlags; /* Loads dynamic libraries and prepares them for use. Flags should be one or more flags from IMG_InitFlags OR'd together. It returns the flags successfully initialized, or 0 on failure. */ extern DECLSPEC int SDLCALL IMG_Init(int flags); /* Unloads libraries loaded with IMG_Init */ extern DECLSPEC void SDLCALL IMG_Quit(void); /* Load an image from an SDL data source. The 'type' may be one of: "BMP", "GIF", "PNG", etc. If the image format supports a transparent pixel, SDL will set the colorkey for the surface. You can enable RLE acceleration on the surface afterwards by calling: SDL_SetColorKey(image, SDL_RLEACCEL, image->format->colorkey); */ extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadTyped_RW(SDL_RWops *src, int freesrc, char *type); /* Convenience functions */ extern DECLSPEC SDL_Surface * SDLCALL IMG_Load(const char *file); extern DECLSPEC SDL_Surface * SDLCALL IMG_Load_RW(SDL_RWops *src, int freesrc); /* Invert the alpha of a surface for use with OpenGL This function is now a no-op, and only provided for backwards compatibility. */ extern DECLSPEC int SDLCALL IMG_InvertAlpha(int on); /* Functions to detect a file type, given a seekable source */ extern DECLSPEC int SDLCALL IMG_isICO(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isCUR(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isBMP(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isGIF(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isJPG(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isLBM(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isPCX(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isPNG(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isPNM(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isTIF(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isXCF(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isXPM(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isXV(SDL_RWops *src); extern DECLSPEC int SDLCALL IMG_isWEBP(SDL_RWops *src); /* Individual loading functions */ extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadICO_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadCUR_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadBMP_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadGIF_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadJPG_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadLBM_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadPCX_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadPNG_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadPNM_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadTGA_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadTIF_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadXCF_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadXPM_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadXV_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_LoadWEBP_RW(SDL_RWops *src); extern DECLSPEC SDL_Surface * SDLCALL IMG_ReadXPMFromArray(char **xpm); /* We'll use SDL for reporting errors */ #define IMG_SetError SDL_SetError #define IMG_GetError SDL_GetError /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_IMAGE_H */ sauerbraten-0.0.20130203.dfsg/include/SDL_platform.h0000644000175000017500000000522411706600205021517 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_types.h0000644000175000017500000000172311706600205021037 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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" sauerbraten-0.0.20130203.dfsg/include/SDL_stdinc.h0000644000175000017500000004013111706600205021153 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 #endif #ifdef HAVE_STDIO_H #include #endif #if defined(STDC_HEADERS) # include # include # include #else # if defined(HAVE_STDLIB_H) # include # elif defined(HAVE_MALLOC_H) # include # endif # if defined(HAVE_STDDEF_H) # include # endif # if defined(HAVE_STDARG_H) # include # endif #endif #ifdef HAVE_STRING_H # if !defined(STDC_HEADERS) && defined(HAVE_MEMORY_H) # include # endif # include #endif #ifdef HAVE_STRINGS_H # include #endif #if defined(HAVE_INTTYPES_H) # include #elif defined(HAVE_STDINT_H) # include #endif #ifdef HAVE_CTYPE_H # include #endif #if defined(HAVE_ICONV) && defined(HAVE_ICONV_H) # include #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(expression) #define SDL_static_cast(type, expression) static_cast(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 # elif defined(__GNUC__) # define alloca __builtin_alloca # elif defined(_MSC_VER) # include # define alloca _alloca # elif defined(__WATCOMC__) # include # elif defined(__BORLANDC__) # include # elif defined(__DMC__) # include # 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_timer.h0000644000175000017500000001065711706600205021021 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ /*@{*/ /** * 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_error.h0000644000175000017500000000352211706600205021023 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_endian.h0000644000175000017500000001364211706600205021134 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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? */ #ifdef __linux__ #include #define SDL_BYTEORDER __BYTE_ORDER #else /* __linux __ */ #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 /* __linux __ */ #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(__m68k__) && !defined(__mcoldfire__)) 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 SDL_static_cast(Uint16, ((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(__m68k__) && !defined(__mcoldfire__)) 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 SDL_static_cast(Uint32, ((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 */ sauerbraten-0.0.20130203.dfsg/include/SDL_byteorder.h0000644000175000017500000000173211706600205021672 0ustar vincentvincent/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 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" sauerbraten-0.0.20130203.dfsg/fpsgame/0000755000175000017500000000000012100771027017014 5ustar vincentvincentsauerbraten-0.0.20130203.dfsg/fpsgame/entities.cpp0000644000175000017500000005623412074623667021376 0ustar vincentvincent#include "game.h" namespace entities { using namespace game; int extraentinfosize() { return 0; } // size in bytes of what the 2 methods below read/write... so it can be skipped by other games void writeent(entity &e, char *buf) // write any additional data to disk (except for ET_ ents) { } void readent(entity &e, char *buf, int ver) // read from disk, and init { if(ver <= 30) switch(e.type) { case FLAG: case MONSTER: case TELEDEST: case RESPAWNPOINT: case BOX: case BARREL: case PLATFORM: case ELEVATOR: e.attr1 = (int(e.attr1)+180)%360; break; } if(ver <= 31) switch(e.type) { case BOX: case BARREL: case PLATFORM: case ELEVATOR: int yaw = (int(e.attr1)%360 + 360)%360 + 7; e.attr1 = yaw - yaw%15; break; } } #ifndef STANDALONE vector ents; vector &getents() { return ents; } bool mayattach(extentity &e) { return false; } bool attachent(extentity &e, extentity &a) { return false; } const char *itemname(int i) { int t = ents[i]->type; if(tI_QUAD) return NULL; return itemstats[t-I_SHELLS].name; } int itemicon(int i) { int t = ents[i]->type; if(tI_QUAD) return -1; return itemstats[t-I_SHELLS].icon; } const char *entmdlname(int type) { static const char *entmdlnames[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "ammo/shells", "ammo/bullets", "ammo/rockets", "ammo/rrounds", "ammo/grenades", "ammo/cartridges", "health", "boost", "armor/green", "armor/yellow", "quad", "teleporter", NULL, NULL, "carrot", NULL, NULL, "checkpoint", NULL, NULL, NULL, NULL, NULL }; return entmdlnames[type]; } const char *entmodel(const entity &e) { if(e.type == TELEPORT) { if(e.attr2 > 0) return mapmodelname(e.attr2); if(e.attr2 < 0) return NULL; } return e.type < MAXENTTYPES ? entmdlname(e.type) : NULL; } void preloadentities() { loopi(MAXENTTYPES) { switch(i) { case I_SHELLS: case I_BULLETS: case I_ROCKETS: case I_ROUNDS: case I_GRENADES: case I_CARTRIDGES: if(m_noammo) continue; break; case I_HEALTH: case I_BOOST: case I_GREENARMOUR: case I_YELLOWARMOUR: case I_QUAD: if(m_noitems) continue; break; case CARROT: case RESPAWNPOINT: if(!m_classicsp) continue; break; } const char *mdl = entmdlname(i); if(!mdl) continue; preloadmodel(mdl); } loopv(ents) { extentity &e = *ents[i]; switch(e.type) { case TELEPORT: if(e.attr2 > 0) preloadmodel(mapmodelname(e.attr2)); case JUMPPAD: if(e.attr4 > 0) preloadmapsound(e.attr4); break; } } } void renderentities() { loopv(ents) { extentity &e = *ents[i]; int revs = 10; switch(e.type) { case CARROT: case RESPAWNPOINT: if(e.attr2) revs = 1; break; case TELEPORT: if(e.attr2 < 0) continue; break; default: if(!e.spawned || e.type < I_SHELLS || e.type > I_QUAD) continue; } const char *mdlname = entmodel(e); if(mdlname) { vec p = e.o; p.z += 1+sinf(lastmillis/100.0+e.o.x+e.o.y)/20; rendermodel(&e.light, mdlname, ANIM_MAPMODEL|ANIM_LOOP, p, lastmillis/(float)revs, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_DIST | MDL_CULL_OCCLUDED); } } } void addammo(int type, int &v, bool local) { itemstat &is = itemstats[type-I_SHELLS]; v += is.add; if(v>is.max) v = is.max; if(local) msgsound(is.sound); } void repammo(fpsent *d, int type, bool local) { addammo(type, d->ammo[type-I_SHELLS+GUN_SG], local); } // these two functions are called when the server acknowledges that you really // picked up the item (in multiplayer someone may grab it before you). void pickupeffects(int n, fpsent *d) { if(!ents.inrange(n)) return; int type = ents[n]->type; if(typeI_QUAD) return; ents[n]->spawned = false; if(!d) return; itemstat &is = itemstats[type-I_SHELLS]; if(d!=player1 || isthirdperson()) { //particle_text(d->abovehead(), is.name, PART_TEXT, 2000, 0xFFC864, 4.0f, -8); particle_icon(d->abovehead(), is.icon%4, is.icon/4, PART_HUD_ICON_GREY, 2000, 0xFFFFFF, 2.0f, -8); } playsound(itemstats[type-I_SHELLS].sound, d!=player1 ? &d->o : NULL, NULL, 0, 0, 0, -1, 0, 1500); d->pickup(type); if(d==player1) switch(type) { case I_BOOST: conoutf(CON_GAMEINFO, "\f2you have a permanent +10 health bonus! (%d)", d->maxhealth); playsound(S_V_BOOST, NULL, NULL, 0, 0, 0, -1, 0, 3000); break; case I_QUAD: conoutf(CON_GAMEINFO, "\f2you got the quad!"); playsound(S_V_QUAD, NULL, NULL, 0, 0, 0, -1, 0, 3000); break; } } // these functions are called when the client touches the item void teleporteffects(fpsent *d, int tp, int td, bool local) { if(ents.inrange(tp) && ents[tp]->type == TELEPORT) { extentity &e = *ents[tp]; if(e.attr4 >= 0) { int snd = S_TELEPORT, flags = 0; if(e.attr4 > 0) { snd = e.attr4; flags = SND_MAP; } if(d == player1) playsound(snd, NULL, NULL, flags); else { playsound(snd, &e.o, NULL, flags); if(ents.inrange(td) && ents[td]->type == TELEDEST) playsound(snd, &ents[td]->o, NULL, flags); } } } if(local && d->clientnum >= 0) { sendposition(d); packetbuf p(32, ENET_PACKET_FLAG_RELIABLE); putint(p, N_TELEPORT); putint(p, d->clientnum); putint(p, tp); putint(p, td); sendclientpacket(p.finalize(), 0); flushclient(); } } void jumppadeffects(fpsent *d, int jp, bool local) { if(ents.inrange(jp) && ents[jp]->type == JUMPPAD) { extentity &e = *ents[jp]; if(e.attr4 >= 0) { int snd = S_JUMPPAD, flags = 0; if(e.attr4 > 0) { snd = e.attr4; flags = SND_MAP; } if(d == player1) playsound(snd, NULL, NULL, flags); else playsound(snd, &e.o, NULL, flags); } } if(local && d->clientnum >= 0) { sendposition(d); packetbuf p(16, ENET_PACKET_FLAG_RELIABLE); putint(p, N_JUMPPAD); putint(p, d->clientnum); putint(p, jp); sendclientpacket(p.finalize(), 0); flushclient(); } } void teleport(int n, fpsent *d) // also used by monsters { int e = -1, tag = ents[n]->attr1, beenhere = -1; for(;;) { e = findentity(TELEDEST, e+1); if(e==beenhere || e<0) { conoutf(CON_WARN, "no teleport destination for tag %d", tag); return; } if(beenhere<0) beenhere = e; if(ents[e]->attr2==tag) { teleporteffects(d, n, e, true); d->o = ents[e]->o; d->yaw = ents[e]->attr1; if(ents[e]->attr3 > 0) { vec dir; vecfromyawpitch(d->yaw, 0, 1, 0, dir); float speed = d->vel.magnitude2(); d->vel.x = dir.x*speed; d->vel.y = dir.y*speed; } else d->vel = vec(0, 0, 0); entinmap(d); updatedynentcache(d); ai::inferwaypoints(d, ents[n]->o, ents[e]->o, 16.f); break; } } } void trypickup(int n, fpsent *d) { switch(ents[n]->type) { default: if(d->canpickup(ents[n]->type)) { addmsg(N_ITEMPICKUP, "rci", d, n); ents[n]->spawned = false; // even if someone else gets it first } break; case TELEPORT: { if(d->lastpickup==ents[n]->type && lastmillis-d->lastpickupmillis<500) break; if(ents[n]->attr3 > 0) { defformatstring(hookname)("can_teleport_%d", ents[n]->attr3); if(identexists(hookname) && !execute(hookname)) break; } d->lastpickup = ents[n]->type; d->lastpickupmillis = lastmillis; teleport(n, d); break; } case RESPAWNPOINT: if(d!=player1) break; if(n==respawnent) break; respawnent = n; conoutf(CON_GAMEINFO, "\f2respawn point set!"); playsound(S_V_RESPAWNPOINT); break; case JUMPPAD: { if(d->lastpickup==ents[n]->type && lastmillis-d->lastpickupmillis<300) break; d->lastpickup = ents[n]->type; d->lastpickupmillis = lastmillis; jumppadeffects(d, n, true); vec v((int)(char)ents[n]->attr3*10.0f, (int)(char)ents[n]->attr2*10.0f, ents[n]->attr1*12.5f); if(d->ai) d->ai->becareful = true; d->falling = vec(0, 0, 0); d->physstate = PHYS_FALL; d->timeinair = 1; d->vel = v; break; } } } void checkitems(fpsent *d) { if(d->state!=CS_ALIVE) return; vec o = d->feetpos(); loopv(ents) { extentity &e = *ents[i]; if(e.type==NOTUSED) continue; if(!e.spawned && e.type!=TELEPORT && e.type!=JUMPPAD && e.type!=RESPAWNPOINT) continue; float dist = e.o.dist(o); if(dist<(e.type==TELEPORT ? 16 : 12)) trypickup(i, d); } } void checkquad(int time, fpsent *d) { if(d->quadmillis && (d->quadmillis -= time)<=0) { d->quadmillis = 0; playsound(S_PUPOUT, d==player1 ? NULL : &d->o); if(d==player1) conoutf(CON_GAMEINFO, "\f2quad damage is over"); } } void putitems(packetbuf &p) // puts items in network stream and also spawns them locally { putint(p, N_ITEMLIST); loopv(ents) if(ents[i]->type>=I_SHELLS && ents[i]->type<=I_QUAD && (!m_noammo || ents[i]->typetype>I_CARTRIDGES)) { putint(p, i); putint(p, ents[i]->type); } putint(p, -1); } void resetspawns() { loopv(ents) ents[i]->spawned = false; } void spawnitems(bool force) { if(m_noitems) return; loopv(ents) if(ents[i]->type>=I_SHELLS && ents[i]->type<=I_QUAD && (!m_noammo || ents[i]->typetype>I_CARTRIDGES)) { ents[i]->spawned = force || m_sp || !server::delayspawn(ents[i]->type); } } void setspawn(int i, bool on) { if(ents.inrange(i)) ents[i]->spawned = on; } extentity *newentity() { return new fpsentity(); } void deleteentity(extentity *e) { delete (fpsentity *)e; } void clearents() { while(ents.length()) deleteentity(ents.pop()); } enum { TRIG_COLLIDE = 1<<0, TRIG_TOGGLE = 1<<1, TRIG_ONCE = 0<<2, TRIG_MANY = 1<<2, TRIG_DISAPPEAR = 1<<3, TRIG_AUTO_RESET = 1<<4, TRIG_RUMBLE = 1<<5, TRIG_LOCKED = 1<<6, TRIG_ENDSP = 1<<7 }; static const int NUMTRIGGERTYPES = 32; static const int triggertypes[NUMTRIGGERTYPES] = { -1, TRIG_ONCE, // 1 TRIG_RUMBLE, // 2 TRIG_TOGGLE, // 3 TRIG_TOGGLE | TRIG_RUMBLE, // 4 TRIG_MANY, // 5 TRIG_MANY | TRIG_RUMBLE, // 6 TRIG_MANY | TRIG_TOGGLE, // 7 TRIG_MANY | TRIG_TOGGLE | TRIG_RUMBLE, // 8 TRIG_COLLIDE | TRIG_TOGGLE | TRIG_RUMBLE, // 9 TRIG_COLLIDE | TRIG_TOGGLE | TRIG_AUTO_RESET | TRIG_RUMBLE, // 10 TRIG_COLLIDE | TRIG_TOGGLE | TRIG_LOCKED | TRIG_RUMBLE, // 11 TRIG_DISAPPEAR, // 12 TRIG_DISAPPEAR | TRIG_RUMBLE, // 13 TRIG_DISAPPEAR | TRIG_COLLIDE | TRIG_LOCKED, // 14 -1 /* reserved 15 */, -1 /* reserved 16 */, -1 /* reserved 17 */, -1 /* reserved 18 */, -1 /* reserved 19 */, -1 /* reserved 20 */, -1 /* reserved 21 */, -1 /* reserved 22 */, -1 /* reserved 23 */, -1 /* reserved 24 */, -1 /* reserved 25 */, -1 /* reserved 26 */, -1 /* reserved 27 */, -1 /* reserved 28 */, TRIG_DISAPPEAR | TRIG_RUMBLE | TRIG_ENDSP, // 29 -1 /* reserved 30 */, -1 /* reserved 31 */, }; #define validtrigger(type) (triggertypes[(type) & (NUMTRIGGERTYPES-1)]>=0) #define checktriggertype(type, flag) (triggertypes[(type) & (NUMTRIGGERTYPES-1)] & (flag)) static inline void setuptriggerflags(fpsentity &e) { e.flags = extentity::F_ANIM; if(checktriggertype(e.attr3, TRIG_COLLIDE|TRIG_DISAPPEAR)) e.flags |= extentity::F_NOSHADOW; if(!checktriggertype(e.attr3, TRIG_COLLIDE)) e.flags |= extentity::F_NOCOLLIDE; switch(e.triggerstate) { case TRIGGERING: if(checktriggertype(e.attr3, TRIG_COLLIDE) && lastmillis-e.lasttrigger >= 500) e.flags |= extentity::F_NOCOLLIDE; break; case TRIGGERED: if(checktriggertype(e.attr3, TRIG_COLLIDE)) e.flags |= extentity::F_NOCOLLIDE; break; case TRIGGER_DISAPPEARED: e.flags |= extentity::F_NOVIS | extentity::F_NOCOLLIDE; break; } } void resettriggers() { loopv(ents) { fpsentity &e = *(fpsentity *)ents[i]; if(e.type != ET_MAPMODEL || !validtrigger(e.attr3)) continue; e.triggerstate = TRIGGER_RESET; e.lasttrigger = 0; setuptriggerflags(e); } } void unlocktriggers(int tag, int oldstate = TRIGGER_RESET, int newstate = TRIGGERING) { loopv(ents) { fpsentity &e = *(fpsentity *)ents[i]; if(e.type != ET_MAPMODEL || !validtrigger(e.attr3)) continue; if(e.attr4 == tag && e.triggerstate == oldstate && checktriggertype(e.attr3, TRIG_LOCKED)) { if(newstate == TRIGGER_RESETTING && checktriggertype(e.attr3, TRIG_COLLIDE) && overlapsdynent(e.o, 20)) continue; e.triggerstate = newstate; e.lasttrigger = lastmillis; if(checktriggertype(e.attr3, TRIG_RUMBLE)) playsound(S_RUMBLE, &e.o); } } } ICOMMAND(trigger, "ii", (int *tag, int *state), { if(*state) unlocktriggers(*tag); else unlocktriggers(*tag, TRIGGERED, TRIGGER_RESETTING); }); VAR(triggerstate, -1, 0, 1); void doleveltrigger(int trigger, int state) { defformatstring(aliasname)("level_trigger_%d", trigger); if(identexists(aliasname)) { triggerstate = state; execute(aliasname); } } void checktriggers() { if(player1->state != CS_ALIVE) return; vec o = player1->feetpos(); loopv(ents) { fpsentity &e = *(fpsentity *)ents[i]; if(e.type != ET_MAPMODEL || !validtrigger(e.attr3)) continue; switch(e.triggerstate) { case TRIGGERING: case TRIGGER_RESETTING: if(lastmillis-e.lasttrigger>=1000) { if(e.attr4) { if(e.triggerstate == TRIGGERING) unlocktriggers(e.attr4); else unlocktriggers(e.attr4, TRIGGERED, TRIGGER_RESETTING); } if(checktriggertype(e.attr3, TRIG_DISAPPEAR)) e.triggerstate = TRIGGER_DISAPPEARED; else if(e.triggerstate==TRIGGERING && checktriggertype(e.attr3, TRIG_TOGGLE)) e.triggerstate = TRIGGERED; else e.triggerstate = TRIGGER_RESET; } setuptriggerflags(e); break; case TRIGGER_RESET: if(e.lasttrigger) { if(checktriggertype(e.attr3, TRIG_AUTO_RESET|TRIG_MANY|TRIG_LOCKED) && e.o.dist(o)-player1->radius>=(checktriggertype(e.attr3, TRIG_COLLIDE) ? 20 : 12)) e.lasttrigger = 0; break; } else if(e.o.dist(o)-player1->radius>=(checktriggertype(e.attr3, TRIG_COLLIDE) ? 20 : 12)) break; else if(checktriggertype(e.attr3, TRIG_LOCKED)) { if(!e.attr4) break; doleveltrigger(e.attr4, -1); e.lasttrigger = lastmillis; break; } e.triggerstate = TRIGGERING; e.lasttrigger = lastmillis; setuptriggerflags(e); if(checktriggertype(e.attr3, TRIG_RUMBLE)) playsound(S_RUMBLE, &e.o); if(checktriggertype(e.attr3, TRIG_ENDSP)) endsp(false); if(e.attr4) doleveltrigger(e.attr4, 1); break; case TRIGGERED: if(e.o.dist(o)-player1->radius<(checktriggertype(e.attr3, TRIG_COLLIDE) ? 20 : 12)) { if(e.lasttrigger) break; } else if(checktriggertype(e.attr3, TRIG_AUTO_RESET)) { if(lastmillis-e.lasttrigger<6000) break; } else if(checktriggertype(e.attr3, TRIG_MANY)) { e.lasttrigger = 0; break; } else break; if(checktriggertype(e.attr3, TRIG_COLLIDE) && overlapsdynent(e.o, 20)) break; e.triggerstate = TRIGGER_RESETTING; e.lasttrigger = lastmillis; setuptriggerflags(e); if(checktriggertype(e.attr3, TRIG_RUMBLE)) playsound(S_RUMBLE, &e.o); if(checktriggertype(e.attr3, TRIG_ENDSP)) endsp(false); if(e.attr4) doleveltrigger(e.attr4, 0); break; } } } void animatemapmodel(const extentity &e, int &anim, int &basetime) { const fpsentity &f = (const fpsentity &)e; if(validtrigger(f.attr3)) switch(f.triggerstate) { case TRIGGER_RESET: anim = ANIM_TRIGGER|ANIM_START; break; case TRIGGERING: anim = ANIM_TRIGGER; basetime = f.lasttrigger; break; case TRIGGERED: anim = ANIM_TRIGGER|ANIM_END; break; case TRIGGER_RESETTING: anim = ANIM_TRIGGER|ANIM_REVERSE; basetime = f.lasttrigger; break; } } void fixentity(extentity &e) { switch(e.type) { case FLAG: case BOX: case BARREL: case PLATFORM: case ELEVATOR: e.attr5 = e.attr4; e.attr4 = e.attr3; case TELEDEST: e.attr3 = e.attr2; case MONSTER: e.attr2 = e.attr1; case RESPAWNPOINT: e.attr1 = (int)player1->yaw; break; } } void entradius(extentity &e, bool color) { switch(e.type) { case TELEPORT: loopv(ents) if(ents[i]->type == TELEDEST && e.attr1==ents[i]->attr2) { renderentarrow(e, vec(ents[i]->o).sub(e.o).normalize(), e.o.dist(ents[i]->o)); break; } break; case JUMPPAD: renderentarrow(e, vec((int)(char)e.attr3*10.0f, (int)(char)e.attr2*10.0f, e.attr1*12.5f).normalize(), 4); break; case FLAG: case MONSTER: case TELEDEST: case RESPAWNPOINT: case BOX: case BARREL: case PLATFORM: case ELEVATOR: { vec dir; vecfromyawpitch(e.attr1, 0, 1, 0, dir); renderentarrow(e, dir, 4); break; } case MAPMODEL: if(validtrigger(e.attr3)) renderentring(e, checktriggertype(e.attr3, TRIG_COLLIDE) ? 20 : 12); break; } } bool printent(extentity &e, char *buf) { return false; } const char *entnameinfo(entity &e) { return ""; } const char *entname(int i) { static const char *entnames[] = { "none?", "light", "mapmodel", "playerstart", "envmap", "particles", "sound", "spotlight", "shells", "bullets", "rockets", "riflerounds", "grenades", "cartridges", "health", "healthboost", "greenarmour", "yellowarmour", "quaddamage", "teleport", "teledest", "monster", "carrot", "jumppad", "base", "respawnpoint", "box", "barrel", "platform", "elevator", "flag", "", "", "", "", }; return i>=0 && size_t(i) hits; VARP(maxdebris, 10, 25, 1000); VARP(maxbarreldebris, 5, 10, 1000); ICOMMAND(getweapon, "", (), intret(player1->gunselect)); void gunselect(int gun, fpsent *d) { if(gun!=d->gunselect) { addmsg(N_GUNSELECT, "rci", d, gun); playsound(S_WEAPLOAD, &d->o); } d->gunselect = gun; } void nextweapon(int dir, bool force = false) { if(player1->state!=CS_ALIVE) return; dir = (dir < 0 ? NUMGUNS-1 : 1); int gun = player1->gunselect; loopi(NUMGUNS) { gun = (gun + dir)%NUMGUNS; if(force || player1->ammo[gun]) break; } if(gun != player1->gunselect) gunselect(gun, player1); else playsound(S_NOAMMO); } ICOMMAND(nextweapon, "ii", (int *dir, int *force), nextweapon(*dir, *force!=0)); int getweapon(const char *name) { const char *abbrevs[] = { "FI", "SG", "CG", "RL", "RI", "GL", "PI" }; if(isdigit(name[0])) return parseint(name); else loopi(sizeof(abbrevs)/sizeof(abbrevs[0])) if(!strcasecmp(abbrevs[i], name)) return i; return -1; } void setweapon(const char *name, bool force = false) { int gun = getweapon(name); if(player1->state!=CS_ALIVE || gunGUN_PISTOL) return; if(force || player1->ammo[gun]) gunselect(gun, player1); else playsound(S_NOAMMO); } ICOMMAND(setweapon, "si", (char *name, int *force), setweapon(name, *force!=0)); void cycleweapon(int numguns, int *guns, bool force = false) { if(numguns<=0 || player1->state!=CS_ALIVE) return; int offset = 0; loopi(numguns) if(guns[i] == player1->gunselect) { offset = i+1; break; } loopi(numguns) { int gun = guns[(i+offset)%numguns]; if(gun>=0 && gunammo[gun])) { gunselect(gun, player1); return; } } playsound(S_NOAMMO); } ICOMMAND(cycleweapon, "V", (tagval *args, int numargs), { int numguns = min(numargs, 7); int guns[7]; loopi(numguns) guns[i] = getweapon(args[i].getstr()); cycleweapon(numguns, guns); }); void weaponswitch(fpsent *d) { if(d->state!=CS_ALIVE) return; int s = d->gunselect; if (s!=GUN_CG && d->ammo[GUN_CG]) s = GUN_CG; else if(s!=GUN_RL && d->ammo[GUN_RL]) s = GUN_RL; else if(s!=GUN_SG && d->ammo[GUN_SG]) s = GUN_SG; else if(s!=GUN_RIFLE && d->ammo[GUN_RIFLE]) s = GUN_RIFLE; else if(s!=GUN_GL && d->ammo[GUN_GL]) s = GUN_GL; else if(s!=GUN_PISTOL && d->ammo[GUN_PISTOL]) s = GUN_PISTOL; else s = GUN_FIST; gunselect(s, d); } ICOMMAND(weapon, "V", (tagval *args, int numargs), { if(player1->state!=CS_ALIVE) return; loopi(7) { const char *name = i < numargs ? args[i].getstr() : ""; if(name[0]) { int gun = getweapon(name); if(gun >= GUN_FIST && gun <= GUN_PISTOL && gun != player1->gunselect && player1->ammo[gun]) { gunselect(gun, player1); return; } } else { weaponswitch(player1); return; } } playsound(S_NOAMMO); }); void offsetray(const vec &from, const vec &to, int spread, float range, vec &dest) { vec offset; do offset = vec(rndscale(1), rndscale(1), rndscale(1)).sub(0.5f); while(offset.squaredlen() > 0.5f*0.5f); offset.mul((to.dist(from)/1024)*spread); offset.z /= 2; dest = vec(offset).add(to); vec dir = vec(dest).sub(from).normalize(); raycubepos(from, dir, dest, range, RAY_CLIPMAT|RAY_ALPHAPOLY); } void createrays(int gun, const vec &from, const vec &to) // create random spread of rays { loopi(guns[gun].rays) offsetray(from, to, guns[gun].spread, guns[gun].range, rays[i]); } enum { BNC_GRENADE, BNC_GIBS, BNC_DEBRIS, BNC_BARRELDEBRIS }; struct bouncer : physent { int lifetime, bounces; float lastyaw, roll; bool local; fpsent *owner; int bouncetype, variant; vec offset; int offsetmillis; int id; entitylight light; bouncer() : bounces(0), roll(0), variant(0) { type = ENT_BOUNCE; collidetype = COLLIDE_AABB; } }; vector bouncers; vec hudgunorigin(int gun, const vec &from, const vec &to, fpsent *d); void newbouncer(const vec &from, const vec &to, bool local, int id, fpsent *owner, int type, int lifetime, int speed, entitylight *light = NULL) { bouncer &bnc = *bouncers.add(new bouncer); bnc.o = from; bnc.radius = bnc.xradius = bnc.yradius = type==BNC_DEBRIS ? 0.5f : 1.5f; bnc.eyeheight = bnc.radius; bnc.aboveeye = bnc.radius; bnc.lifetime = lifetime; bnc.local = local; bnc.owner = owner; bnc.bouncetype = type; bnc.id = local ? lastmillis : id; if(light) bnc.light = *light; switch(type) { case BNC_GRENADE: bnc.collidetype = COLLIDE_ELLIPSE; break; case BNC_DEBRIS: case BNC_BARRELDEBRIS: bnc.variant = rnd(4); break; case BNC_GIBS: bnc.variant = rnd(3); break; } vec dir(to); dir.sub(from).normalize(); bnc.vel = dir; bnc.vel.mul(speed); avoidcollision(&bnc, dir, owner, 0.1f); if(type==BNC_GRENADE) { bnc.offset = hudgunorigin(GUN_GL, from, to, owner); if(owner==hudplayer() && !isthirdperson()) bnc.offset.sub(owner->o).rescale(16).add(owner->o); } else bnc.offset = from; bnc.offset.sub(bnc.o); bnc.offsetmillis = OFFSETMILLIS; bnc.resetinterp(); } void bounced(physent *d, const vec &surface) { if(d->type != ENT_BOUNCE) return; bouncer *b = (bouncer *)d; if(b->bouncetype != BNC_GIBS || b->bounces >= 2) return; b->bounces++; adddecal(DECAL_BLOOD, vec(b->o).sub(vec(surface).mul(b->radius)), surface, 2.96f/b->bounces, bvec(0x60, 0xFF, 0xFF), rnd(4)); } void updatebouncers(int time) { loopv(bouncers) { bouncer &bnc = *bouncers[i]; if(bnc.bouncetype==BNC_GRENADE && bnc.vel.magnitude() > 50.0f) { vec pos(bnc.o); pos.add(vec(bnc.offset).mul(bnc.offsetmillis/float(OFFSETMILLIS))); regular_particle_splash(PART_SMOKE, 1, 150, pos, 0x404040, 2.4f, 50, -20); } vec old(bnc.o); bool stopped = false; if(bnc.bouncetype==BNC_GRENADE) stopped = bounce(&bnc, 0.6f, 0.5f, 0.8f) || (bnc.lifetime -= time)<0; else { // cheaper variable rate physics for debris, gibs, etc. for(int rtime = time; rtime > 0;) { int qtime = min(30, rtime); rtime -= qtime; if((bnc.lifetime -= qtime)<0 || bounce(&bnc, qtime/1000.0f, 0.6f, 0.5f, 1)) { stopped = true; break; } } } if(stopped) { if(bnc.bouncetype==BNC_GRENADE) { int qdam = guns[GUN_GL].damage*(bnc.owner->quadmillis ? 4 : 1); hits.setsize(0); explode(bnc.local, bnc.owner, bnc.o, NULL, qdam, GUN_GL); adddecal(DECAL_SCORCH, bnc.o, vec(0, 0, 1), guns[GUN_GL].exprad/2); if(bnc.local) addmsg(N_EXPLODE, "rci3iv", bnc.owner, lastmillis-maptime, GUN_GL, bnc.id-maptime, hits.length(), hits.length()*sizeof(hitmsg)/sizeof(int), hits.getbuf()); } delete bouncers.remove(i--); } else { bnc.roll += old.sub(bnc.o).magnitude()/(4*RAD); bnc.offsetmillis = max(bnc.offsetmillis-time, 0); } } } void removebouncers(fpsent *owner) { loopv(bouncers) if(bouncers[i]->owner==owner) { delete bouncers[i]; bouncers.remove(i--); } } void clearbouncers() { bouncers.deletecontents(); } struct projectile { vec dir, o, to, offset; float speed; fpsent *owner; int gun; bool local; int offsetmillis; int id; entitylight light; }; vector projs; void clearprojectiles() { projs.shrink(0); } void newprojectile(const vec &from, const vec &to, float speed, bool local, int id, fpsent *owner, int gun) { projectile &p = projs.add(); p.dir = vec(to).sub(from).normalize(); p.o = from; p.to = to; p.offset = hudgunorigin(gun, from, to, owner); p.offset.sub(from); p.speed = speed; p.local = local; p.owner = owner; p.gun = gun; p.offsetmillis = OFFSETMILLIS; p.id = local ? lastmillis : id; } void removeprojectiles(fpsent *owner) { // can't use loopv here due to strange GCC optimizer bug int len = projs.length(); loopi(len) if(projs[i].owner==owner) { projs.remove(i--); len--; } } VARP(blood, 0, 1, 1); void damageeffect(int damage, fpsent *d, bool thirdperson) { vec p = d->o; p.z += 0.6f*(d->eyeheight + d->aboveeye) - d->eyeheight; if(blood) particle_splash(PART_BLOOD, damage/10, 1000, p, 0x60FFFF, 2.96f); if(thirdperson) { defformatstring(ds)("%d", damage); particle_textcopy(d->abovehead(), ds, PART_TEXT, 2000, 0xFF4B19, 4.0f, -8); } } void spawnbouncer(const vec &p, const vec &vel, fpsent *d, int type, entitylight *light = NULL) { vec to(rnd(100)-50, rnd(100)-50, rnd(100)-50); if(to.iszero()) to.z += 1; to.normalize(); to.add(p); newbouncer(p, to, true, 0, d, type, rnd(1000)+1000, rnd(100)+20, light); } void gibeffect(int damage, const vec &vel, fpsent *d) { if(!blood || damage <= 0) return; vec from = d->abovehead(); loopi(min(damage/25, 40)+1) spawnbouncer(from, vel, d, BNC_GIBS); } void hit(int damage, dynent *d, fpsent *at, const vec &vel, int gun, float info1, int info2 = 1) { if(at==player1 && d!=at) { extern int hitsound; if(hitsound && lasthit != lastmillis) playsound(S_HIT); lasthit = lastmillis; } if(d->type==ENT_INANIMATE) { hitmovable(damage, (movable *)d, at, vel, gun); return; } fpsent *f = (fpsent *)d; f->lastpain = lastmillis; if(at->type==ENT_PLAYER && !isteam(at->team, f->team)) at->totaldamage += damage; if(f->type==ENT_AI || !m_mp(gamemode) || f==at) f->hitpush(damage, vel, at, gun); if(f->type==ENT_AI) hitmonster(damage, (monster *)f, at, vel, gun); else if(!m_mp(gamemode)) damaged(damage, f, at); else { hitmsg &h = hits.add(); h.target = f->clientnum; h.lifesequence = f->lifesequence; h.info1 = int(info1*DMF); h.info2 = info2; h.dir = f==at ? ivec(0, 0, 0) : ivec(int(vel.x*DNF), int(vel.y*DNF), int(vel.z*DNF)); if(at==player1) { damageeffect(damage, f); if(f==player1) { damageblend(damage); damagecompass(damage, at ? at->o : f->o); playsound(S_PAIN6); } else playsound(S_PAIN1+rnd(5), &f->o); } } } void hitpush(int damage, dynent *d, fpsent *at, vec &from, vec &to, int gun, int rays) { hit(damage, d, at, vec(to).sub(from).normalize(), gun, from.dist(to), rays); } float projdist(dynent *o, vec &dir, const vec &v) { vec middle = o->o; middle.z += (o->aboveeye-o->eyeheight)/2; float dist = middle.dist(v, dir); dir.div(dist); if(dist<0) dist = 0; return dist; } void radialeffect(dynent *o, const vec &v, int qdam, fpsent *at, int gun) { if(o->state!=CS_ALIVE) return; vec dir; float dist = projdist(o, dir, v); if(disto==v ? vec(0, 0, 0) : vec(owner->o).sub(v).normalize(), debrisorigin(v); if(gun==GUN_RL) debrisorigin.add(vec(debrisvel).mul(8)); if(numdebris) { entitylight light; lightreaching(debrisorigin, light.color, light.dir); loopi(numdebris) spawnbouncer(debrisorigin, debrisvel, owner, gun==GUN_BARREL ? BNC_BARRELDEBRIS : BNC_DEBRIS, &light); } if(!local) return; loopi(numdynents()) { dynent *o = iterdynents(i); if(o==safe) continue; radialeffect(o, v, damage, owner, gun); } } void projsplash(projectile &p, vec &v, dynent *safe, int damage) { if(guns[p.gun].part) { particle_splash(PART_SPARK, 100, 200, v, 0xB49B4B, 0.24f); playsound(S_FEXPLODE, &v); // no push? } else { explode(p.local, p.owner, v, safe, damage, GUN_RL); adddecal(DECAL_SCORCH, v, vec(p.dir).neg(), guns[p.gun].exprad/2); } } void explodeeffects(int gun, fpsent *d, bool local, int id) { if(local) return; switch(gun) { case GUN_RL: loopv(projs) { projectile &p = projs[i]; if(p.gun == gun && p.owner == d && p.id == id && !p.local) { vec pos(p.o); pos.add(vec(p.offset).mul(p.offsetmillis/float(OFFSETMILLIS))); explode(p.local, p.owner, pos, NULL, 0, GUN_RL); adddecal(DECAL_SCORCH, pos, vec(p.dir).neg(), guns[gun].exprad/2); projs.remove(i); break; } } break; case GUN_GL: loopv(bouncers) { bouncer &b = *bouncers[i]; if(b.bouncetype == BNC_GRENADE && b.owner == d && b.id == id && !b.local) { vec pos(b.o); pos.add(vec(b.offset).mul(b.offsetmillis/float(OFFSETMILLIS))); explode(b.local, b.owner, pos, NULL, 0, GUN_GL); adddecal(DECAL_SCORCH, pos, vec(0, 0, 1), guns[gun].exprad/2); delete bouncers.remove(i); break; } } break; default: break; } } bool projdamage(dynent *o, projectile &p, vec &v, int qdam) { if(o->state!=CS_ALIVE) return false; if(!intersect(o, p.o, v)) return false; projsplash(p, v, o, qdam); vec dir; projdist(o, dir, v); hit(qdam, o, p.owner, dir, p.gun, 0); return true; } void updateprojectiles(int time) { loopv(projs) { projectile &p = projs[i]; p.offsetmillis = max(p.offsetmillis-time, 0); int qdam = guns[p.gun].damage*(p.owner->quadmillis ? 4 : 1); if(p.owner->type==ENT_AI) qdam /= MONSTERDAMAGEFACTOR; vec v; float dist = p.to.dist(p.o, v); float dtime = dist*1000/p.speed; if(time > dtime) dtime = time; v.mul(time/dtime); v.add(p.o); bool exploded = false; hits.setsize(0); if(p.local) { loopj(numdynents()) { dynent *o = iterdynents(j); if(p.owner==o || o->o.reject(v, 10.0f)) continue; if(projdamage(o, p, v, qdam)) { exploded = true; break; } } } if(!exploded) { if(dist<4) { if(p.o!=p.to) // if original target was moving, reevaluate endpoint { if(raycubepos(p.o, p.dir, p.to, 0, RAY_CLIPMAT|RAY_ALPHAPOLY)>=4) continue; } projsplash(p, v, NULL, qdam); exploded = true; } else { vec pos(v); pos.add(vec(p.offset).mul(p.offsetmillis/float(OFFSETMILLIS))); if(guns[p.gun].part) { regular_particle_splash(PART_SMOKE, 2, 300, pos, 0x404040, 0.6f, 150, -20); int color = 0xFFFFFF; switch(guns[p.gun].part) { case PART_FIREBALL1: color = 0xFFC8C8; break; } particle_splash(guns[p.gun].part, 1, 1, pos, color, 4.8f, 150, 20); } else regular_particle_splash(PART_SMOKE, 2, 300, pos, 0x404040, 2.4f, 50, -20); } } if(exploded) { if(p.local) addmsg(N_EXPLODE, "rci3iv", p.owner, lastmillis-maptime, p.gun, p.id-maptime, hits.length(), hits.length()*sizeof(hitmsg)/sizeof(int), hits.getbuf()); projs.remove(i--); } else p.o = v; } } extern int chainsawhudgun; VARP(muzzleflash, 0, 1, 1); VARP(muzzlelight, 0, 1, 1); void shoteffects(int gun, const vec &from, const vec &to, fpsent *d, bool local, int id, int prevaction) // create visual effect from a shot { int sound = guns[gun].sound, pspeed = 25; switch(gun) { case GUN_FIST: if(d->type==ENT_PLAYER && chainsawhudgun) sound = S_CHAINSAW_ATTACK; break; case GUN_SG: { if(!local) createrays(gun, from, to); if(muzzleflash && d->muzzle.x >= 0) particle_flare(d->muzzle, d->muzzle, 200, PART_MUZZLE_FLASH3, 0xFFFFFF, 2.75f, d); loopi(guns[gun].rays) { particle_splash(PART_SPARK, 20, 250, rays[i], 0xB49B4B, 0.24f); particle_flare(hudgunorigin(gun, from, rays[i], d), rays[i], 300, PART_STREAK, 0xFFC864, 0.28f); if(!local) adddecal(DECAL_BULLET, rays[i], vec(from).sub(rays[i]).normalize(), 2.0f); } if(muzzlelight) adddynlight(hudgunorigin(gun, d->o, to, d), 30, vec(0.5f, 0.375f, 0.25f), 100, 100, DL_FLASH, 0, vec(0, 0, 0), d); break; } case GUN_CG: case GUN_PISTOL: { particle_splash(PART_SPARK, 200, 250, to, 0xB49B4B, 0.24f); particle_flare(hudgunorigin(gun, from, to, d), to, 600, PART_STREAK, 0xFFC864, 0.28f); if(muzzleflash && d->muzzle.x >= 0) particle_flare(d->muzzle, d->muzzle, gun==GUN_CG ? 100 : 200, PART_MUZZLE_FLASH1, 0xFFFFFF, gun==GUN_CG ? 2.25f : 1.25f, d); if(!local) adddecal(DECAL_BULLET, to, vec(from).sub(to).normalize(), 2.0f); if(muzzlelight) adddynlight(hudgunorigin(gun, d->o, to, d), gun==GUN_CG ? 30 : 15, vec(0.5f, 0.375f, 0.25f), gun==GUN_CG ? 50 : 100, gun==GUN_CG ? 50 : 100, DL_FLASH, 0, vec(0, 0, 0), d); break; } case GUN_RL: if(muzzleflash && d->muzzle.x >= 0) particle_flare(d->muzzle, d->muzzle, 250, PART_MUZZLE_FLASH2, 0xFFFFFF, 3.0f, d); case GUN_FIREBALL: case GUN_ICEBALL: case GUN_SLIMEBALL: pspeed = guns[gun].projspeed; if(d->type==ENT_AI) pspeed /= 2; newprojectile(from, to, (float)pspeed, local, id, d, gun); break; case GUN_GL: { float dist = from.dist(to); vec up = to; up.z += dist/8; if(muzzleflash && d->muzzle.x >= 0) particle_flare(d->muzzle, d->muzzle, 200, PART_MUZZLE_FLASH2, 0xFFFFFF, 1.5f, d); if(muzzlelight) adddynlight(hudgunorigin(gun, d->o, to, d), 20, vec(0.5f, 0.375f, 0.25f), 100, 100, DL_FLASH, 0, vec(0, 0, 0), d); newbouncer(from, up, local, id, d, BNC_GRENADE, guns[gun].ttl, guns[gun].projspeed); break; } case GUN_RIFLE: particle_splash(PART_SPARK, 200, 250, to, 0xB49B4B, 0.24f); particle_trail(PART_SMOKE, 500, hudgunorigin(gun, from, to, d), to, 0x404040, 0.6f, 20); if(muzzleflash && d->muzzle.x >= 0) particle_flare(d->muzzle, d->muzzle, 150, PART_MUZZLE_FLASH3, 0xFFFFFF, 1.25f, d); if(!local) adddecal(DECAL_BULLET, to, vec(from).sub(to).normalize(), 3.0f); if(muzzlelight) adddynlight(hudgunorigin(gun, d->o, to, d), 25, vec(0.5f, 0.375f, 0.25f), 75, 75, DL_FLASH, 0, vec(0, 0, 0), d); break; } bool looped = false; if(d->attacksound >= 0 && d->attacksound != sound) d->stopattacksound(); if(d->idlesound >= 0) d->stopidlesound(); switch(sound) { case S_CHAINSAW_ATTACK: if(d->attacksound >= 0) looped = true; d->attacksound = sound; d->attackchan = playsound(sound, d==hudplayer() ? NULL : &d->o, NULL, 0, -1, 100, d->attackchan); break; default: playsound(sound, d==hudplayer() ? NULL : &d->o); break; } if(d->quadmillis && lastmillis-prevaction>200 && !looped) playsound(S_ITEMPUP, d==hudplayer() ? NULL : &d->o); } void particletrack(physent *owner, vec &o, vec &d) { if(owner->type!=ENT_PLAYER && owner->type!=ENT_AI) return; fpsent *pl = (fpsent *)owner; if(pl->muzzle.x < 0 || pl->lastattackgun != pl->gunselect) return; float dist = o.dist(d); o = pl->muzzle; if(dist <= 0) d = o; else { vecfromyawpitch(owner->yaw, owner->pitch, 1, 0, d); float newdist = raycube(owner->o, d, dist, RAY_CLIPMAT|RAY_ALPHAPOLY); d.mul(min(newdist, dist)).add(owner->o); } } void dynlighttrack(physent *owner, vec &o, vec &hud) { if(owner->type!=ENT_PLAYER && owner->type!=ENT_AI) return; fpsent *pl = (fpsent *)owner; if(pl->muzzle.x < 0 || pl->lastattackgun != pl->gunselect) return; o = pl->muzzle; hud = owner == hudplayer() ? vec(pl->o).add(vec(0, 0, 2)) : pl->muzzle; } float intersectdist = 1e16f; bool intersect(dynent *d, const vec &from, const vec &to, float &dist) // if lineseg hits entity bounding box { vec bottom(d->o), top(d->o); bottom.z -= d->eyeheight; top.z += d->aboveeye; return linecylinderintersect(from, to, bottom, top, d->radius, dist); } dynent *intersectclosest(const vec &from, const vec &to, fpsent *at, float &bestdist) { dynent *best = NULL; bestdist = 1e16f; loopi(numdynents()) { dynent *o = iterdynents(i); if(o==at || o->state!=CS_ALIVE) continue; float dist; if(!intersect(o, from, to, dist)) continue; if(distgunselect].damage; if(d->quadmillis) qdam *= 4; if(d->type==ENT_AI) qdam /= MONSTERDAMAGEFACTOR; dynent *o; float dist; if(guns[d->gunselect].rays > 1) { dynent *hits[MAXRAYS]; int maxrays = guns[d->gunselect].rays; loopi(maxrays) { if((hits[i] = intersectclosest(from, rays[i], d, dist))) shorten(from, rays[i], dist); else adddecal(DECAL_BULLET, rays[i], vec(from).sub(rays[i]).normalize(), 2.0f); } loopi(maxrays) if(hits[i]) { o = hits[i]; hits[i] = NULL; int numhits = 1; for(int j = i+1; j < maxrays; j++) if(hits[j] == o) { hits[j] = NULL; numhits++; } hitpush(numhits*qdam, o, d, from, to, d->gunselect, numhits); } } else if((o = intersectclosest(from, to, d, dist))) { shorten(from, to, dist); hitpush(qdam, o, d, from, to, d->gunselect, 1); } else if(d->gunselect!=GUN_FIST && d->gunselect!=GUN_BITE) adddecal(DECAL_BULLET, to, vec(from).sub(to).normalize(), d->gunselect==GUN_RIFLE ? 3.0f : 2.0f); } void shoot(fpsent *d, const vec &targ) { int prevaction = d->lastaction, attacktime = lastmillis-prevaction; if(attacktimegunwait) return; d->gunwait = 0; if((d==player1 || d->ai) && !d->attacking) return; d->lastaction = lastmillis; d->lastattackgun = d->gunselect; if(!d->ammo[d->gunselect]) { if(d==player1) { msgsound(S_NOAMMO, d); d->gunwait = 600; d->lastattackgun = -1; weaponswitch(d); } return; } if(d->gunselect) d->ammo[d->gunselect]--; vec from = d->o; vec to = targ; vec unitv; float dist = to.dist(from, unitv); unitv.div(dist); vec kickback(unitv); kickback.mul(guns[d->gunselect].kickamount*-2.5f); d->vel.add(kickback); float shorten = 0; if(guns[d->gunselect].range && dist > guns[d->gunselect].range) shorten = guns[d->gunselect].range; float barrier = raycube(d->o, unitv, dist, RAY_CLIPMAT|RAY_ALPHAPOLY); if(barrier > 0 && barrier < dist && (!shorten || barrier < shorten)) shorten = barrier; if(shorten) to = vec(unitv).mul(shorten).add(from); if(guns[d->gunselect].rays > 1) createrays(d->gunselect, from, to); else if(guns[d->gunselect].spread) offsetray(from, to, guns[d->gunselect].spread, guns[d->gunselect].range, to); hits.setsize(0); if(!guns[d->gunselect].projspeed) raydamage(from, to, d); shoteffects(d->gunselect, from, to, d, true, 0, prevaction); if(d==player1 || d->ai) { addmsg(N_SHOOT, "rci2i6iv", d, lastmillis-maptime, d->gunselect, (int)(from.x*DMF), (int)(from.y*DMF), (int)(from.z*DMF), (int)(to.x*DMF), (int)(to.y*DMF), (int)(to.z*DMF), hits.length(), hits.length()*sizeof(hitmsg)/sizeof(int), hits.getbuf()); } d->gunwait = guns[d->gunselect].attackdelay; if(d->gunselect == GUN_PISTOL && d->ai) d->gunwait += int(d->gunwait*(((101-d->skill)+rnd(111-d->skill))/100.f)); d->totalshots += guns[d->gunselect].damage*(d->quadmillis ? 4 : 1)*guns[d->gunselect].rays; } void adddynlights() { loopv(projs) { projectile &p = projs[i]; if(p.gun!=GUN_RL) continue; vec pos(p.o); pos.add(vec(p.offset).mul(p.offsetmillis/float(OFFSETMILLIS))); adddynlight(pos, 20, vec(1, 0.75f, 0.5f)); } loopv(bouncers) { bouncer &bnc = *bouncers[i]; if(bnc.bouncetype!=BNC_GRENADE) continue; vec pos(bnc.o); pos.add(vec(bnc.offset).mul(bnc.offsetmillis/float(OFFSETMILLIS))); adddynlight(pos, 8, vec(0.25f, 1, 1)); } } static const char * const projnames[2] = { "projectiles/grenade", "projectiles/rocket" }; static const char * const gibnames[3] = { "gibs/gib01", "gibs/gib02", "gibs/gib03" }; static const char * const debrisnames[4] = { "debris/debris01", "debris/debris02", "debris/debris03", "debris/debris04" }; static const char * const barreldebrisnames[4] = { "barreldebris/debris01", "barreldebris/debris02", "barreldebris/debris03", "barreldebris/debris04" }; void preloadbouncers() { loopi(sizeof(projnames)/sizeof(projnames[0])) preloadmodel(projnames[i]); loopi(sizeof(gibnames)/sizeof(gibnames[0])) preloadmodel(gibnames[i]); loopi(sizeof(debrisnames)/sizeof(debrisnames[0])) preloadmodel(debrisnames[i]); loopi(sizeof(barreldebrisnames)/sizeof(barreldebrisnames[0])) preloadmodel(barreldebrisnames[i]); } void renderbouncers() { float yaw, pitch; loopv(bouncers) { bouncer &bnc = *bouncers[i]; vec pos(bnc.o); pos.add(vec(bnc.offset).mul(bnc.offsetmillis/float(OFFSETMILLIS))); vec vel(bnc.vel); if(vel.magnitude() <= 25.0f) yaw = bnc.lastyaw; else { vectoyawpitch(vel, yaw, pitch); yaw += 90; bnc.lastyaw = yaw; } pitch = -bnc.roll; if(bnc.bouncetype==BNC_GRENADE) rendermodel(&bnc.light, "projectiles/grenade", ANIM_MAPMODEL|ANIM_LOOP, pos, yaw, pitch, MDL_CULL_VFC|MDL_CULL_OCCLUDED|MDL_LIGHT|MDL_LIGHT_FAST|MDL_DYNSHADOW); else { const char *mdl = NULL; int cull = MDL_CULL_VFC|MDL_CULL_DIST|MDL_CULL_OCCLUDED; float fade = 1; if(bnc.lifetime < 250) fade = bnc.lifetime/250.0f; switch(bnc.bouncetype) { case BNC_GIBS: mdl = gibnames[bnc.variant]; cull |= MDL_LIGHT|MDL_LIGHT_FAST|MDL_DYNSHADOW; break; case BNC_DEBRIS: mdl = debrisnames[bnc.variant]; break; case BNC_BARRELDEBRIS: mdl = barreldebrisnames[bnc.variant]; break; default: continue; } rendermodel(&bnc.light, mdl, ANIM_MAPMODEL|ANIM_LOOP, pos, yaw, pitch, cull, NULL, NULL, 0, 0, fade); } } } void renderprojectiles() { float yaw, pitch; loopv(projs) { projectile &p = projs[i]; if(p.gun!=GUN_RL) continue; float dist = min(p.o.dist(p.to)/32.0f, 1.0f); vec pos = vec(p.o).add(vec(p.offset).mul(dist*p.offsetmillis/float(OFFSETMILLIS))), v = dist < 1e-6f ? p.dir : vec(p.to).sub(pos).normalize(); // the amount of distance in front of the smoke trail needs to change if the model does vectoyawpitch(v, yaw, pitch); yaw += 90; v.mul(3); v.add(pos); rendermodel(&p.light, "projectiles/rocket", ANIM_MAPMODEL|ANIM_LOOP, v, yaw, pitch, MDL_CULL_VFC|MDL_CULL_OCCLUDED|MDL_LIGHT|MDL_LIGHT_FAST); } } void checkattacksound(fpsent *d, bool local) { int gun = -1; switch(d->attacksound) { case S_CHAINSAW_ATTACK: if(chainsawhudgun) gun = GUN_FIST; break; default: return; } if(gun >= 0 && gun < NUMGUNS && d->clientnum >= 0 && d->state == CS_ALIVE && d->lastattackgun == gun && lastmillis - d->lastaction < guns[gun].attackdelay + 50) { d->attackchan = playsound(d->attacksound, local ? NULL : &d->o, NULL, 0, -1, -1, d->attackchan); if(d->attackchan < 0) d->attacksound = -1; } else d->stopattacksound(); } void checkidlesound(fpsent *d, bool local) { int sound = -1, radius = 0; if(d->clientnum >= 0 && d->state == CS_ALIVE) switch(d->gunselect) { case GUN_FIST: if(chainsawhudgun && d->attacksound < 0) { sound = S_CHAINSAW_IDLE; radius = 50; } break; } if(d->idlesound != sound) { if(d->idlesound >= 0) d->stopidlesound(); if(sound >= 0) { d->idlechan = playsound(sound, local ? NULL : &d->o, NULL, 0, -1, 100, d->idlechan, radius); if(d->idlechan >= 0) d->idlesound = sound; } } else if(sound >= 0) { d->idlechan = playsound(sound, local ? NULL : &d->o, NULL, 0, -1, -1, d->idlechan, radius); if(d->idlechan < 0) d->idlesound = -1; } } void removeweapons(fpsent *d) { removebouncers(d); removeprojectiles(d); } void updateweapons(int curtime) { updateprojectiles(curtime); if(player1->clientnum>=0 && player1->state==CS_ALIVE) shoot(player1, worldpos); // only shoot when connected to server updatebouncers(curtime); // need to do this after the player shoots so grenades don't end up inside player's BB next frame fpsent *following = followingplayer(); if(!following) following = player1; loopv(players) { fpsent *d = players[i]; checkattacksound(d, d==following); checkidlesound(d, d==following); } } void avoidweapons(ai::avoidset &obstacles, float radius) { loopv(projs) { projectile &p = projs[i]; obstacles.avoidnear(NULL, p.o.z + guns[p.gun].exprad + 1, p.o, radius + guns[p.gun].exprad); } loopv(bouncers) { bouncer &bnc = *bouncers[i]; if(bnc.bouncetype != BNC_GRENADE) continue; obstacles.avoidnear(NULL, bnc.o.z + guns[GUN_GL].exprad + 1, bnc.o, radius + guns[GUN_GL].exprad); } } }; sauerbraten-0.0.20130203.dfsg/fpsgame/capture.h0000644000175000017500000011176012100271117020631 0ustar vincentvincent// capture.h: client and server state for capture gamemode #ifndef PARSEMESSAGES #ifdef SERVMODE struct captureservmode : servmode #else VARP(capturetether, 0, 1, 1); VARP(autorepammo, 0, 1, 1); VARP(basenumbers, 0, 0, 1); struct captureclientmode : clientmode #endif { static const int CAPTURERADIUS = 64; static const int CAPTUREHEIGHT = 24; static const int OCCUPYBONUS = 1; static const int OCCUPYPOINTS = 1; static const int OCCUPYENEMYLIMIT = 28; static const int OCCUPYNEUTRALLIMIT = 14; static const int SCORESECS = 10; static const int AMMOSECS = 15; static const int REGENSECS = 1; static const int REGENHEALTH = 10; static const int REGENARMOUR = 10; static const int REGENAMMO = 20; static const int MAXAMMO = 5; static const int REPAMMODIST = 32; static const int RESPAWNSECS = 5; static const int MAXBASES = 100; struct baseinfo { vec o; string owner, enemy; #ifndef SERVMODE vec ammopos; string name, info; entitylight light; #endif int ammogroup, ammotype, ammo, owners, enemies, converted, capturetime; baseinfo() { reset(); } bool valid() const { return ammotype>0 && ammotype<=I_CARTRIDGES-I_SHELLS+1; } void noenemy() { enemy[0] = '\0'; enemies = 0; converted = 0; } void reset() { noenemy(); owner[0] = '\0'; capturetime = -1; ammogroup = 0; ammotype = 0; ammo = 0; owners = 0; } bool enter(const char *team) { if(!strcmp(owner, team)) { owners++; return false; } if(!enemies) { if(strcmp(enemy, team)) { converted = 0; copystring(enemy, team); } enemies++; return true; } else if(strcmp(enemy, team)) return false; else enemies++; return false; } bool steal(const char *team) { return !enemies && strcmp(owner, team); } bool leave(const char *team) { if(!strcmp(owner, team) && owners > 0) { owners--; return false; } if(strcmp(enemy, team) || enemies <= 0) return false; enemies--; return !enemies; } int occupy(const char *team, int units) { if(strcmp(enemy, team)) return -1; converted += units; if(units<0) { if(converted<=0) noenemy(); return -1; } else if(converted<(owner[0] ? int(OCCUPYENEMYLIMIT) : int(OCCUPYNEUTRALLIMIT))) return -1; if(owner[0]) { owner[0] = '\0'; converted = 0; copystring(enemy, team); return 0; } else { copystring(owner, team); ammo = 0; capturetime = 0; owners = enemies; noenemy(); return 1; } } bool addammo(int i) { if(ammo>=MAXAMMO) return false; ammo = min(ammo+i, int(MAXAMMO)); return true; } bool takeammo(const char *team) { if(strcmp(owner, team) || ammo<=0) return false; ammo--; return true; } }; vector bases; struct score { string team; int total; }; vector scores; int captures; void resetbases() { bases.shrink(0); scores.shrink(0); captures = 0; } bool hidefrags() { return true; } int getteamscore(const char *team) { loopv(scores) { score &cs = scores[i]; if(!strcmp(cs.team, team)) return cs.total; } return 0; } void getteamscores(vector &teamscores) { loopv(scores) teamscores.add(teamscore(scores[i].team, scores[i].total)); } score &findscore(const char *team) { loopv(scores) { score &cs = scores[i]; if(!strcmp(cs.team, team)) return cs; } score &cs = scores.add(); copystring(cs.team, team); cs.total = 0; return cs; } void addbase(int ammotype, const vec &o) { if(bases.length() >= MAXBASES) return; baseinfo &b = bases.add(); b.ammogroup = min(ammotype, 0); b.ammotype = ammotype > 0 ? ammotype : rnd(I_GRENADES-I_SHELLS+1)+1; b.o = o; if(b.ammogroup) { loopi(bases.length()-1) if(b.ammogroup == bases[i].ammogroup) { b.ammotype = bases[i].ammotype; return; } int uses[I_GRENADES-I_SHELLS+1]; memset(uses, 0, sizeof(uses)); loopi(bases.length()-1) if(bases[i].ammogroup) { loopj(i) if(bases[j].ammogroup == bases[i].ammogroup) goto nextbase; uses[bases[i].ammotype-1]++; nextbase:; } int mintype = 0; loopi(I_GRENADES-I_SHELLS+1) if(uses[i] < uses[mintype]) mintype = i; int numavail = 0, avail[I_GRENADES-I_SHELLS+1]; loopi(I_GRENADES-I_SHELLS+1) if(uses[i] == uses[mintype]) avail[numavail++] = i+1; b.ammotype = avail[rnd(numavail)]; } } void initbase(int i, int ammotype, const char *owner, const char *enemy, int converted, int ammo) { if(!bases.inrange(i)) return; baseinfo &b = bases[i]; b.ammotype = ammotype; copystring(b.owner, owner); copystring(b.enemy, enemy); b.converted = converted; b.ammo = ammo; } bool hasbases(const char *team) { loopv(bases) { baseinfo &b = bases[i]; if(b.owner[0] && !strcmp(b.owner, team)) return true; } return false; } float disttoenemy(baseinfo &b) { float dist = 1e10f; loopv(bases) { baseinfo &e = bases[i]; if(e.owner[0] && strcmp(b.owner, e.owner)) dist = min(dist, b.o.dist(e.o)); } return dist; } bool insidebase(const baseinfo &b, const vec &o) { float dx = (b.o.x-o.x), dy = (b.o.y-o.y), dz = (b.o.z-o.z); return dx*dx + dy*dy <= CAPTURERADIUS*CAPTURERADIUS && fabs(dz) <= CAPTUREHEIGHT; } #ifndef SERVMODE static const int AMMOHEIGHT = 5; captureclientmode() : captures(0) { } void respawned(fpsent *d) { } void replenishammo() { if(!m_capture || m_regencapture) return; loopv(bases) { baseinfo &b = bases[i]; if(b.valid() && insidebase(b, player1->feetpos()) && player1->hasmaxammo(b.ammotype-1+I_SHELLS)) return; } addmsg(N_REPAMMO, "rc", player1); } void receiveammo(fpsent *d, int type) { type += I_SHELLS-1; if(typeI_CARTRIDGES) return; entities::repammo(d, type, d==player1); int icon = itemstats[type-I_SHELLS].icon; if(icon >= 0) particle_icon(d->abovehead(), icon%4, icon/4, PART_HUD_ICON_GREY, 2000, 0xFFFFFF, 2.0f, -8); } void checkitems(fpsent *d) { if(m_regencapture || !autorepammo || d!=player1 || d->state!=CS_ALIVE) return; vec o = d->feetpos(); loopv(bases) { baseinfo &b = bases[i]; if(b.valid() && insidebase(b, d->feetpos()) && !strcmp(b.owner, d->team) && b.o.dist(o) < 12) { if(d->lastrepammo!=i) { if(b.ammo > 0 && !player1->hasmaxammo(b.ammotype-1+I_SHELLS)) addmsg(N_REPAMMO, "rc", d); d->lastrepammo = i; } return; } } d->lastrepammo = -1; } void rendertether(fpsent *d) { int oldbase = d->lastbase; d->lastbase = -1; vec pos(d->o.x, d->o.y, d->o.z + (d->aboveeye - d->eyeheight)/2); if(d->state==CS_ALIVE) { loopv(bases) { baseinfo &b = bases[i]; if(!b.valid() || !insidebase(b, d->feetpos()) || (strcmp(b.owner, d->team) && strcmp(b.enemy, d->team))) continue; if(d->lastbase < 0 && (lookupmaterial(d->feetpos())&MATF_CLIP) == MAT_GAMECLIP) break; particle_flare(pos, vec(b.ammopos.x, b.ammopos.y, b.ammopos.z - AMMOHEIGHT - 4.4f), 0, PART_LIGHTNING, strcmp(d->team, player1->team) ? 0xFF2222 : 0x2222FF, 1.0f); if(oldbase < 0) { particle_fireball(pos, 4.8f, PART_EXPLOSION, 250, strcmp(d->team, player1->team) ? 0x802020 : 0x2020FF, 4.8f); particle_splash(PART_SPARK, 50, 250, pos, strcmp(d->team, player1->team) ? 0x802020 : 0x2020FF, 0.24f); } d->lastbase = i; } } if(d->lastbase < 0 && oldbase >= 0) { particle_fireball(pos, 4.8f, PART_EXPLOSION, 250, strcmp(d->team, player1->team) ? 0x802020 : 0x2020FF, 4.8f); particle_splash(PART_SPARK, 50, 250, pos, strcmp(d->team, player1->team) ? 0x802020 : 0x2020FF, 0.24f); } } void preload() { static const char *basemodels[3] = { "base/neutral", "base/red", "base/blue" }; loopi(3) preloadmodel(basemodels[i]); preloadsound(S_V_BASECAP); preloadsound(S_V_BASELOST); } void rendergame() { if(capturetether && canaddparticles()) { loopv(players) { fpsent *d = players[i]; if(d) rendertether(d); } rendertether(player1); } loopv(bases) { baseinfo &b = bases[i]; if(!b.valid()) continue; const char *basename = b.owner[0] ? (strcmp(b.owner, player1->team) ? "base/red" : "base/blue") : "base/neutral"; rendermodel(&b.light, basename, ANIM_MAPMODEL|ANIM_LOOP, b.o, 0, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_OCCLUDED); float fradius = 1.0f, fheight = 0.5f; regular_particle_flame(PART_FLAME, vec(b.ammopos.x, b.ammopos.y, b.ammopos.z - 4.5f), fradius, fheight, b.owner[0] ? (strcmp(b.owner, player1->team) ? 0x802020 : 0x2020FF) : 0x208020, 3, 2.0f); //regular_particle_flame(PART_SMOKE, vec(b.ammopos.x, b.ammopos.y, b.ammopos.z - 4.5f + 4.0f*min(fradius, fheight)), fradius, fheight, 0x303020, 1, 4.0f, 100.0f, 2000.0f, -20); // particle_fireball(b.ammopos, 4.8f, PART_EXPLOSION, 0, b.owner[0] ? (strcmp(b.owner, player1->team) ? 0x802020 : 0x2020FF) : 0x208020, 4.8f); const char *ammoname = entities::entmdlname(I_SHELLS+b.ammotype-1); if(m_regencapture) { vec height(0, 0, 0); abovemodel(height, ammoname); vec ammopos(b.ammopos); ammopos.z -= height.z/2 + sinf(lastmillis/100.0f)/20; rendermodel(&b.light, ammoname, ANIM_MAPMODEL|ANIM_LOOP, ammopos, lastmillis/10.0f, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_OCCLUDED); } else loopj(b.ammo) { float angle = 2*M_PI*(lastmillis/4000.0f + j/float(MAXAMMO)); vec ammopos(b.o); ammopos.x += 10*cosf(angle); ammopos.y += 10*sinf(angle); ammopos.z += 4; rendermodel(&b.light, entities::entmdlname(I_SHELLS+b.ammotype-1), ANIM_MAPMODEL|ANIM_LOOP, ammopos, 0, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_OCCLUDED); } int tcolor = 0x1EC850, mtype = -1, mcolor = 0xFFFFFF, mcolor2 = 0; if(b.owner[0]) { bool isowner = !strcmp(b.owner, player1->team); if(b.enemy[0]) { mtype = PART_METER_VS; mcolor = 0xFF1932; mcolor2 = 0x3219FF; if(!isowner) swap(mcolor, mcolor2); } if(!b.name[0]) formatstring(b.info)("base %d: %s", i+1, b.owner); else if(basenumbers) formatstring(b.info)("%s (%d): %s", b.name, i+1, b.owner); else formatstring(b.info)("%s: %s", b.name, b.owner); tcolor = isowner ? 0x6496FF : 0xFF4B19; } else if(b.enemy[0]) { if(!b.name[0]) formatstring(b.info)("base %d: %s", i+1, b.enemy); else if(basenumbers) formatstring(b.info)("%s (%d): %s", b.name, i+1, b.enemy); else formatstring(b.info)("%s: %s", b.name, b.enemy); if(strcmp(b.enemy, player1->team)) { tcolor = 0xFF4B19; mtype = PART_METER; mcolor = 0xFF1932; } else { tcolor = 0x6496FF; mtype = PART_METER; mcolor = 0x3219FF; } } else if(!b.name[0]) formatstring(b.info)("base %d", i+1); else if(basenumbers) formatstring(b.info)("%s (%d)", b.name, i+1); else copystring(b.info, b.name); vec above(b.ammopos); above.z += AMMOHEIGHT; if(b.info[0]) particle_text(above, b.info, PART_TEXT, 1, tcolor, 2.0f); if(mtype>=0) { above.z += 3.0f; particle_meter(above, b.converted/float((b.owner[0] ? int(OCCUPYENEMYLIMIT) : int(OCCUPYNEUTRALLIMIT))), mtype, 1, mcolor, mcolor2, 2.0f); } } } void drawblips(fpsent *d, float blipsize, int fw, int fh, int type, bool skipenemy = false) { float scale = calcradarscale(); int blips = 0; loopv(bases) { baseinfo &b = bases[i]; if(!b.valid()) continue; if(skipenemy && b.enemy[0]) continue; switch(type) { case 1: if(!b.owner[0] || strcmp(b.owner, player1->team)) continue; break; case 0: if(b.owner[0]) continue; break; case -1: if(!b.owner[0] || !strcmp(b.owner, player1->team)) continue; break; case -2: if(!b.enemy[0] || !strcmp(b.enemy, player1->team)) continue; break; } vec dir(d->o); dir.sub(b.o).div(scale); float dist = dir.magnitude2(), maxdist = 1 - 0.05f - blipsize; if(dist >= maxdist) dir.mul(maxdist/dist); dir.rotate_around_z(-camera1->yaw*RAD); if(basenumbers) { static string blip; formatstring(blip)("%d", i+1); int tw, th; text_bounds(blip, tw, th); draw_text(blip, int(0.5f*(dir.x*fw/blipsize - tw)), int(0.5f*(dir.y*fh/blipsize - th))); } else { if(!blips) glBegin(GL_QUADS); float x = 0.5f*(dir.x*fw/blipsize - fw), y = 0.5f*(dir.y*fh/blipsize - fh); glTexCoord2f(0.0f, 0.0f); glVertex2f(x, y); glTexCoord2f(1.0f, 0.0f); glVertex2f(x+fw, y); glTexCoord2f(1.0f, 1.0f); glVertex2f(x+fw, y+fh); glTexCoord2f(0.0f, 1.0f); glVertex2f(x, y+fh); } blips++; } if(blips && !basenumbers) glEnd(); } int respawnwait(fpsent *d) { if(m_regencapture) return -1; return max(0, RESPAWNSECS-(lastmillis-d->lastpain)/1000); } int clipconsole(int w, int h) { return (h*(1 + 1 + 10))/(4*10); } void drawhud(fpsent *d, int w, int h) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int s = 1800/4, x = 1800*w/h - s - s/10, y = s/10; glColor4f(1, 1, 1, minimapalpha); if(minimapalpha >= 1) glDisable(GL_BLEND); bindminimap(); drawminimap(d, x, y, s); if(minimapalpha >= 1) glEnable(GL_BLEND); glColor3f(1, 1, 1); float margin = 0.04f, roffset = s*margin, rsize = s + 2*roffset; settexture("packages/hud/radar.png", 3); drawradar(x - roffset, y - roffset, rsize); #if 0 settexture("packages/hud/compass.png", 3); glPushMatrix(); glTranslatef(x - roffset + 0.5f*rsize, y - roffset + 0.5f*rsize, 0); glRotatef(camera1->yaw + 180, 0, 0, -1); drawradar(-0.5f*rsize, -0.5f*rsize, rsize); glPopMatrix(); #endif bool showenemies = lastmillis%1000 >= 500; int fw = 1, fh = 1; if(basenumbers) { pushfont(); setfont("digit_blue"); text_bounds(" ", fw, fh); } else settexture("packages/hud/blip_blue.png", 3); glPushMatrix(); glTranslatef(x + 0.5f*s, y + 0.5f*s, 0); float blipsize = basenumbers ? 0.1f : 0.05f; glScalef((s*blipsize)/fw, (s*blipsize)/fh, 1.0f); drawblips(d, blipsize, fw, fh, 1, showenemies); if(basenumbers) setfont("digit_grey"); else settexture("packages/hud/blip_grey.png", 3); drawblips(d, blipsize, fw, fh, 0, showenemies); if(basenumbers) setfont("digit_red"); else settexture("packages/hud/blip_red.png", 3); drawblips(d, blipsize, fw, fh, -1, showenemies); if(showenemies) drawblips(d, blipsize, fw, fh, -2); glPopMatrix(); if(basenumbers) popfont(); drawteammates(d, x, y, s); if(d->state == CS_DEAD) { int wait = respawnwait(d); if(wait>=0) { glPushMatrix(); glScalef(2, 2, 1); bool flash = wait>0 && d==player1 && lastspawnattempt>=d->lastpain && lastmillis < lastspawnattempt+100; draw_textf("%s%d", (x+s/2)/2-(wait>=10 ? 28 : 16), (y+s/2)/2-32, flash ? "\f3" : "", wait); glPopMatrix(); } } } void setup() { resetbases(); loopv(entities::ents) { extentity *e = entities::ents[i]; if(e->type!=BASE) continue; baseinfo &b = bases.add(); b.o = e->o; b.ammopos = b.o; abovemodel(b.ammopos, "base/neutral"); b.ammopos.z += AMMOHEIGHT-2; b.ammotype = e->attr1; defformatstring(alias)("base_%d", e->attr2); const char *name = getalias(alias); copystring(b.name, name); b.light = e->light; } } void senditems(packetbuf &p) { putint(p, N_BASES); putint(p, bases.length()); loopv(bases) { baseinfo &b = bases[i]; putint(p, b.ammotype); putint(p, int(b.o.x*DMF)); putint(p, int(b.o.y*DMF)); putint(p, int(b.o.z*DMF)); } } void updatebase(int i, const char *owner, const char *enemy, int converted, int ammo) { if(!bases.inrange(i)) return; baseinfo &b = bases[i]; if(owner[0]) { if(strcmp(b.owner, owner)) { if(!b.name[0]) conoutf(CON_GAMEINFO, "%s captured base %d", teamcolor(owner, owner), i+1); else if(basenumbers) conoutf(CON_GAMEINFO, "%s captured %s (%d)", teamcolor(owner, owner), b.name, i+1); else conoutf(CON_GAMEINFO, "%s captured %s", teamcolor(owner, owner), b.name); if(!strcmp(owner, player1->team)) playsound(S_V_BASECAP); } } else if(b.owner[0]) { if(!b.name[0]) conoutf(CON_GAMEINFO, "%s lost base %d", teamcolor(b.owner, b.owner), i+1); else if(basenumbers) conoutf(CON_GAMEINFO, "%s lost %s (%d)", teamcolor(b.owner, b.owner), b.name, i+1); else conoutf(CON_GAMEINFO, "%s lost %s", teamcolor(b.owner, b.owner), b.name); if(!strcmp(b.owner, player1->team)) playsound(S_V_BASELOST); } if(strcmp(b.owner, owner)) particle_splash(PART_SPARK, 200, 250, b.ammopos, owner[0] ? (strcmp(owner, player1->team) ? 0x802020 : 0x2020FF) : 0x208020, 0.24f); copystring(b.owner, owner); copystring(b.enemy, enemy); b.converted = converted; if(ammo>b.ammo) { playsound(S_ITEMSPAWN, &b.o); int icon = b.valid() ? itemstats[b.ammotype-1].icon : -1; if(icon >= 0) particle_icon(vec(b.ammopos.x, b.ammopos.y, b.ammopos.z + AMMOHEIGHT + 1.0f), icon%4, icon/4, PART_HUD_ICON, 2000, 0xFFFFFF, 2.0f, -8); } b.ammo = ammo; } void setscore(int base, const char *team, int total) { findscore(team).total = total; if(total>=10000) conoutf(CON_GAMEINFO, "%s captured all bases", teamcolor(team, team)); else if(bases.inrange(base)) { baseinfo &b = bases[base]; if(!strcmp(b.owner, team)) { defformatstring(msg)("%d", total); vec above(b.ammopos); above.z += AMMOHEIGHT+1.0f; particle_textcopy(above, msg, PART_TEXT, 2000, isteam(team, player1->team) ? 0x6496FF : 0xFF4B19, 4.0f, -8); } } } int closesttoenemy(const char *team, bool noattacked = false, bool farthest = false) { float bestdist = farthest ? -1e10f : 1e10f; int best = -1; int attackers = INT_MAX, attacked = -1; loopv(bases) { baseinfo &b = bases[i]; if(!b.owner[0] || strcmp(b.owner, team)) continue; if(noattacked && b.enemy[0]) continue; float dist = disttoenemy(b); if(farthest ? dist > bestdist : dist < bestdist) { best = i; bestdist = dist; } else if(b.enemy[0] && b.enemies < attackers) { attacked = i; attackers = b.enemies; } } if(best < 0) return attacked; return best; } int pickteamspawn(const char *team) { int closest = closesttoenemy(team, true, m_regencapture); if(!m_regencapture && closest < 0) closest = closesttoenemy(team, false); if(closest < 0) return -1; baseinfo &b = bases[closest]; float bestdist = 1e10f, altdist = 1e10f; int best = -1, alt = -1; loopv(entities::ents) { extentity *e = entities::ents[i]; if(e->type!=PLAYERSTART || e->attr2) continue; float dist = e->o.dist(b.o); if(dist < bestdist) { alt = best; altdist = bestdist; best = i; bestdist = dist; } else if(dist < altdist) { alt = i; altdist = dist; } } return rnd(2) ? best : alt; } void pickspawn(fpsent *d) { findplayerspawn(d, pickteamspawn(d->team)); } bool aicheck(fpsent *d, ai::aistate &b) { return false; } void aifind(fpsent *d, ai::aistate &b, vector &interests) { vec pos = d->feetpos(); loopvj(bases) { baseinfo &f = bases[j]; if(!f.valid()) continue; static vector targets; // build a list of others who are interested in this targets.setsize(0); ai::checkothers(targets, d, ai::AI_S_DEFEND, ai::AI_T_AFFINITY, j, true); fpsent *e = NULL; int regen = !m_regencapture || d->health >= 100 ? 0 : 1; if(m_regencapture) { int gun = f.ammotype-1+I_SHELLS; if(f.ammo > 0 && !d->hasmaxammo(gun)) regen = gun != d->ai->weappref ? 2 : 4; } loopi(numdynents()) if((e = (fpsent *)iterdynents(i)) && !e->ai && e->state == CS_ALIVE && isteam(d->team, e->team)) { // try to guess what non ai are doing vec ep = e->feetpos(); if(targets.find(e->clientnum) < 0 && ep.squaredist(f.o) <= (CAPTURERADIUS*CAPTURERADIUS)) targets.add(e->clientnum); } if((regen && f.owner[0] && !strcmp(f.owner, d->team)) || (targets.empty() && (!f.owner[0] || strcmp(f.owner, d->team) || f.enemy[0]))) { ai::interest &n = interests.add(); n.state = ai::AI_S_DEFEND; n.node = ai::closestwaypoint(f.o, ai::SIGHTMIN, false); n.target = j; n.targtype = ai::AI_T_AFFINITY; n.score = pos.squaredist(f.o)/(regen ? float(100*regen) : 1.f); } } } bool aidefend(fpsent *d, ai::aistate &b) { if(!bases.inrange(b.target)) return false; baseinfo &f = bases[b.target]; if(!f.valid()) return false; bool regen = !m_regencapture || d->health >= 100 ? false : true; if(!regen && m_regencapture) { int gun = f.ammotype-1+I_SHELLS; if(f.ammo > 0 && !d->hasmaxammo(gun)) regen = true; } int walk = 0; if(!regen && !f.enemy[0] && f.owner[0] && !strcmp(f.owner, d->team)) { static vector targets; // build a list of others who are interested in this targets.setsize(0); ai::checkothers(targets, d, ai::AI_S_DEFEND, ai::AI_T_AFFINITY, b.target, true); fpsent *e = NULL; loopi(numdynents()) if((e = (fpsent *)iterdynents(i)) && !e->ai && e->state == CS_ALIVE && isteam(d->team, e->team)) { // try to guess what non ai are doing vec ep = e->feetpos(); if(targets.find(e->clientnum) < 0 && (ep.squaredist(f.o) <= (CAPTURERADIUS*CAPTURERADIUS*4))) targets.add(e->clientnum); } if(!targets.empty()) { if(lastmillis-b.millis >= (201-d->skill)*33) { d->ai->trywipe = true; // re-evaluate so as not to herd return true; } else walk = 2; } else walk = 1; b.millis = lastmillis; } return ai::defend(d, b, f.o, float(CAPTURERADIUS), float(CAPTURERADIUS*(2+(walk*2))), walk); // less wander than ctf } bool aipursue(fpsent *d, ai::aistate &b) { b.type = ai::AI_S_DEFEND; return aidefend(d, b); } }; extern captureclientmode capturemode; ICOMMAND(repammo, "", (), capturemode.replenishammo()); ICOMMAND(insidebases, "", (), { vector buf; if(m_capture && player1->state == CS_ALIVE) loopv(capturemode.bases) { captureclientmode::baseinfo &b = capturemode.bases[i]; if(b.valid() && capturemode.insidebase(b, player1->feetpos())) { if(buf.length()) buf.add(' '); defformatstring(basenum)("%d", i+1); buf.put(basenum, strlen(basenum)); } } buf.add('\0'); result(buf.getbuf()); }); #else bool notgotbases; captureservmode() : captures(0), notgotbases(false) {} void reset(bool empty) { resetbases(); notgotbases = !empty; } void cleanup() { reset(false); } void setup() { reset(false); if(notgotitems || ments.empty()) return; loopv(ments) { entity &e = ments[i]; if(e.type != BASE) continue; int ammotype = e.attr1; addbase(ammotype, e.o); } notgotbases = false; sendbases(); loopv(clients) if(clients[i]->state.state==CS_ALIVE) entergame(clients[i]); } void newmap() { reset(true); } void stealbase(int n, const char *team) { baseinfo &b = bases[n]; loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.state==CS_ALIVE && ci->team[0] && !strcmp(ci->team, team) && insidebase(b, ci->state.o)) b.enter(ci->team); } sendbaseinfo(n); } void replenishammo(clientinfo *ci) { if(m_noitems || notgotbases || ci->state.state!=CS_ALIVE || !ci->team[0]) return; loopv(bases) { baseinfo &b = bases[i]; if(b.valid() && insidebase(b, ci->state.o) && !ci->state.hasmaxammo(b.ammotype-1+I_SHELLS) && b.takeammo(ci->team)) { sendbaseinfo(i); sendf(-1, 1, "riii", N_REPAMMO, ci->clientnum, b.ammotype); ci->state.addammo(b.ammotype); break; } } } void movebases(const char *team, const vec &oldpos, bool oldclip, const vec &newpos, bool newclip) { if(!team[0] || gamemillis>=gamelimit) return; loopv(bases) { baseinfo &b = bases[i]; if(!b.valid()) continue; bool leave = !oldclip && insidebase(b, oldpos), enter = !newclip && insidebase(b, newpos); if(leave && !enter && b.leave(team)) sendbaseinfo(i); else if(enter && !leave && b.enter(team)) sendbaseinfo(i); else if(leave && enter && b.steal(team)) stealbase(i, team); } } void leavebases(const char *team, const vec &o) { movebases(team, o, false, vec(-1e10f, -1e10f, -1e10f), true); } void enterbases(const char *team, const vec &o) { movebases(team, vec(-1e10f, -1e10f, -1e10f), true, o, false); } void addscore(int base, const char *team, int n) { if(!n) return; score &cs = findscore(team); cs.total += n; sendf(-1, 1, "riisi", N_BASESCORE, base, team, cs.total); } void regenowners(baseinfo &b, int ticks) { loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.state==CS_ALIVE && ci->team[0] && !strcmp(ci->team, b.owner) && insidebase(b, ci->state.o)) { bool notify = false; if(ci->state.health < ci->state.maxhealth) { ci->state.health = min(ci->state.health + ticks*REGENHEALTH, ci->state.maxhealth); notify = true; } if(ci->state.armourtype != A_GREEN || ci->state.armour < itemstats[I_GREENARMOUR-I_SHELLS].max) { if(ci->state.armourtype != A_GREEN) { ci->state.armourtype = A_GREEN; ci->state.armour = 0; } ci->state.armour = min(ci->state.armour + ticks*REGENARMOUR, itemstats[I_GREENARMOUR-I_SHELLS].max); notify = true; } if(b.valid()) { int ammotype = b.ammotype-1+I_SHELLS; if(!ci->state.hasmaxammo(ammotype)) { ci->state.addammo(b.ammotype, ticks*REGENAMMO, 100); notify = true; } } if(notify) sendf(-1, 1, "ri6", N_BASEREGEN, ci->clientnum, ci->state.health, ci->state.armour, b.ammotype, b.valid() ? ci->state.ammo[b.ammotype] : 0); } } } void update() { if(gamemillis>=gamelimit) return; endcheck(); int t = gamemillis/1000 - (gamemillis-curtime)/1000; if(t<1) return; loopv(bases) { baseinfo &b = bases[i]; if(!b.valid()) continue; if(b.enemy[0]) { if(!b.owners || !b.enemies) b.occupy(b.enemy, OCCUPYBONUS*(b.enemies ? 1 : -1) + OCCUPYPOINTS*(b.enemies ? b.enemies : -(1+b.owners))*t); sendbaseinfo(i); } else if(b.owner[0]) { b.capturetime += t; int score = b.capturetime/SCORESECS - (b.capturetime-t)/SCORESECS; if(score) addscore(i, b.owner, score); if(m_regencapture) { int regen = b.capturetime/REGENSECS - (b.capturetime-t)/REGENSECS; if(regen) regenowners(b, regen); } else { int ammo = b.capturetime/AMMOSECS - (b.capturetime-t)/AMMOSECS; if(ammo && b.addammo(ammo)) sendbaseinfo(i); } } } } void sendbaseinfo(int i) { baseinfo &b = bases[i]; sendf(-1, 1, "riissii", N_BASEINFO, i, b.owner, b.enemy, b.enemy[0] ? b.converted : 0, b.owner[0] ? b.ammo : 0); } void sendbases() { packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); initclient(NULL, p, false); sendpacket(-1, 1, p.finalize()); } void initclient(clientinfo *ci, packetbuf &p, bool connecting) { if(connecting) { loopv(scores) { score &cs = scores[i]; putint(p, N_BASESCORE); putint(p, -1); sendstring(cs.team, p); putint(p, cs.total); } } putint(p, N_BASES); putint(p, bases.length()); loopv(bases) { baseinfo &b = bases[i]; putint(p, b.ammotype); sendstring(b.owner, p); sendstring(b.enemy, p); putint(p, b.converted); putint(p, b.ammo); } } void endcheck() { const char *lastteam = NULL; loopv(bases) { baseinfo &b = bases[i]; if(!b.valid()) continue; if(b.owner[0]) { if(!lastteam) lastteam = b.owner; else if(strcmp(lastteam, b.owner)) { lastteam = NULL; break; } } else { lastteam = NULL; break; } } if(!lastteam) return; findscore(lastteam).total = 10000; sendf(-1, 1, "riisi", N_BASESCORE, -1, lastteam, 10000); startintermission(); } void entergame(clientinfo *ci) { if(notgotbases || ci->state.state!=CS_ALIVE || ci->gameclip) return; enterbases(ci->team, ci->state.o); } void spawned(clientinfo *ci) { if(notgotbases || ci->gameclip) return; enterbases(ci->team, ci->state.o); } void leavegame(clientinfo *ci, bool disconnecting = false) { if(notgotbases || ci->state.state!=CS_ALIVE || ci->gameclip) return; leavebases(ci->team, ci->state.o); } void died(clientinfo *ci, clientinfo *actor) { if(notgotbases || ci->gameclip) return; leavebases(ci->team, ci->state.o); } bool canspawn(clientinfo *ci, bool connecting) { return m_regencapture || connecting || !ci->state.lastdeath || gamemillis+curtime-ci->state.lastdeath >= RESPAWNSECS*1000; } void moved(clientinfo *ci, const vec &oldpos, bool oldclip, const vec &newpos, bool newclip) { if(notgotbases) return; movebases(ci->team, oldpos, oldclip, newpos, newclip); } void changeteam(clientinfo *ci, const char *oldteam, const char *newteam) { if(notgotbases || ci->gameclip) return; leavebases(oldteam, ci->state.o); enterbases(newteam, ci->state.o); } void parsebases(ucharbuf &p, bool commit) { int numbases = getint(p); loopi(numbases) { int ammotype = getint(p); vec o; loopk(3) o[k] = max(getint(p)/DMF, 0.0f); if(p.overread()) break; if(commit && notgotbases) addbase(ammotype>=GUN_SG && ammotype<=GUN_PISTOL ? ammotype : min(ammotype, 0), o); } if(commit && notgotbases) { notgotbases = false; sendbases(); loopv(clients) if(clients[i]->state.state==CS_ALIVE) entergame(clients[i]); } } bool extinfoteam(const char *team, ucharbuf &p) { int numbases = 0; loopvj(bases) if(!strcmp(bases[j].owner, team)) numbases++; putint(p, numbases); loopvj(bases) if(!strcmp(bases[j].owner, team)) putint(p, j); return true; } }; #endif #elif SERVMODE case N_BASES: if(smode==&capturemode) capturemode.parsebases(p, (ci->state.state!=CS_SPECTATOR || ci->privilege || ci->local) && !strcmp(ci->clientmap, smapname)); break; case N_REPAMMO: if((ci->state.state!=CS_SPECTATOR || ci->local || ci->privilege) && cq && smode==&capturemode) capturemode.replenishammo(cq); break; #else case N_BASEINFO: { int base = getint(p); string owner, enemy; getstring(text, p); copystring(owner, text); getstring(text, p); copystring(enemy, text); int converted = getint(p), ammo = getint(p); if(m_capture) capturemode.updatebase(base, owner, enemy, converted, ammo); break; } case N_BASEREGEN: { int rcn = getint(p), health = getint(p), armour = getint(p), ammotype = getint(p), ammo = getint(p); fpsent *regen = rcn==player1->clientnum ? player1 : getclient(rcn); if(regen && m_capture) { regen->health = health; regen->armourtype = A_GREEN; regen->armour = armour; if(ammotype>=GUN_SG && ammotype<=GUN_PISTOL) regen->ammo[ammotype] = ammo; } break; } case N_BASES: { int numbases = getint(p); loopi(numbases) { int ammotype = getint(p); string owner, enemy; getstring(text, p); copystring(owner, text); getstring(text, p); copystring(enemy, text); int converted = getint(p), ammo = getint(p); capturemode.initbase(i, ammotype, owner, enemy, converted, ammo); } break; } case N_BASESCORE: { int base = getint(p); getstring(text, p); int total = getint(p); if(m_capture) capturemode.setscore(base, text, total); break; } case N_REPAMMO: { int rcn = getint(p), ammotype = getint(p); fpsent *r = rcn==player1->clientnum ? player1 : getclient(rcn); if(r && m_capture) capturemode.receiveammo(r, ammotype); break; } #endif sauerbraten-0.0.20130203.dfsg/fpsgame/fps.cpp0000644000175000017500000010275712074035705020332 0ustar vincentvincent#include "game.h" namespace game { bool intermission = false; int maptime = 0, maprealtime = 0, maplimit = -1; int respawnent = -1; int lasthit = 0, lastspawnattempt = 0; int following = -1, followdir = 0; fpsent *player1 = NULL; // our client vector players; // other clients int savedammo[NUMGUNS]; bool clientoption(const char *arg) { return false; } void taunt() { if(player1->state!=CS_ALIVE || player1->physstatelasttaunt<1000) return; player1->lasttaunt = lastmillis; addmsg(N_TAUNT, "rc", player1); } COMMAND(taunt, ""); ICOMMAND(getfollow, "", (), { fpsent *f = followingplayer(); intret(f ? f->clientnum : -1); }); void follow(char *arg) { if(arg[0] ? player1->state==CS_SPECTATOR : following>=0) { following = arg[0] ? parseplayer(arg) : -1; if(following==player1->clientnum) following = -1; followdir = 0; conoutf("follow %s", following>=0 ? "on" : "off"); } } COMMAND(follow, "s"); void nextfollow(int dir) { if(player1->state!=CS_SPECTATOR || clients.empty()) { stopfollowing(); return; } int cur = following >= 0 ? following : (dir < 0 ? clients.length() - 1 : 0); loopv(clients) { cur = (cur + dir + clients.length()) % clients.length(); if(clients[cur] && clients[cur]->state!=CS_SPECTATOR) { if(following<0) conoutf("follow on"); following = cur; followdir = dir; return; } } stopfollowing(); } ICOMMAND(nextfollow, "i", (int *dir), nextfollow(*dir < 0 ? -1 : 1)); const char *getclientmap() { return clientmap; } void resetgamestate() { if(m_classicsp) { clearmovables(); clearmonsters(); // all monsters back at their spawns for editing entities::resettriggers(); } clearprojectiles(); clearbouncers(); } fpsent *spawnstate(fpsent *d) // reset player state not persistent accross spawns { d->respawn(); d->spawnstate(gamemode); return d; } void respawnself() { if(ispaused()) return; if(m_mp(gamemode)) { int seq = (player1->lifesequence<<16)|((lastmillis/1000)&0xFFFF); if(player1->respawned!=seq) { addmsg(N_TRYSPAWN, "rc", player1); player1->respawned = seq; } } else { spawnplayer(player1); showscores(false); lasthit = 0; if(cmode) cmode->respawned(player1); } } fpsent *pointatplayer() { loopv(players) if(players[i] != player1 && intersect(players[i], player1->o, worldpos)) return players[i]; return NULL; } void stopfollowing() { if(following<0) return; following = -1; followdir = 0; conoutf("follow off"); } fpsent *followingplayer() { if(player1->state!=CS_SPECTATOR || following<0) return NULL; fpsent *target = getclient(following); if(target && target->state!=CS_SPECTATOR) return target; return NULL; } fpsent *hudplayer() { if(thirdperson) return player1; fpsent *target = followingplayer(); return target ? target : player1; } void setupcamera() { fpsent *target = followingplayer(); if(target) { player1->yaw = target->yaw; player1->pitch = target->state==CS_DEAD ? 0 : target->pitch; player1->o = target->o; player1->resetinterp(); } } bool detachcamera() { fpsent *d = hudplayer(); return d->state==CS_DEAD; } bool collidecamera() { switch(player1->state) { case CS_EDITING: return false; case CS_SPECTATOR: return followingplayer()!=NULL; } return true; } VARP(smoothmove, 0, 75, 100); VARP(smoothdist, 0, 32, 64); void predictplayer(fpsent *d, bool move) { d->o = d->newpos; d->yaw = d->newyaw; d->pitch = d->newpitch; d->roll = d->newroll; if(move) { moveplayer(d, 1, false); d->newpos = d->o; } float k = 1.0f - float(lastmillis - d->smoothmillis)/smoothmove; if(k>0) { d->o.add(vec(d->deltapos).mul(k)); d->yaw += d->deltayaw*k; if(d->yaw<0) d->yaw += 360; else if(d->yaw>=360) d->yaw -= 360; d->pitch += d->deltapitch*k; d->roll += d->deltaroll*k; } } void otherplayers(int curtime) { loopv(players) { fpsent *d = players[i]; if(d == player1 || d->ai) continue; if(d->state==CS_DEAD && d->ragdoll) moveragdoll(d); else if(!intermission) { if(lastmillis - d->lastaction >= d->gunwait) d->gunwait = 0; if(d->quadmillis) entities::checkquad(curtime, d); } const int lagtime = totalmillis-d->lastupdate; if(!lagtime || intermission) continue; else if(lagtime>1000 && d->state==CS_ALIVE) { d->state = CS_LAGGED; continue; } if(d->state==CS_ALIVE || d->state==CS_EDITING) { if(smoothmove && d->smoothmillis>0) predictplayer(d, true); else moveplayer(d, 1, false); } else if(d->state==CS_DEAD && !d->ragdoll && lastmillis-d->lastpain<2000) moveplayer(d, 1, true); } } VARFP(slowmosp, 0, 0, 1, { if(m_sp && !slowmosp) server::forcegamespeed(100); }); void checkslowmo() { static int lastslowmohealth = 0; server::forcegamespeed(intermission ? 100 : clamp(player1->health, 25, 200)); if(player1->healthmaxhealth && lastmillis-max(maptime, lastslowmohealth)>player1->health*player1->health/2) { lastslowmohealth = lastmillis; player1->health++; } } void updateworld() // main game update loop { if(!maptime) { maptime = lastmillis; maprealtime = totalmillis; return; } if(!curtime) { gets2c(); if(player1->clientnum>=0) c2sinfo(); return; } physicsframe(); ai::navigate(); if(player1->state != CS_DEAD && !intermission) { if(player1->quadmillis) entities::checkquad(curtime, player1); } updateweapons(curtime); otherplayers(curtime); ai::update(); moveragdolls(); gets2c(); updatemovables(curtime); updatemonsters(curtime); if(player1->state == CS_DEAD) { if(player1->ragdoll) moveragdoll(player1); else if(lastmillis-player1->lastpain<2000) { player1->move = player1->strafe = 0; moveplayer(player1, 10, true); } } else if(!intermission) { if(player1->ragdoll) cleanragdoll(player1); moveplayer(player1, 10, true); swayhudgun(curtime); entities::checkitems(player1); if(m_sp) { if(slowmosp) checkslowmo(); if(m_classicsp) entities::checktriggers(); } else if(cmode) cmode->checkitems(player1); } if(player1->clientnum>=0) c2sinfo(); // do this last, to reduce the effective frame lag } void spawnplayer(fpsent *d) // place at random spawn { if(cmode) cmode->pickspawn(d); else findplayerspawn(d, d==player1 && respawnent>=0 ? respawnent : -1); spawnstate(d); if(d==player1) { if(editmode) d->state = CS_EDITING; else if(d->state != CS_SPECTATOR) d->state = CS_ALIVE; } else d->state = CS_ALIVE; } VARP(spawnwait, 0, 0, 1000); void respawn() { if(player1->state==CS_DEAD) { player1->attacking = false; int wait = cmode ? cmode->respawnwait(player1) : 0; if(wait>0) { lastspawnattempt = lastmillis; //conoutf(CON_GAMEINFO, "\f2you must wait %d second%s before respawn!", wait, wait!=1 ? "s" : ""); return; } if(lastmillis < player1->lastpain + spawnwait) return; if(m_dmsp) { changemap(clientmap, gamemode); return; } // if we die in SP we try the same map again respawnself(); if(m_classicsp) { conoutf(CON_GAMEINFO, "\f2You wasted another life! The monsters stole your armour and some ammo..."); loopi(NUMGUNS) if(i!=GUN_PISTOL && (player1->ammo[i] = savedammo[i]) > 5) player1->ammo[i] = max(player1->ammo[i]/3, 5); } } } // inputs void doattack(bool on) { if(intermission) return; if((player1->attacking = on)) respawn(); } bool canjump() { if(!intermission) respawn(); return player1->state!=CS_DEAD && !intermission; } bool allowmove(physent *d) { if(d->type!=ENT_PLAYER) return true; return !((fpsent *)d)->lasttaunt || lastmillis-((fpsent *)d)->lasttaunt>=1000; } VARP(hitsound, 0, 0, 1); void damaged(int damage, fpsent *d, fpsent *actor, bool local) { if((d->state!=CS_ALIVE && d->state != CS_LAGGED && d->state != CS_SPAWNING) || intermission) return; if(local) damage = d->dodamage(damage); else if(actor==player1) return; fpsent *h = hudplayer(); if(h!=player1 && actor==h && d!=actor) { if(hitsound && lasthit != lastmillis) playsound(S_HIT); lasthit = lastmillis; } if(d==h) { damageblend(damage); damagecompass(damage, actor->o); } damageeffect(damage, d, d!=h); ai::damaged(d, actor); if(m_sp && slowmosp && d==player1 && d->health < 1) d->health = 1; if(d->health<=0) { if(local) killed(d, actor); } else if(d==h) playsound(S_PAIN6); else playsound(S_PAIN1+rnd(5), &d->o); } VARP(deathscore, 0, 1, 1); void deathstate(fpsent *d, bool restore) { d->state = CS_DEAD; d->lastpain = lastmillis; if(!restore) gibeffect(max(-d->health, 0), d->vel, d); if(d==player1) { if(deathscore) showscores(true); disablezoom(); if(!restore) loopi(NUMGUNS) savedammo[i] = player1->ammo[i]; d->attacking = false; if(!restore) d->deaths++; //d->pitch = 0; d->roll = 0; playsound(S_DIE1+rnd(2)); } else { d->move = d->strafe = 0; d->resetinterp(); d->smoothmillis = 0; playsound(S_DIE1+rnd(2), &d->o); } } VARP(teamcolorfrags, 0, 1, 1); void killed(fpsent *d, fpsent *actor) { if(d->state==CS_EDITING) { d->editstate = CS_DEAD; if(d==player1) d->deaths++; else d->resetinterp(); return; } else if((d->state!=CS_ALIVE && d->state != CS_LAGGED && d->state != CS_SPAWNING) || intermission) return; fpsent *h = followingplayer(); if(!h) h = player1; int contype = d==h || actor==h ? CON_FRAG_SELF : CON_FRAG_OTHER; const char *dname = "", *aname = ""; if(m_teammode && teamcolorfrags) { dname = teamcolorname(d, "you"); aname = teamcolorname(actor, "you"); } else { dname = colorname(d, NULL, "", "", "you"); aname = colorname(actor, NULL, "", "", "you"); } if(actor->type==ENT_AI) conoutf(contype, "\f2%s got killed by %s!", dname, aname); else if(d==actor || actor->type==ENT_INANIMATE) conoutf(contype, "\f2%s suicided%s", dname, d==player1 ? "!" : ""); else if(isteam(d->team, actor->team)) { contype |= CON_TEAMKILL; if(actor==player1) conoutf(contype, "\f6%s fragged a teammate (%s)", aname, dname); else if(d==player1) conoutf(contype, "\f6%s got fragged by a teammate (%s)", dname, aname); else conoutf(contype, "\f2%s fragged a teammate (%s)", aname, dname); } else { if(d==player1) conoutf(contype, "\f2%s got fragged by %s", dname, aname); else conoutf(contype, "\f2%s fragged %s", aname, dname); } deathstate(d); ai::killed(d, actor); } void timeupdate(int secs) { if(secs > 0) { maplimit = lastmillis + secs*1000; } else { intermission = true; player1->attacking = false; if(cmode) cmode->gameover(); conoutf(CON_GAMEINFO, "\f2intermission:"); conoutf(CON_GAMEINFO, "\f2game has ended!"); if(m_ctf) conoutf(CON_GAMEINFO, "\f2player frags: %d, flags: %d, deaths: %d", player1->frags, player1->flags, player1->deaths); else if(m_collect) conoutf(CON_GAMEINFO, "\f2player frags: %d, skulls: %d, deaths: %d", player1->frags, player1->flags, player1->deaths); else conoutf(CON_GAMEINFO, "\f2player frags: %d, deaths: %d", player1->frags, player1->deaths); int accuracy = (player1->totaldamage*100)/max(player1->totalshots, 1); conoutf(CON_GAMEINFO, "\f2player total damage dealt: %d, damage wasted: %d, accuracy(%%): %d", player1->totaldamage, player1->totalshots-player1->totaldamage, accuracy); if(m_sp) spsummary(accuracy); showscores(true); disablezoom(); if(identexists("intermission")) execute("intermission"); } } ICOMMAND(getfrags, "", (), intret(player1->frags)); ICOMMAND(getflags, "", (), intret(player1->flags)); ICOMMAND(getdeaths, "", (), intret(player1->deaths)); ICOMMAND(getaccuracy, "", (), intret((player1->totaldamage*100)/max(player1->totalshots, 1))); ICOMMAND(gettotaldamage, "", (), intret(player1->totaldamage)); ICOMMAND(gettotalshots, "", (), intret(player1->totalshots)); vector clients; fpsent *newclient(int cn) // ensure valid entity { if(cn < 0 || cn > max(0xFF, MAXCLIENTS + MAXBOTS)) { neterr("clientnum", false); return NULL; } if(cn == player1->clientnum) return player1; while(cn >= clients.length()) clients.add(NULL); if(!clients[cn]) { fpsent *d = new fpsent; d->clientnum = cn; clients[cn] = d; players.add(d); } return clients[cn]; } fpsent *getclient(int cn) // ensure valid entity { if(cn == player1->clientnum) return player1; return clients.inrange(cn) ? clients[cn] : NULL; } void clientdisconnected(int cn, bool notify) { if(!clients.inrange(cn)) return; if(following==cn) { if(followdir) nextfollow(followdir); else stopfollowing(); } unignore(cn); fpsent *d = clients[cn]; if(!d) return; if(notify && d->name[0]) conoutf("\f4leave:\f7 %s", colorname(d)); removeweapons(d); removetrackedparticles(d); removetrackeddynlights(d); if(cmode) cmode->removeplayer(d); players.removeobj(d); DELETEP(clients[cn]); cleardynentcache(); } void clearclients(bool notify) { loopv(clients) if(clients[i]) clientdisconnected(i, notify); } void initclient() { player1 = spawnstate(new fpsent); players.add(player1); } VARP(showmodeinfo, 0, 1, 1); void startgame() { clearmovables(); clearmonsters(); clearprojectiles(); clearbouncers(); clearragdolls(); clearteaminfo(); // reset perma-state loopv(players) { fpsent *d = players[i]; d->frags = d->flags = 0; d->deaths = 0; d->totaldamage = 0; d->totalshots = 0; d->maxhealth = 100; d->lifesequence = -1; d->respawned = d->suicided = -2; } setclientmode(); intermission = false; maptime = maprealtime = 0; maplimit = -1; if(cmode) { cmode->preload(); cmode->setup(); } conoutf(CON_GAMEINFO, "\f2game mode is %s", server::modename(gamemode)); if(m_sp) { defformatstring(scorename)("bestscore_%s", getclientmap()); const char *best = getalias(scorename); if(*best) conoutf(CON_GAMEINFO, "\f2try to beat your best score so far: %s", best); } else { const char *info = m_valid(gamemode) ? gamemodes[gamemode - STARTGAMEMODE].info : NULL; if(showmodeinfo && info) conoutf(CON_GAMEINFO, "\f0%s", info); } if(player1->playermodel != playermodel) switchplayermodel(playermodel); showscores(false); disablezoom(); lasthit = 0; if(identexists("mapstart")) execute("mapstart"); } void startmap(const char *name) // called just after a map load { ai::savewaypoints(); ai::clearwaypoints(true); respawnent = -1; // so we don't respawn at an old spot if(!m_mp(gamemode)) spawnplayer(player1); else findplayerspawn(player1, -1); entities::resetspawns(); copystring(clientmap, name ? name : ""); sendmapinfo(); } const char *getmapinfo() { return showmodeinfo && m_valid(gamemode) ? gamemodes[gamemode - STARTGAMEMODE].info : NULL; } void physicstrigger(physent *d, bool local, int floorlevel, int waterlevel, int material) { if(d->type==ENT_INANIMATE) return; if (waterlevel>0) { if(material!=MAT_LAVA) playsound(S_SPLASH1, d==player1 ? NULL : &d->o); } else if(waterlevel<0) playsound(material==MAT_LAVA ? S_BURN : S_SPLASH2, d==player1 ? NULL : &d->o); if (floorlevel>0) { if(d==player1 || d->type!=ENT_PLAYER || ((fpsent *)d)->ai) msgsound(S_JUMP, d); } else if(floorlevel<0) { if(d==player1 || d->type!=ENT_PLAYER || ((fpsent *)d)->ai) msgsound(S_LAND, d); } } void dynentcollide(physent *d, physent *o, const vec &dir) { switch(d->type) { case ENT_AI: if(dir.z > 0) stackmonster((monster *)d, o); break; case ENT_INANIMATE: if(dir.z > 0) stackmovable((movable *)d, o); break; } } void msgsound(int n, physent *d) { if(!d || d==player1) { addmsg(N_SOUND, "ci", d, n); playsound(n); } else { if(d->type==ENT_PLAYER && ((fpsent *)d)->ai) addmsg(N_SOUND, "ci", d, n); playsound(n, &d->o); } } int numdynents() { return players.length()+monsters.length()+movables.length(); } dynent *iterdynents(int i) { if(iname; if(alt && d != player1 && !strcmp(name, alt)) return true; loopv(players) if(d!=players[i] && !strcmp(name, players[i]->name)) return true; return false; } static string cname[3]; static int cidx = 0; const char *colorname(fpsent *d, const char *name, const char *prefix, const char *suffix, const char *alt) { if(!name) name = alt && d == player1 ? alt : d->name; bool dup = !name[0] || duplicatename(d, name, alt) || d->aitype != AI_NONE; if(dup || prefix[0] || suffix[0]) { cidx = (cidx+1)%3; if(dup) formatstring(cname[cidx])(d->aitype == AI_NONE ? "%s%s \fs\f5(%d)\fr%s" : "%s%s \fs\f5[%d]\fr%s", prefix, name, d->clientnum, suffix); else formatstring(cname[cidx])("%s%s%s", prefix, name, suffix); return cname[cidx]; } return name; } VARP(teamcolortext, 0, 1, 1); const char *teamcolorname(fpsent *d, const char *alt) { if(!teamcolortext || !m_teammode) return colorname(d, NULL, "", "", alt); return colorname(d, NULL, isteam(d->team, player1->team) ? "\fs\f1" : "\fs\f3", "\fr", alt); } const char *teamcolor(const char *name, bool sameteam, const char *alt) { if(!teamcolortext || !m_teammode) return sameteam || !alt ? name : alt; cidx = (cidx+1)%3; formatstring(cname[cidx])(sameteam ? "\fs\f1%s\fr" : "\fs\f3%s\fr", sameteam || !alt ? name : alt); return cname[cidx]; } const char *teamcolor(const char *name, const char *team, const char *alt) { return teamcolor(name, team && isteam(team, player1->team), alt); } void suicide(physent *d) { if(d==player1 || (d->type==ENT_PLAYER && ((fpsent *)d)->ai)) { if(d->state!=CS_ALIVE) return; fpsent *pl = (fpsent *)d; if(!m_mp(gamemode)) killed(pl, pl); else { int seq = (pl->lifesequence<<16)|((lastmillis/1000)&0xFFFF); if(pl->suicided!=seq) { addmsg(N_SUICIDE, "rc", pl); pl->suicided = seq; } } } else if(d->type==ENT_AI) suicidemonster((monster *)d); else if(d->type==ENT_INANIMATE) suicidemovable((movable *)d); } ICOMMAND(kill, "", (), suicide(player1)); bool needminimap() { return m_ctf || m_protect || m_hold || m_capture || m_collect; } void drawicon(int icon, float x, float y, float sz) { settexture("packages/hud/items.png"); glBegin(GL_TRIANGLE_STRIP); float tsz = 0.25f, tx = tsz*(icon%4), ty = tsz*(icon/4); glTexCoord2f(tx, ty); glVertex2f(x, y); glTexCoord2f(tx+tsz, ty); glVertex2f(x+sz, y); glTexCoord2f(tx, ty+tsz); glVertex2f(x, y+sz); glTexCoord2f(tx+tsz, ty+tsz); glVertex2f(x+sz, y+sz); glEnd(); } float abovegameplayhud(int w, int h) { switch(hudplayer()->state) { case CS_EDITING: case CS_SPECTATOR: return 1; default: return 1650.0f/1800.0f; } } int ammohudup[3] = { GUN_CG, GUN_RL, GUN_GL }, ammohuddown[3] = { GUN_RIFLE, GUN_SG, GUN_PISTOL }, ammohudcycle[7] = { -1, -1, -1, -1, -1, -1, -1 }; ICOMMAND(ammohudup, "V", (tagval *args, int numargs), { loopi(3) ammohudup[i] = i < numargs ? getweapon(args[i].getstr()) : -1; }); ICOMMAND(ammohuddown, "V", (tagval *args, int numargs), { loopi(3) ammohuddown[i] = i < numargs ? getweapon(args[i].getstr()) : -1; }); ICOMMAND(ammohudcycle, "V", (tagval *args, int numargs), { loopi(7) ammohudcycle[i] = i < numargs ? getweapon(args[i].getstr()) : -1; }); VARP(ammohud, 0, 1, 1); void drawammohud(fpsent *d) { float x = HICON_X + 2*HICON_STEP, y = HICON_Y, sz = HICON_SIZE; glPushMatrix(); glScalef(1/3.2f, 1/3.2f, 1); float xup = (x+sz)*3.2f, yup = y*3.2f + 0.1f*sz; loopi(3) { int gun = ammohudup[i]; if(gun < GUN_FIST || gun > GUN_PISTOL || gun == d->gunselect || !d->ammo[gun]) continue; drawicon(HICON_FIST+gun, xup, yup, sz); yup += sz; } float xdown = x*3.2f - sz, ydown = (y+sz)*3.2f - 0.1f*sz; loopi(3) { int gun = ammohuddown[3-i-1]; if(gun < GUN_FIST || gun > GUN_PISTOL || gun == d->gunselect || !d->ammo[gun]) continue; ydown -= sz; drawicon(HICON_FIST+gun, xdown, ydown, sz); } int offset = 0, num = 0; loopi(7) { int gun = ammohudcycle[i]; if(gun < GUN_FIST || gun > GUN_PISTOL) continue; if(gun == d->gunselect) offset = i + 1; else if(d->ammo[gun]) num++; } float xcycle = (x+sz/2)*3.2f + 0.5f*num*sz, ycycle = y*3.2f-sz; loopi(7) { int gun = ammohudcycle[(i + offset)%7]; if(gun < GUN_FIST || gun > GUN_PISTOL || gun == d->gunselect || !d->ammo[gun]) continue; xcycle -= sz; drawicon(HICON_FIST+gun, xcycle, ycycle, sz); } glPopMatrix(); } void drawhudicons(fpsent *d) { glPushMatrix(); glScalef(2, 2, 1); draw_textf("%d", (HICON_X + HICON_SIZE + HICON_SPACE)/2, HICON_TEXTY/2, d->state==CS_DEAD ? 0 : d->health); if(d->state!=CS_DEAD) { if(d->armour) draw_textf("%d", (HICON_X + HICON_STEP + HICON_SIZE + HICON_SPACE)/2, HICON_TEXTY/2, d->armour); draw_textf("%d", (HICON_X + 2*HICON_STEP + HICON_SIZE + HICON_SPACE)/2, HICON_TEXTY/2, d->ammo[d->gunselect]); } glPopMatrix(); drawicon(HICON_HEALTH, HICON_X, HICON_Y); if(d->state!=CS_DEAD) { if(d->armour) drawicon(HICON_BLUE_ARMOUR+d->armourtype, HICON_X + HICON_STEP, HICON_Y); drawicon(HICON_FIST+d->gunselect, HICON_X + 2*HICON_STEP, HICON_Y); if(d->quadmillis) drawicon(HICON_QUAD, HICON_X + 3*HICON_STEP, HICON_Y); if(ammohud) drawammohud(d); } } void gameplayhud(int w, int h) { glPushMatrix(); glScalef(h/1800.0f, h/1800.0f, 1); if(player1->state==CS_SPECTATOR) { int pw, ph, tw, th, fw, fh; text_bounds(" ", pw, ph); text_bounds("SPECTATOR", tw, th); th = max(th, ph); fpsent *f = followingplayer(); text_bounds(f ? colorname(f) : " ", fw, fh); fh = max(fh, ph); draw_text("SPECTATOR", w*1800/h - tw - pw, 1650 - th - fh); if(f) { int color = f->state!=CS_DEAD ? 0xFFFFFF : 0x606060; if(f->privilege) { color = f->privilege>=PRIV_ADMIN ? 0xFF8000 : 0x40FF80; if(f->state==CS_DEAD) color = (color>>1)&0x7F7F7F; } draw_text(colorname(f), w*1800/h - fw - pw, 1650 - fh, (color>>16)&0xFF, (color>>8)&0xFF, color&0xFF); } } fpsent *d = hudplayer(); if(d->state!=CS_EDITING) { if(d->state!=CS_SPECTATOR) drawhudicons(d); if(cmode) cmode->drawhud(d, w, h); } glPopMatrix(); } int clipconsole(int w, int h) { if(cmode) return cmode->clipconsole(w, h); return 0; } VARP(teamcrosshair, 0, 1, 1); VARP(hitcrosshair, 0, 425, 1000); const char *defaultcrosshair(int index) { switch(index) { case 2: return "data/hit.png"; case 1: return "data/teammate.png"; default: return "data/crosshair.png"; } } int selectcrosshair(float &r, float &g, float &b) { fpsent *d = hudplayer(); if(d->state==CS_SPECTATOR || d->state==CS_DEAD) return -1; if(d->state!=CS_ALIVE) return 0; int crosshair = 0; if(lasthit && lastmillis - lasthit < hitcrosshair) crosshair = 2; else if(teamcrosshair) { dynent *o = intersectclosest(d->o, worldpos, d); if(o && o->type==ENT_PLAYER && isteam(((fpsent *)o)->team, d->team)) { crosshair = 1; r = g = 0; } } if(crosshair!=1 && !editmode && !m_insta) { if(d->health<=25) { r = 1.0f; g = b = 0; } else if(d->health<=50) { r = 1.0f; g = 0.5f; b = 0; } } if(d->gunwait) { r *= 0.5f; g *= 0.5f; b *= 0.5f; } return crosshair; } void lighteffects(dynent *e, vec &color, vec &dir) { #if 0 fpsent *d = (fpsent *)e; if(d->state!=CS_DEAD && d->quadmillis) { float t = 0.5f + 0.5f*sinf(2*M_PI*lastmillis/1000.0f); color.y = color.y*(1-t) + t; } #endif } bool serverinfostartcolumn(g3d_gui *g, int i) { static const char *names[] = { "ping ", "players ", "mode ", "map ", "time ", "master ", "host ", "port ", "description " }; static const float struts[] = { 7, 7, 12.5f, 14, 7, 8, 14, 7, 24.5f }; if(size_t(i) >= sizeof(names)/sizeof(names[0])) return false; g->pushlist(); g->text(names[i], 0xFFFF80, !i ? " " : NULL); if(struts[i]) g->strut(struts[i]); g->mergehits(true); return true; } void serverinfoendcolumn(g3d_gui *g, int i) { g->mergehits(false); g->column(i); g->poplist(); } const char *mastermodecolor(int n, const char *unknown) { return (n>=MM_START && size_t(n-MM_START)=MM_START && size_t(n-MM_START) &attr, int np) { if(ping < 0 || attr.empty() || attr[0]!=PROTOCOL_VERSION) { switch(i) { case 0: if(g->button(" ", 0xFFFFDD, "serverunk")&G3D_UP) return true; break; case 1: case 2: case 3: case 4: case 5: if(g->button(" ", 0xFFFFDD)&G3D_UP) return true; break; case 6: if(g->buttonf("%s ", 0xFFFFDD, NULL, name)&G3D_UP) return true; break; case 7: if(g->buttonf("%d ", 0xFFFFDD, NULL, port)&G3D_UP) return true; break; case 8: if(ping < 0) { if(g->button(sdesc, 0xFFFFDD)&G3D_UP) return true; } else if(g->buttonf("[%s protocol] ", 0xFFFFDD, NULL, attr.empty() ? "unknown" : (attr[0] < PROTOCOL_VERSION ? "older" : "newer"))&G3D_UP) return true; break; } return false; } switch(i) { case 0: { const char *icon = attr.inrange(3) && np >= attr[3] ? "serverfull" : (attr.inrange(4) ? mastermodeicon(attr[4], "serverunk") : "serverunk"); if(g->buttonf("%d ", 0xFFFFDD, icon, ping)&G3D_UP) return true; break; } case 1: if(attr.length()>=4) { if(g->buttonf(np >= attr[3] ? "\f3%d/%d " : "%d/%d ", 0xFFFFDD, NULL, np, attr[3])&G3D_UP) return true; } else if(g->buttonf("%d ", 0xFFFFDD, NULL, np)&G3D_UP) return true; break; case 2: if(g->buttonf("%s ", 0xFFFFDD, NULL, attr.length()>=2 ? server::modename(attr[1], "") : "")&G3D_UP) return true; break; case 3: if(g->buttonf("%.25s ", 0xFFFFDD, NULL, map)&G3D_UP) return true; break; case 4: if(attr.length()>=3 && attr[2] > 0) { int secs = clamp(attr[2], 0, 59*60+59), mins = secs/60; secs %= 60; if(g->buttonf("%d:%02d ", 0xFFFFDD, NULL, mins, secs)&G3D_UP) return true; } else if(g->buttonf(" ", 0xFFFFDD)&G3D_UP) return true; break; case 5: if(g->buttonf("%s%s ", 0xFFFFDD, NULL, attr.length()>=5 ? mastermodecolor(attr[4], "") : "", attr.length()>=5 ? server::mastermodename(attr[4], "") : "")&G3D_UP) return true; break; case 6: if(g->buttonf("%s ", 0xFFFFDD, NULL, name)&G3D_UP) return true; break; case 7: if(g->buttonf("%d ", 0xFFFFDD, NULL, port)&G3D_UP) return true; break; case 8: if(g->buttonf("%.25s", 0xFFFFDD, NULL, sdesc)&G3D_UP) return true; break; } return false; } // any data written into this vector will get saved with the map data. Must take care to do own versioning, and endianess if applicable. Will not get called when loading maps from other games, so provide defaults. void writegamedata(vector &extras) {} void readgamedata(vector &extras) {} const char *savedconfig() { return "config.cfg"; } const char *restoreconfig() { return "restore.cfg"; } const char *defaultconfig() { return "data/defaults.cfg"; } const char *autoexec() { return "autoexec.cfg"; } const char *savedservers() { return "servers.cfg"; } void loadconfigs() { execfile("auth.cfg", false); } } sauerbraten-0.0.20130203.dfsg/fpsgame/extinfo.h0000644000175000017500000001125212064164321020644 0ustar vincentvincent #define EXT_ACK -1 #define EXT_VERSION 105 #define EXT_NO_ERROR 0 #define EXT_ERROR 1 #define EXT_PLAYERSTATS_RESP_IDS -10 #define EXT_PLAYERSTATS_RESP_STATS -11 #define EXT_UPTIME 0 #define EXT_PLAYERSTATS 1 #define EXT_TEAMSCORE 2 /* Client: ----- A: 0 EXT_UPTIME B: 0 EXT_PLAYERSTATS cn #a client number or -1 for all players# C: 0 EXT_TEAMSCORE Server: -------- A: 0 EXT_UPTIME EXT_ACK EXT_VERSION uptime #in seconds# B: 0 EXT_PLAYERSTATS cn #send by client# EXT_ACK EXT_VERSION 0 or 1 #error, if cn was > -1 and client does not exist# ... EXT_PLAYERSTATS_RESP_IDS pid(s) #1 packet# EXT_PLAYERSTATS_RESP_STATS pid playerdata #1 packet for each player# C: 0 EXT_TEAMSCORE EXT_ACK EXT_VERSION 0 or 1 #error, no teammode# remaining_time gamemode loop(teamdata [numbases bases] or -1) Errors: -------------- B:C:default: 0 command EXT_ACK EXT_VERSION EXT_ERROR */ void extinfoplayer(ucharbuf &p, clientinfo *ci) { ucharbuf q = p; putint(q, EXT_PLAYERSTATS_RESP_STATS); // send player stats following putint(q, ci->clientnum); //add player id putint(q, ci->ping); sendstring(ci->name, q); sendstring(ci->team, q); putint(q, ci->state.frags); putint(q, ci->state.flags); putint(q, ci->state.deaths); putint(q, ci->state.teamkills); putint(q, ci->state.damage*100/max(ci->state.shotdamage,1)); putint(q, ci->state.health); putint(q, ci->state.armour); putint(q, ci->state.gunselect); putint(q, ci->privilege); putint(q, ci->state.state); uint ip = getclientip(ci->clientnum); q.put((uchar*)&ip, 3); sendserverinforeply(q); } static inline void extinfoteamscore(ucharbuf &p, const char *team, int score) { sendstring(team, p); putint(p, score); if(!smode || !smode->extinfoteam(team, p)) putint(p,-1); //no bases follow } void extinfoteams(ucharbuf &p) { putint(p, m_teammode ? 0 : 1); putint(p, gamemode); putint(p, max((gamelimit - gamemillis)/1000, 0)); if(!m_teammode) return; vector scores; if(smode && smode->hidefrags()) smode->getteamscores(scores); loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.state!=CS_SPECTATOR && ci->team[0] && scores.htfind(ci->team) < 0) { if(smode && smode->hidefrags()) scores.add(teamscore(ci->team, 0)); else { teaminfo *ti = teaminfos.access(ci->team); scores.add(teamscore(ci->team, ti ? ti->frags : 0)); } } } loopv(scores) extinfoteamscore(p, scores[i].team, scores[i].score); } void extserverinforeply(ucharbuf &req, ucharbuf &p) { int extcmd = getint(req); // extended commands //Build a new packet putint(p, EXT_ACK); //send ack putint(p, EXT_VERSION); //send version of extended info switch(extcmd) { case EXT_UPTIME: { putint(p, totalsecs); //in seconds break; } case EXT_PLAYERSTATS: { int cn = getint(req); //a special player, -1 for all clientinfo *ci = NULL; if(cn >= 0) { loopv(clients) if(clients[i]->clientnum == cn) { ci = clients[i]; break; } if(!ci) { putint(p, EXT_ERROR); //client requested by id was not found sendserverinforeply(p); return; } } putint(p, EXT_NO_ERROR); //so far no error can happen anymore ucharbuf q = p; //remember buffer position putint(q, EXT_PLAYERSTATS_RESP_IDS); //send player ids following if(ci) putint(q, ci->clientnum); else loopv(clients) putint(q, clients[i]->clientnum); sendserverinforeply(q); if(ci) extinfoplayer(p, ci); else loopv(clients) extinfoplayer(p, clients[i]); return; } case EXT_TEAMSCORE: { extinfoteams(p); break; } default: { putint(p, EXT_ERROR); break; } } sendserverinforeply(p); } sauerbraten-0.0.20130203.dfsg/fpsgame/ai.h0000644000175000017500000002335612012724622017570 0ustar vincentvincentstruct fpsent; #define MAXBOTS 32 enum { AI_NONE = 0, AI_BOT, AI_MAX }; #define isaitype(a) (a >= 0 && a <= AI_MAX-1) namespace ai { const int MAXWAYPOINTS = USHRT_MAX - 2; const int MAXWAYPOINTLINKS = 6; const int WAYPOINTRADIUS = 16; const float MINWPDIST = 4.f; // is on top of const float CLOSEDIST = 32.f; // is close const float FARDIST = 128.f; // too far to remap close const float JUMPMIN = 4.f; // decides to jump const float JUMPMAX = 32.f; // max jump const float SIGHTMIN = 64.f; // minimum line of sight const float SIGHTMAX = 1024.f; // maximum line of sight const float VIEWMIN = 90.f; // minimum field of view const float VIEWMAX = 180.f; // maximum field of view struct waypoint { vec o; float curscore, estscore; int weight; ushort route, prev; ushort links[MAXWAYPOINTLINKS]; waypoint() {} waypoint(const vec &o, int weight = 0) : o(o), weight(weight), route(0) { memset(links, 0, sizeof(links)); } int score() const { return int(curscore) + int(estscore); } int find(int wp) { loopi(MAXWAYPOINTLINKS) if(links[i] == wp) return i; return -1; } bool haslinks() { return links[0]!=0; } }; extern vector waypoints; static inline bool iswaypoint(int n) { return n > 0 && n < waypoints.length(); } extern int showwaypoints, dropwaypoints; extern int closestwaypoint(const vec &pos, float mindist, bool links, fpsent *d = NULL); extern void findwaypointswithin(const vec &pos, float mindist, float maxdist, vector &results); extern void inferwaypoints(fpsent *d, const vec &o, const vec &v, float mindist = ai::CLOSEDIST); struct avoidset { struct obstacle { void *owner; int numwaypoints; float above; obstacle(void *owner, float above = -1) : owner(owner), numwaypoints(0), above(above) {} }; vector obstacles; vector waypoints; void clear() { obstacles.setsize(0); waypoints.setsize(0); } void add(void *owner, float above) { obstacles.add(obstacle(owner, above)); } void add(void *owner, float above, int wp) { if(obstacles.empty() || owner != obstacles.last().owner) add(owner, above); obstacles.last().numwaypoints++; waypoints.add(wp); } void add(avoidset &avoid) { waypoints.put(avoid.waypoints.getbuf(), avoid.waypoints.length()); loopv(avoid.obstacles) { obstacle &o = avoid.obstacles[i]; if(obstacles.empty() || o.owner != obstacles.last().owner) add(o.owner, o.above); obstacles.last().numwaypoints += o.numwaypoints; } } void avoidnear(void *owner, float above, const vec &pos, float limit); #define loopavoid(v, d, body) \ if(!(v).obstacles.empty()) \ { \ int cur = 0; \ loopv((v).obstacles) \ { \ const ai::avoidset::obstacle &ob = (v).obstacles[i]; \ int next = cur + ob.numwaypoints; \ if(ob.owner != d) \ { \ for(; cur < next; cur++) \ { \ int wp = (v).waypoints[cur]; \ body; \ } \ } \ cur = next; \ } \ } bool find(int n, fpsent *d) const { loopavoid(*this, d, { if(wp == n) return true; }); return false; } int remap(fpsent *d, int n, vec &pos, bool retry = false); }; extern bool route(fpsent *d, int node, int goal, vector &route, const avoidset &obstacles, int retries = 0); extern void navigate(); extern void clearwaypoints(bool full = false); extern void seedwaypoints(); extern void loadwaypoints(bool force = false, const char *mname = NULL); extern void savewaypoints(bool force = false, const char *mname = NULL); // ai state information for the owner client enum { AI_S_WAIT = 0, // waiting for next command AI_S_DEFEND, // defend goal target AI_S_PURSUE, // pursue goal target AI_S_INTEREST, // interest in goal entity AI_S_MAX }; enum { AI_T_NODE, AI_T_PLAYER, AI_T_AFFINITY, AI_T_ENTITY, AI_T_MAX }; struct interest { int state, node, target, targtype; float score; interest() : state(-1), node(-1), target(-1), targtype(-1), score(0.f) {} ~interest() {} }; struct aistate { int type, millis, targtype, target, idle; bool override; aistate(int m, int t, int r = -1, int v = -1) : type(t), millis(m), targtype(r), target(v) { reset(); } ~aistate() {} void reset() { idle = 0; override = false; } }; const int NUMPREVNODES = 6; struct aiinfo { vector state; vector route; vec target, spot; int enemy, enemyseen, enemymillis, weappref, prevnodes[NUMPREVNODES], targnode, targlast, targtime, targseq, lastrun, lasthunt, lastaction, lastcheck, jumpseed, jumprand, blocktime, huntseq, blockseq, lastaimrnd; float targyaw, targpitch, views[3], aimrnd[3]; bool dontmove, becareful, tryreset, trywipe; aiinfo() { clearsetup(); reset(); loopk(3) views[k] = 0.f; } ~aiinfo() {} void clearsetup() { weappref = GUN_PISTOL; spot = target = vec(0, 0, 0); lastaction = lasthunt = lastcheck = enemyseen = enemymillis = blocktime = huntseq = blockseq = targtime = targseq = lastaimrnd = 0; lastrun = jumpseed = lastmillis; jumprand = lastmillis+5000; targnode = targlast = enemy = -1; } void clear(bool prev = false) { if(prev) memset(prevnodes, -1, sizeof(prevnodes)); route.setsize(0); } void wipe(bool prev = false) { clear(prev); state.setsize(0); addstate(AI_S_WAIT); trywipe = false; } void clean(bool tryit = false) { if(!tryit) becareful = dontmove = false; targyaw = rnd(360); targpitch = 0.f; tryreset = tryit; } void reset(bool tryit = false) { wipe(); clean(tryit); } bool hasprevnode(int n) const { loopi(NUMPREVNODES) if(prevnodes[i] == n) return true; return false; } void addprevnode(int n) { if(prevnodes[0] != n) { memmove(&prevnodes[1], prevnodes, sizeof(prevnodes) - sizeof(prevnodes[0])); prevnodes[0] = n; } } aistate &addstate(int t, int r = -1, int v = -1) { return state.add(aistate(lastmillis, t, r, v)); } void removestate(int index = -1) { if(index < 0) state.pop(); else if(state.inrange(index)) state.remove(index); if(!state.length()) addstate(AI_S_WAIT); } aistate &getstate(int idx = -1) { if(state.inrange(idx)) return state[idx]; return state.last(); } aistate &switchstate(aistate &b, int t, int r = -1, int v = -1) { if((b.type == t && b.targtype == r) || (b.type == AI_S_INTEREST && b.targtype == AI_T_NODE)) { b.millis = lastmillis; b.target = v; b.reset(); return b; } return addstate(t, r, v); } }; extern avoidset obstacles; extern vec aitarget; extern float viewdist(int x = 101); extern float viewfieldx(int x = 101); extern float viewfieldy(int x = 101); extern bool targetable(fpsent *d, fpsent *e); extern bool cansee(fpsent *d, vec &x, vec &y, vec &targ = aitarget); extern void init(fpsent *d, int at, int on, int sk, int bn, int pm, const char *name, const char *team); extern void update(); extern void avoid(); extern void think(fpsent *d, bool run); extern bool badhealth(fpsent *d); extern bool checkothers(vector &targets, fpsent *d = NULL, int state = -1, int targtype = -1, int target = -1, bool teams = false, int *members = NULL); extern bool makeroute(fpsent *d, aistate &b, int node, bool changed = true, int retries = 0); extern bool makeroute(fpsent *d, aistate &b, const vec &pos, bool changed = true, int retries = 0); extern bool randomnode(fpsent *d, aistate &b, const vec &pos, float guard = SIGHTMIN, float wander = SIGHTMAX); extern bool randomnode(fpsent *d, aistate &b, float guard = SIGHTMIN, float wander = SIGHTMAX); extern bool violence(fpsent *d, aistate &b, fpsent *e, int pursue = 0); extern bool patrol(fpsent *d, aistate &b, const vec &pos, float guard = SIGHTMIN, float wander = SIGHTMAX, int walk = 1, bool retry = false); extern bool defend(fpsent *d, aistate &b, const vec &pos, float guard = SIGHTMIN, float wander = SIGHTMAX, int walk = 1); extern void assist(fpsent *d, aistate &b, vector &interests, bool all = false, bool force = false); extern bool parseinterests(fpsent *d, aistate &b, vector &interests, bool override = false, bool ignore = false); extern void spawned(fpsent *d); extern void damaged(fpsent *d, fpsent *e); extern void killed(fpsent *d, fpsent *e); extern void itemspawned(int ent); extern void render(); } sauerbraten-0.0.20130203.dfsg/fpsgame/ctf.h0000644000175000017500000012041512073125552017751 0ustar vincentvincent#ifndef PARSEMESSAGES #define ctfteamflag(s) (!strcmp(s, "good") ? 1 : (!strcmp(s, "evil") ? 2 : 0)) #define ctfflagteam(i) (i==1 ? "good" : (i==2 ? "evil" : NULL)) #ifdef SERVMODE VAR(ctftkpenalty, 0, 1, 1); struct ctfservmode : servmode #else struct ctfclientmode : clientmode #endif { static const int BASERADIUS = 64; static const int BASEHEIGHT = 24; static const int MAXFLAGS = 20; static const int FLAGRADIUS = 16; static const int FLAGLIMIT = 10; static const int MAXHOLDSPAWNS = 100; static const int HOLDSECS = 20; static const int HOLDFLAGS = 1; static const int RESPAWNSECS = 5; struct flag { int id, version, spawnindex; vec droploc, spawnloc; int team, droptime, owntime; #ifdef SERVMODE int owner, dropcount, dropper, invistime; #else fpsent *owner; float dropangle, spawnangle; entitylight light; vec interploc; float interpangle; int interptime, vistime; #endif flag() { reset(); } void reset() { version = 0; spawnindex = -1; droploc = spawnloc = vec(0, 0, 0); #ifdef SERVMODE dropcount = 0; owner = dropper = -1; invistime = owntime = 0; #else loopv(players) players[i]->flagpickup &= ~(1<o).sub(owner->eyeheight); if(droptime) return droploc; return spawnloc; } #endif }; struct holdspawn { vec o; #ifndef SERVMODE entitylight light; #endif }; vector holdspawns; vector flags; int scores[2]; void resetflags() { holdspawns.shrink(0); flags.shrink(0); loopk(2) scores[k] = 0; } #ifdef SERVMODE bool addflag(int i, const vec &o, int team, int invistime = 0) #else bool addflag(int i, const vec &o, int team, int vistime = -1000) #endif { if(i<0 || i>=MAXFLAGS) return false; while(flags.length()<=i) flags.add(); flag &f = flags[i]; f.reset(); f.id = i; f.team = team; f.spawnloc = o; #ifdef SERVMODE f.invistime = invistime; #else f.vistime = vistime; #endif return true; } #ifdef SERVMODE bool addholdspawn(const vec &o) #else bool addholdspawn(const vec &o) #endif { if(holdspawns.length() >= MAXHOLDSPAWNS) return false; holdspawn &h = holdspawns.add(); h.o = o; return true; } #ifdef SERVMODE void ownflag(int i, int owner, int owntime) #else void ownflag(int i, fpsent *owner, int owntime) #endif { flag &f = flags[i]; f.owner = owner; f.owntime = owntime; #ifdef SERVMODE if(owner == f.dropper) { if(f.dropcount < INT_MAX) f.dropcount++; } else f.dropcount = 0; f.dropper = -1; f.invistime = 0; #else loopv(players) players[i]->flagpickup &= ~(1<flagpickup &= ~(1<flagpickup &= ~(1<= 1 && team <= 2 ? scores[team-1] : 0; } int setscore(int team, int score) { if(team >= 1 && team <= 2) return scores[team-1] = score; return 0; } int addscore(int team, int score) { if(team >= 1 && team <= 2) return scores[team-1] += score; return 0; } bool hidefrags() { return true; } int getteamscore(const char *team) { return totalscore(ctfteamflag(team)); } void getteamscores(vector &tscores) { loopk(2) if(scores[k]) tscores.add(teamscore(ctfflagteam(k+1), scores[k])); } bool insidebase(const flag &f, const vec &o) { float dx = (f.spawnloc.x-o.x), dy = (f.spawnloc.y-o.y), dz = (f.spawnloc.z-o.z); return dx*dx + dy*dy <= BASERADIUS*BASERADIUS && fabs(dz) <= BASEHEIGHT; } #ifdef SERVMODE static const int RESETFLAGTIME = 10000; static const int INVISFLAGTIME = 20000; bool notgotflags; ctfservmode() : notgotflags(false) {} void reset(bool empty) { resetflags(); notgotflags = !empty; } void cleanup() { reset(false); } void setupholdspawns() { if(!m_hold || holdspawns.empty()) return; while(flags.length() < HOLDFLAGS) { int i = flags.length(); if(!addflag(i, vec(0, 0, 0), 0, 0)) break; flag &f = flags[i]; spawnflag(i); sendf(-1, 1, "ri6", N_RESETFLAG, i, ++f.version, f.spawnindex, 0, 0); } } void setup() { reset(false); if(notgotitems || ments.empty()) return; if(m_hold) { loopv(ments) { entity &e = ments[i]; if(e.type != BASE) continue; if(!addholdspawn(e.o)) break; } setupholdspawns(); } else loopv(ments) { entity &e = ments[i]; if(e.type != FLAG || e.attr2 < 1 || e.attr2 > 2) continue; if(!addflag(flags.length(), e.o, e.attr2, m_protect ? lastmillis : 0)) break; } notgotflags = false; } void newmap() { reset(true); } void dropflag(clientinfo *ci, clientinfo *dropper = NULL) { if(notgotflags) return; loopv(flags) if(flags[i].owner==ci->clientnum) { flag &f = flags[i]; if(m_protect && insidebase(f, ci->state.o)) { returnflag(i); sendf(-1, 1, "ri4", N_RETURNFLAG, ci->clientnum, i, ++f.version); } else { ivec o(vec(ci->state.o).mul(DMF)); sendf(-1, 1, "ri7", N_DROPFLAG, ci->clientnum, i, ++f.version, o.x, o.y, o.z); dropflag(i, o.tovec().div(DMF), lastmillis, dropper ? dropper->clientnum : ci->clientnum, dropper && dropper!=ci); } } } void leavegame(clientinfo *ci, bool disconnecting = false) { dropflag(ci); loopv(flags) if(flags[i].dropper == ci->clientnum) { flags[i].dropper = -1; flags[i].dropcount = 0; } } void died(clientinfo *ci, clientinfo *actor) { dropflag(ci, ctftkpenalty && actor && actor != ci && isteam(actor->team, ci->team) ? actor : NULL); loopv(flags) if(flags[i].dropper == ci->clientnum) { flags[i].dropper = -1; flags[i].dropcount = 0; } } bool canspawn(clientinfo *ci, bool connecting) { return m_efficiency || !m_protect ? connecting || !ci->state.lastdeath || gamemillis+curtime-ci->state.lastdeath >= RESPAWNSECS*1000 : true; } bool canchangeteam(clientinfo *ci, const char *oldteam, const char *newteam) { return ctfteamflag(newteam) > 0; } void changeteam(clientinfo *ci, const char *oldteam, const char *newteam) { dropflag(ci); } void spawnflag(int i) { if(holdspawns.empty()) return; int spawnindex = flags[i].spawnindex; loopj(4) { spawnindex = rnd(holdspawns.length()); if(spawnindex != flags[i].spawnindex) break; } flags[i].spawnindex = spawnindex; } void scoreflag(clientinfo *ci, int goal, int relay = -1) { returnflag(relay >= 0 ? relay : goal, m_protect ? lastmillis : 0); ci->state.flags++; int team = ctfteamflag(ci->team), score = addscore(team, 1); if(m_hold) spawnflag(goal); sendf(-1, 1, "rii9", N_SCOREFLAG, ci->clientnum, relay, relay >= 0 ? ++flags[relay].version : -1, goal, ++flags[goal].version, flags[goal].spawnindex, team, score, ci->state.flags); if(score >= FLAGLIMIT) startintermission(); } void takeflag(clientinfo *ci, int i, int version) { if(notgotflags || !flags.inrange(i) || ci->state.state!=CS_ALIVE || !ci->team[0]) return; flag &f = flags[i]; if((m_hold ? f.spawnindex < 0 : !ctfflagteam(f.team)) || f.owner>=0 || f.version != version || (f.droptime && f.dropper == ci->clientnum && f.dropcount >= 1)) return; int team = ctfteamflag(ci->team); if(m_hold || m_protect == (f.team==team)) { loopvj(flags) if(flags[j].owner==ci->clientnum) return; ownflag(i, ci->clientnum, lastmillis); sendf(-1, 1, "ri4", N_TAKEFLAG, ci->clientnum, i, ++f.version); } else if(m_protect) { if(!f.invistime) scoreflag(ci, i); } else if(f.droptime) { returnflag(i); sendf(-1, 1, "ri4", N_RETURNFLAG, ci->clientnum, i, ++f.version); } else { loopvj(flags) if(flags[j].owner==ci->clientnum) { scoreflag(ci, i, j); break; } } } void update() { if(gamemillis>=gamelimit || notgotflags) return; loopv(flags) { flag &f = flags[i]; if(f.owner<0 && f.droptime && lastmillis - f.droptime >= RESETFLAGTIME) { returnflag(i, m_protect ? lastmillis : 0); if(m_hold) spawnflag(i); sendf(-1, 1, "ri6", N_RESETFLAG, i, ++f.version, f.spawnindex, m_hold ? 0 : f.team, m_hold ? 0 : addscore(f.team, m_protect ? -1 : 0)); } if(f.invistime && lastmillis - f.invistime >= INVISFLAGTIME) { f.invistime = 0; sendf(-1, 1, "ri3", N_INVISFLAG, i, 0); } if(m_hold && f.owner>=0 && lastmillis - f.owntime >= HOLDSECS*1000) { clientinfo *ci = getinfo(f.owner); if(ci) scoreflag(ci, i); else { spawnflag(i); sendf(-1, 1, "ri6", N_RESETFLAG, i, ++f.version, f.spawnindex, 0, 0); } } } } void initclient(clientinfo *ci, packetbuf &p, bool connecting) { putint(p, N_INITFLAGS); loopk(2) putint(p, scores[k]); putint(p, flags.length()); loopv(flags) { flag &f = flags[i]; putint(p, f.version); putint(p, f.spawnindex); putint(p, f.owner); putint(p, f.invistime ? 1 : 0); if(f.owner<0) { putint(p, f.droptime ? 1 : 0); if(f.droptime) { putint(p, int(f.droploc.x*DMF)); putint(p, int(f.droploc.y*DMF)); putint(p, int(f.droploc.z*DMF)); } } } } void parseflags(ucharbuf &p, bool commit) { int numflags = getint(p); loopi(numflags) { int team = getint(p); vec o; loopk(3) o[k] = max(getint(p)/DMF, 0.0f); if(p.overread()) break; if(commit && notgotflags) { if(m_hold) addholdspawn(o); else addflag(i, o, team, m_protect ? lastmillis : 0); } } if(commit && notgotflags) { if(m_hold) setupholdspawns(); notgotflags = false; } } }; #else void preload() { if(m_hold) preloadmodel("flags/neutral"); else { preloadmodel("flags/red"); preloadmodel("flags/blue"); } static const int sounds[] = { S_FLAGPICKUP, S_FLAGDROP, S_FLAGRETURN, S_FLAGSCORE, S_FLAGRESET, S_FLAGFAIL }; loopi(sizeof(sounds)/sizeof(sounds[0])) preloadsound(sounds[i]); } void drawblip(fpsent *d, float x, float y, float s, const vec &pos, bool flagblip) { float scale = calcradarscale(); vec dir = d->o; dir.sub(pos).div(scale); float size = flagblip ? 0.1f : 0.05f, xoffset = flagblip ? -2*(3/32.0f)*size : -size, yoffset = flagblip ? -2*(1 - 3/32.0f)*size : -size, dist = dir.magnitude2(), maxdist = 1 - 0.05f - 0.05f; if(dist >= maxdist) dir.mul(maxdist/dist); dir.rotate_around_z(-camera1->yaw*RAD); drawradar(x + s*0.5f*(1.0f + dir.x + xoffset), y + s*0.5f*(1.0f + dir.y + yoffset), size*s); } void drawblip(fpsent *d, float x, float y, float s, int i, bool flagblip) { flag &f = flags[i]; settexture(m_hold && (!flagblip || !f.owner || lastmillis%1000 < 500) ? (flagblip ? "packages/hud/blip_neutral_flag.png" : "packages/hud/blip_neutral.png") : ((m_hold ? ctfteamflag(f.owner->team) : f.team)==ctfteamflag(player1->team) ? (flagblip ? "packages/hud/blip_blue_flag.png" : "packages/hud/blip_blue.png") : (flagblip ? "packages/hud/blip_red_flag.png" : "packages/hud/blip_red.png")), 3); drawblip(d, x, y, s, flagblip ? (f.owner ? f.owner->o : (f.droptime ? f.droploc : f.spawnloc)) : f.spawnloc, flagblip); } int clipconsole(int w, int h) { return (h*(1 + 1 + 10))/(4*10); } void drawhud(fpsent *d, int w, int h) { if(d->state == CS_ALIVE) { loopv(flags) if(flags[i].owner == d) { int x = HICON_X + 3*HICON_STEP + (d->quadmillis ? HICON_SIZE + HICON_SPACE : 0); drawicon(m_hold ? HICON_NEUTRAL_FLAG : (flags[i].team==ctfteamflag(player1->team) ? HICON_BLUE_FLAG : HICON_RED_FLAG), x, HICON_Y); if(m_hold) { glPushMatrix(); glScalef(2, 2, 1); draw_textf("%d", (x + HICON_SIZE + HICON_SPACE)/2, HICON_TEXTY/2, max(HOLDSECS - (lastmillis - flags[i].owntime)/1000, 0)); glPopMatrix(); } break; } } glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int s = 1800/4, x = 1800*w/h - s - s/10, y = s/10; glColor4f(1, 1, 1, minimapalpha); if(minimapalpha >= 1) glDisable(GL_BLEND); bindminimap(); drawminimap(d, x, y, s); if(minimapalpha >= 1) glEnable(GL_BLEND); glColor3f(1, 1, 1); float margin = 0.04f, roffset = s*margin, rsize = s + 2*roffset; settexture("packages/hud/radar.png", 3); drawradar(x - roffset, y - roffset, rsize); #if 0 settexture("packages/hud/compass.png", 3); glPushMatrix(); glTranslatef(x - roffset + 0.5f*rsize, y - roffset + 0.5f*rsize, 0); glRotatef(camera1->yaw + 180, 0, 0, -1); drawradar(-0.5f*rsize, -0.5f*rsize, rsize); glPopMatrix(); #endif if(m_hold) { settexture("packages/hud/blip_neutral.png", 3); loopv(holdspawns) drawblip(d, x, y, s, holdspawns[i].o, false); } loopv(flags) { flag &f = flags[i]; if(m_hold ? f.spawnindex < 0 : !ctfflagteam(f.team)) continue; if(!m_hold) drawblip(d, x, y, s, i, false); if(f.owner) { if(!m_hold && lastmillis%1000 >= 500) continue; } else if(f.droptime && (f.droploc.x < 0 || lastmillis%300 >= 150)) continue; drawblip(d, x, y, s, i, true); } drawteammates(d, x, y, s); if(d->state == CS_DEAD && (m_efficiency || !m_protect)) { int wait = respawnwait(d); if(wait>=0) { glPushMatrix(); glScalef(2, 2, 1); bool flash = wait>0 && d==player1 && lastspawnattempt>=d->lastpain && lastmillis < lastspawnattempt+100; draw_textf("%s%d", (x+s/2)/2-(wait>=10 ? 28 : 16), (y+s/2)/2-32, flash ? "\f3" : "", wait); glPopMatrix(); } } } void removeplayer(fpsent *d) { loopv(flags) if(flags[i].owner == d) { flag &f = flags[i]; f.interploc.x = -1; f.interptime = 0; dropflag(i, f.owner->o, f.owner->yaw, 1); } } vec interpflagpos(flag &f, float &angle) { vec pos = f.owner ? vec(f.owner->abovehead()).add(vec(0, 0, 1)) : (f.droptime ? f.droploc : f.spawnloc); if(f.owner) angle = f.owner->yaw; else if(m_hold) { float yaw, pitch; vectoyawpitch(vec(pos).sub(camera1->o), yaw, pitch); angle = yaw + 180; } else angle = f.droptime ? f.dropangle : f.spawnangle; if(pos.x < 0) return pos; if(f.interptime && f.interploc.x >= 0) { float t = min((lastmillis - f.interptime)/500.0f, 1.0f); pos.lerp(f.interploc, pos, t); angle += (1-t)*(f.interpangle - angle); } return pos; } vec interpflagpos(flag &f) { float angle; return interpflagpos(f, angle); } void rendergame() { loopv(flags) { flag &f = flags[i]; if(!f.owner && f.droptime && f.droploc.x < 0) continue; if(m_hold && f.spawnindex < 0) continue; const char *flagname = m_hold && (!f.owner || lastmillis%1000 < 500) ? "flags/neutral" : (m_hold ? ctfteamflag(f.owner->team) : f.team)==ctfteamflag(player1->team) ? "flags/blue" : "flags/red"; float angle; vec pos = interpflagpos(f, angle); if(m_hold) rendermodel(!f.droptime && !f.owner ? &f.light : NULL, flagname, ANIM_MAPMODEL|ANIM_LOOP, pos, angle, 0, MDL_GHOST | MDL_CULL_VFC | (f.droptime || f.owner ? MDL_LIGHT : 0), NULL, NULL, 0, 0, 0.5f + 0.5f*(2*fabs(fmod(lastmillis/1000.0f, 1.0f) - 0.5f))); rendermodel(!f.droptime && !f.owner ? &f.light : NULL, flagname, ANIM_MAPMODEL|ANIM_LOOP, pos, angle, 0, MDL_DYNSHADOW | MDL_CULL_VFC | MDL_CULL_OCCLUDED | (f.droptime || f.owner ? MDL_LIGHT : 0), NULL, NULL, 0, 0, 0.3f + (f.vistime ? 0.7f*min((lastmillis - f.vistime)/1000.0f, 1.0f) : 0.0f)); if(m_protect && canaddparticles() && f.owner && insidebase(f, f.owner->feetpos())) { particle_flare(pos, f.spawnloc, 0, PART_LIGHTNING, strcmp(f.owner->team, player1->team) ? 0xFF2222 : 0x2222FF, 1.0f); if(!flags.inrange(f.owner->lastbase)) { particle_fireball(pos, 4.8f, PART_EXPLOSION, 250, strcmp(f.owner->team, player1->team) ? 0x802020 : 0x2020FF, 4.8f); particle_splash(PART_SPARK, 50, 250, pos, strcmp(f.owner->team, player1->team) ? 0x802020 : 0x2020FF, 0.24f); } f.owner->lastbase = i; } } if(m_protect && canaddparticles()) loopv(players) { fpsent *d = players[i]; if(!flags.inrange(d->lastbase)) continue; flag &f = flags[d->lastbase]; if(f.owner == d && insidebase(f, d->feetpos())) continue; d->lastbase = -1; float angle; vec pos = interpflagpos(f, angle); particle_fireball(pos, 4.8f, PART_EXPLOSION, 250, strcmp(d->team, player1->team) ? 0x802020 : 0x2020FF, 4.8f); particle_splash(PART_SPARK, 50, 250, pos, strcmp(d->team, player1->team) ? 0x802020 : 0x2020FF, 0.24f); } } void setup() { resetflags(); if(m_hold) { loopv(entities::ents) { extentity *e = entities::ents[i]; if(e->type!=BASE) continue; if(!addholdspawn(e->o)) continue; holdspawns.last().light = e->light; } if(holdspawns.length()) while(flags.length() < HOLDFLAGS) addflag(flags.length(), vec(0, 0, 0), 0, -1000); } else { loopv(entities::ents) { extentity *e = entities::ents[i]; if(e->type!=FLAG) continue; if(e->attr2<1 || e->attr2>2) continue; int index = flags.length(); if(!addflag(index, e->o, e->attr2, m_protect ? 0 : -1000)) continue; flags[index].spawnangle = e->attr1; flags[index].light = e->light; } } } void senditems(packetbuf &p) { putint(p, N_INITFLAGS); if(m_hold) { putint(p, holdspawns.length()); loopv(holdspawns) { holdspawn &h = holdspawns[i]; putint(p, -1); loopk(3) putint(p, int(h.o[k]*DMF)); } } else { putint(p, flags.length()); loopv(flags) { flag &f = flags[i]; putint(p, f.team); loopk(3) putint(p, int(f.spawnloc[k]*DMF)); } } } void parseflags(ucharbuf &p, bool commit) { loopk(2) { int score = getint(p); if(commit) scores[k] = score; } int numflags = getint(p); loopi(numflags) { int version = getint(p), spawn = getint(p), owner = getint(p), invis = getint(p), dropped = 0; vec droploc(0, 0, 0); if(owner<0) { dropped = getint(p); if(dropped) loopk(3) droploc[k] = getint(p)/DMF; } if(commit && flags.inrange(i)) { flag &f = flags[i]; f.version = version; f.spawnindex = spawn; if(m_hold) spawnflag(f); f.owner = owner>=0 ? (owner==player1->clientnum ? player1 : newclient(owner)) : NULL; f.droptime = dropped; f.droploc = dropped ? droploc : f.spawnloc; f.vistime = invis>0 ? 0 : -1000; f.interptime = 0; if(dropped) { f.droploc.z += 4; if(!droptofloor(f.droploc, 4, 0)) f.droploc = vec(-1, -1, -1); } } } } void trydropflag() { if(!m_ctf) return; loopv(flags) if(flags[i].owner == player1) { addmsg(N_TRYDROPFLAG, "rc", player1); return; } } const char *teamcolorflag(flag &f) { return m_hold ? "the flag" : teamcolor("your flag", ctfflagteam(f.team), "the enemy flag"); } void dropflag(fpsent *d, int i, int version, const vec &droploc) { if(!flags.inrange(i)) return; flag &f = flags[i]; f.version = version; f.interploc = interpflagpos(f, f.interpangle); f.interptime = lastmillis; dropflag(i, droploc, d->yaw, 1); f.droploc.z += 4; d->flagpickup |= 1<team)) { fcolor = 0x2020FF; color = vec(0.25f, 0.25f, 1); } else { fcolor = 0x802020; color = vec(1, 0.25f, 0.25f); } particle_fireball(loc, 30, PART_EXPLOSION, -1, fcolor, 4.8f); adddynlight(loc, 35, color, 900, 100); particle_splash(PART_SPARK, 150, 300, loc, fcolor, 0.24f); } void flageffect(int i, int team, const vec &from, const vec &to) { vec fromexp(from), toexp(to); if(from.x >= 0) { fromexp.z += 8; flagexplosion(i, team, fromexp); } if(from==to) return; if(to.x >= 0) { toexp.z += 8; flagexplosion(i, team, toexp); } if(from.x >= 0 && to.x >= 0) particle_flare(fromexp, toexp, 600, PART_LIGHTNING, !team ? 0xFFC0A0 : (team==ctfteamflag(player1->team) ? 0x2222FF : 0xFF2222), 1.0f); } void returnflag(fpsent *d, int i, int version) { if(!flags.inrange(i)) return; flag &f = flags[i]; f.version = version; flageffect(i, f.team, interpflagpos(f), f.spawnloc); f.interptime = 0; returnflag(i); if(m_protect && d->feetpos().dist(f.spawnloc) < FLAGRADIUS) d->flagpickup |= 1<= 0; f.spawnindex = spawnindex; if(m_hold) spawnflag(f); if(shouldeffect) flageffect(i, m_hold ? 0 : team, interpflagpos(f), f.spawnloc); f.interptime = 0; returnflag(i, m_protect ? 0 : -1000); if(shouldeffect) { conoutf(CON_GAMEINFO, "%s reset", teamcolorflag(f)); playsound(S_FLAGRESET); } } void scoreflag(fpsent *d, int relay, int relayversion, int goal, int goalversion, int goalspawn, int team, int score, int dflags) { setscore(team, score); if(flags.inrange(goal)) { flag &f = flags[goal]; f.version = goalversion; f.spawnindex = goalspawn; if(m_hold) spawnflag(f); if(relay >= 0) { flags[relay].version = relayversion; flageffect(goal, team, f.spawnloc, flags[relay].spawnloc); } else flageffect(goal, team, interpflagpos(f), f.spawnloc); f.interptime = 0; returnflag(relay >= 0 ? relay : goal, m_protect ? 0 : -1000); d->flagpickup &= ~(1<feetpos().dist(f.spawnloc) < FLAGRADIUS) d->flagpickup |= 1<abovehead(), ds, PART_TEXT, 2000, 0x32FF64, 4.0f, -8); } d->flags = dflags; conoutf(CON_GAMEINFO, "%s scored for %s", teamcolorname(d), teamcolor("your team", ctfflagteam(team), "the enemy team")); playsound(team==ctfteamflag(player1->team) ? S_FLAGSCORE : S_FLAGFAIL); if(score >= FLAGLIMIT) conoutf(CON_GAMEINFO, "%s captured %d flags", teamcolor("your team", ctfflagteam(team), "the enemy team"), score); } void takeflag(fpsent *d, int i, int version) { if(!flags.inrange(i)) return; flag &f = flags[i]; f.version = version; f.interploc = interpflagpos(f, f.interpangle); f.interptime = lastmillis; if(m_hold) conoutf(CON_GAMEINFO, "%s picked up the flag for %s", teamcolorname(d), teamcolor("your team", d->team, "the enemy team")); else if(m_protect || f.droptime) conoutf(CON_GAMEINFO, "%s picked up %s", teamcolorname(d), teamcolorflag(f)); else conoutf(CON_GAMEINFO, "%s stole %s", teamcolorname(d), teamcolorflag(f)); ownflag(i, d, lastmillis); playsound(S_FLAGPICKUP); } void invisflag(int i, int invis) { if(!flags.inrange(i)) return; flag &f = flags[i]; if(invis>0) f.vistime = 0; else if(!f.vistime) f.vistime = lastmillis; } void checkitems(fpsent *d) { vec o = d->feetpos(); loopv(flags) { flag &f = flags[i]; if((m_hold ? f.spawnindex < 0 : !ctfflagteam(f.team)) || f.owner || (f.droptime && f.droploc.x<0)) continue; const vec &loc = f.droptime ? f.droploc : f.spawnloc; if(o.dist(loc) < FLAGRADIUS) { if(d->flagpickup&(1<flagpickup |= 1<flagpickup &= ~(1<feetpos(); d->flagpickup = 0; loopv(flags) { flag &f = flags[i]; if((m_hold ? f.spawnindex < 0 : !ctfflagteam(f.team)) || f.owner || (f.droptime && f.droploc.x<0)) continue; if(o.dist(f.droptime ? f.droploc : f.spawnloc) < FLAGRADIUS) d->flagpickup |= 1<lastpain)/1000) : 0; } bool pickholdspawn(fpsent *d) { vector spawns; loopv(flags) { flag &f = flags[i]; if(f.spawnindex < 0 || (!f.owner && (!f.droptime || f.droploc.x < 0))) continue; const vec &goal = f.owner ? f.owner->o : f.droploc; extentity *flagspawns[7]; int numflagspawns = 0; memset(flagspawns, 0, sizeof(flagspawns)); loopvj(entities::ents) { extentity *e = entities::ents[j]; if(e->type != PLAYERSTART || e->attr2 != 0) continue; float dist = e->o.dist(goal); loopk(numflagspawns) { float sdist = flagspawns[k]->o.dist(goal); if(dist >= sdist) continue; swap(e, flagspawns[k]); dist = sdist; } if(numflagspawns < int(sizeof(flagspawns)/sizeof(flagspawns[0]))) flagspawns[numflagspawns++] = e; } loopk(numflagspawns) spawns.add(flagspawns[k]); } if(spawns.empty()) return false; int pick = rnd(spawns.length()); d->pitch = 0; d->roll = 0; loopv(spawns) { int attempt = (pick + i)%spawns.length(); d->o = spawns[attempt]->o; d->yaw = spawns[attempt]->attr1; if(entinmap(d, true)) return true; } return false; } void pickspawn(fpsent *d) { if(!m_hold || !pickholdspawn(d)) findplayerspawn(d, -1, m_hold ? 0 : ctfteamflag(d->team)); } bool aihomerun(fpsent *d, ai::aistate &b) { if(m_protect || m_hold) { static vector interests; loopk(2) { interests.setsize(0); ai::assist(d, b, interests, k != 0); if(ai::parseinterests(d, b, interests, false, true)) return true; } } else { vec pos = d->feetpos(); loopk(2) { int goal = -1; loopv(flags) { flag &g = flags[i]; if(g.team == ctfteamflag(d->team) && (k || (!g.owner && !g.droptime)) && (!flags.inrange(goal) || g.pos().squaredist(pos) < flags[goal].pos().squaredist(pos))) { goal = i; } } if(flags.inrange(goal) && ai::makeroute(d, b, flags[goal].pos())) { d->ai->switchstate(b, ai::AI_S_PURSUE, ai::AI_T_AFFINITY, goal); return true; } } } if(b.type == ai::AI_S_INTEREST && b.targtype == ai::AI_T_NODE) return true; // we already did this.. if(randomnode(d, b, ai::SIGHTMIN, 1e16f)) { d->ai->switchstate(b, ai::AI_S_INTEREST, ai::AI_T_NODE, d->ai->route[0]); return true; } return false; } bool aicheck(fpsent *d, ai::aistate &b) { static vector takenflags; takenflags.setsize(0); loopv(flags) { flag &g = flags[i]; if(g.owner == d) return aihomerun(d, b); else if(g.team == ctfteamflag(d->team) && ((g.owner && g.team != ctfteamflag(g.owner->team)) || g.droptime)) takenflags.add(i); } if(!ai::badhealth(d) && !takenflags.empty()) { int flag = takenflags.length() > 2 ? rnd(takenflags.length()) : 0; d->ai->switchstate(b, ai::AI_S_PURSUE, ai::AI_T_AFFINITY, takenflags[flag]); return true; } return false; } void aifind(fpsent *d, ai::aistate &b, vector &interests) { vec pos = d->feetpos(); loopvj(flags) { flag &f = flags[j]; if((!m_protect && !m_hold) || f.owner != d) { static vector targets; // build a list of others who are interested in this targets.setsize(0); bool home = !m_hold && f.team == ctfteamflag(d->team); ai::checkothers(targets, d, home ? ai::AI_S_DEFEND : ai::AI_S_PURSUE, ai::AI_T_AFFINITY, j, true); fpsent *e = NULL; loopi(numdynents()) if((e = (fpsent *)iterdynents(i)) && !e->ai && e->state == CS_ALIVE && isteam(d->team, e->team)) { // try to guess what non ai are doing vec ep = e->feetpos(); if(targets.find(e->clientnum) < 0 && (ep.squaredist(f.pos()) <= (FLAGRADIUS*FLAGRADIUS*4) || f.owner == e)) targets.add(e->clientnum); } if(home) { bool guard = false; if((f.owner && f.team != ctfteamflag(f.owner->team)) || f.droptime || targets.empty()) guard = true; else if(d->hasammo(d->ai->weappref)) { // see if we can relieve someone who only has a piece of crap fpsent *t; loopvk(targets) if((t = getclient(targets[k]))) { if((t->ai && !t->hasammo(t->ai->weappref)) || (!t->ai && (t->gunselect == GUN_FIST || t->gunselect == GUN_PISTOL))) { guard = true; break; } } } if(guard) { // defend the flag ai::interest &n = interests.add(); n.state = ai::AI_S_DEFEND; n.node = ai::closestwaypoint(f.pos(), ai::SIGHTMIN, true); n.target = j; n.targtype = ai::AI_T_AFFINITY; n.score = pos.squaredist(f.pos())/100.f; } } else { if(targets.empty()) { // attack the flag ai::interest &n = interests.add(); n.state = ai::AI_S_PURSUE; n.node = ai::closestwaypoint(f.pos(), ai::SIGHTMIN, true); n.target = j; n.targtype = ai::AI_T_AFFINITY; n.score = pos.squaredist(f.pos()); } else { // help by defending the attacker fpsent *t; loopvk(targets) if((t = getclient(targets[k]))) { ai::interest &n = interests.add(); n.state = ai::AI_S_DEFEND; n.node = t->lastnode; n.target = t->clientnum; n.targtype = ai::AI_T_PLAYER; n.score = d->o.squaredist(t->o); } } } } } } bool aidefend(fpsent *d, ai::aistate &b) { loopv(flags) { flag &g = flags[i]; if(g.owner == d) return aihomerun(d, b); } if(flags.inrange(b.target)) { flag &f = flags[b.target]; if(f.droptime) return ai::makeroute(d, b, f.pos()); if(f.owner) return ai::violence(d, b, f.owner, 4); int walk = 0; if(lastmillis-b.millis >= (201-d->skill)*33) { static vector targets; // build a list of others who are interested in this targets.setsize(0); ai::checkothers(targets, d, ai::AI_S_DEFEND, ai::AI_T_AFFINITY, b.target, true); fpsent *e = NULL; loopi(numdynents()) if((e = (fpsent *)iterdynents(i)) && !e->ai && e->state == CS_ALIVE && isteam(d->team, e->team)) { // try to guess what non ai are doing vec ep = e->feetpos(); if(targets.find(e->clientnum) < 0 && (ep.squaredist(f.pos()) <= (FLAGRADIUS*FLAGRADIUS*4) || f.owner == e)) targets.add(e->clientnum); } if(!targets.empty()) { d->ai->trywipe = true; // re-evaluate so as not to herd return true; } else { walk = 2; b.millis = lastmillis; } } vec pos = d->feetpos(); float mindist = float(FLAGRADIUS*FLAGRADIUS*8); loopv(flags) { // get out of the way of the returnee! flag &g = flags[i]; if(pos.squaredist(g.pos()) <= mindist) { if(!m_protect && !m_hold && g.owner && !strcmp(g.owner->team, d->team)) walk = 1; if(g.droptime && ai::makeroute(d, b, g.pos())) return true; } } return ai::defend(d, b, f.pos(), float(FLAGRADIUS*2), float(FLAGRADIUS*(2+(walk*2))), walk); } return false; } bool aipursue(fpsent *d, ai::aistate &b) { if(flags.inrange(b.target)) { flag &f = flags[b.target]; if(f.owner == d) return aihomerun(d, b); if(!m_hold && f.team == ctfteamflag(d->team)) { if(f.droptime) return ai::makeroute(d, b, f.pos()); if(f.owner) return ai::violence(d, b, f.owner, 4); loopv(flags) { flag &g = flags[i]; if(g.owner == d) return ai::makeroute(d, b, f.pos()); } } else { if(f.owner) return ai::violence(d, b, f.owner, 4); return ai::makeroute(d, b, f.pos()); } } return false; } }; extern ctfclientmode ctfmode; ICOMMAND(dropflag, "", (), { ctfmode.trydropflag(); }); #endif #elif SERVMODE case N_TRYDROPFLAG: { if((ci->state.state!=CS_SPECTATOR || ci->local || ci->privilege) && cq && smode==&ctfmode) ctfmode.dropflag(cq); break; } case N_TAKEFLAG: { int flag = getint(p), version = getint(p); if((ci->state.state!=CS_SPECTATOR || ci->local || ci->privilege) && cq && smode==&ctfmode) ctfmode.takeflag(cq, flag, version); break; } case N_INITFLAGS: if(smode==&ctfmode) ctfmode.parseflags(p, (ci->state.state!=CS_SPECTATOR || ci->privilege || ci->local) && !strcmp(ci->clientmap, smapname)); break; #else case N_INITFLAGS: { ctfmode.parseflags(p, m_ctf); break; } case N_DROPFLAG: { int ocn = getint(p), flag = getint(p), version = getint(p); vec droploc; loopk(3) droploc[k] = getint(p)/DMF; fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); if(o && m_ctf) ctfmode.dropflag(o, flag, version, droploc); break; } case N_SCOREFLAG: { int ocn = getint(p), relayflag = getint(p), relayversion = getint(p), goalflag = getint(p), goalversion = getint(p), goalspawn = getint(p), team = getint(p), score = getint(p), oflags = getint(p); fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); if(o && m_ctf) ctfmode.scoreflag(o, relayflag, relayversion, goalflag, goalversion, goalspawn, team, score, oflags); break; } case N_RETURNFLAG: { int ocn = getint(p), flag = getint(p), version = getint(p); fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); if(o && m_ctf) ctfmode.returnflag(o, flag, version); break; } case N_TAKEFLAG: { int ocn = getint(p), flag = getint(p), version = getint(p); fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); if(o && m_ctf) ctfmode.takeflag(o, flag, version); break; } case N_RESETFLAG: { int flag = getint(p), version = getint(p), spawnindex = getint(p), team = getint(p), score = getint(p); if(m_ctf) ctfmode.resetflag(flag, version, spawnindex, team, score); break; } case N_INVISFLAG: { int flag = getint(p), invis = getint(p); if(m_ctf) ctfmode.invisflag(flag, invis); break; } #endif sauerbraten-0.0.20130203.dfsg/fpsgame/waypoint.cpp0000644000175000017500000006510012070403407021374 0ustar vincentvincent#include "game.h" extern selinfo sel; namespace ai { using namespace game; vector waypoints; bool clipped(const vec &o) { int material = lookupmaterial(o), clipmat = material&MATF_CLIP; return clipmat == MAT_CLIP || material&MAT_DEATH || (material&MATF_VOLUME) == MAT_LAVA; } int getweight(const vec &o) { vec pos = o; pos.z += ai::JUMPMIN; if(!insideworld(vec(pos.x, pos.y, min(pos.z, getworldsize() - 1e-3f)))) return -2; float dist = raycube(pos, vec(0, 0, -1), 0, RAY_CLIPMAT); int posmat = lookupmaterial(pos), weight = 1; if(isliquid(posmat&MATF_VOLUME)) weight *= 5; if(dist >= 0) { weight = int(dist/ai::JUMPMIN); pos.z -= clamp(dist-8.0f, 0.0f, pos.z); int trgmat = lookupmaterial(pos); if(trgmat&MAT_DEATH || (trgmat&MATF_VOLUME) == MAT_LAVA) weight *= 10; else if(isliquid(trgmat&MATF_VOLUME)) weight *= 2; } return weight; } enum { WPCACHE_STATIC = 0, WPCACHE_DYNAMIC, NUMWPCACHES }; struct wpcachenode { float split[2]; uint child[2]; int axis() const { return child[0]>>30; } int childindex(int which) const { return child[which]&0x3FFFFFFF; } bool isleaf(int which) const { return (child[1]&(1<<(30+which)))!=0; } }; struct wpcache { vector nodes; int firstwp, lastwp, maxdepth; vec bbmin, bbmax; wpcache() { clear(); } void clear() { nodes.setsize(0); firstwp = lastwp = -1; maxdepth = -1; bbmin = vec(1e16f, 1e16f, 1e16f); bbmax = vec(-1e16f, -1e16f, -1e16f); } void build(int first = -1, int last = -1) { if(last < 0) last = waypoints.length(); vector indices; for(int i = first; i < last; i++) { waypoint &w = waypoints[i]; indices.add(i); if(firstwp < 0) firstwp = i; float radius = WAYPOINTRADIUS; bbmin.min(vec(w.o).sub(radius)); bbmax.max(vec(w.o).add(radius)); } if(first < last) lastwp = max(lastwp, last-1); build(indices.getbuf(), indices.length(), bbmin, bbmax); } void build(int *indices, int numindices, const vec &vmin, const vec &vmax, int depth = 1) { int axis = 2; loopk(2) if(vmax[k] - vmin[k] > vmax[axis] - vmin[axis]) axis = k; vec leftmin(1e16f, 1e16f, 1e16f), leftmax(-1e16f, -1e16f, -1e16f), rightmin(1e16f, 1e16f, 1e16f), rightmax(-1e16f, -1e16f, -1e16f); float split = 0.5f*(vmax[axis] + vmin[axis]), splitleft = -1e16f, splitright = 1e16f; int left, right; for(left = 0, right = numindices; left < right;) { waypoint &w = waypoints[indices[left]]; float radius = WAYPOINTRADIUS; if(max(split - (w.o[axis]-radius), 0.0f) > max((w.o[axis]+radius) - split, 0.0f)) { ++left; splitleft = max(splitleft, w.o[axis]+radius); leftmin.min(vec(w.o).sub(radius)); leftmax.max(vec(w.o).add(radius)); } else { --right; swap(indices[left], indices[right]); splitright = min(splitright, w.o[axis]-radius); rightmin.min(vec(w.o).sub(radius)); rightmax.max(vec(w.o).add(radius)); } } if(!left || right==numindices) { leftmin = rightmin = vec(1e16f, 1e16f, 1e16f); leftmax = rightmax = vec(-1e16f, -1e16f, -1e16f); left = right = numindices/2; splitleft = -1e16f; splitright = 1e16f; loopi(numindices) { waypoint &w = waypoints[indices[i]]; float radius = WAYPOINTRADIUS; if(i < left) { splitleft = max(splitleft, w.o[axis]+radius); leftmin.min(vec(w.o).sub(radius)); leftmax.max(vec(w.o).add(radius)); } else { splitright = min(splitright, w.o[axis]-radius); rightmin.min(vec(w.o).sub(radius)); rightmax.max(vec(w.o).add(radius)); } } } int node = nodes.length(); nodes.add(); nodes[node].split[0] = splitleft; nodes[node].split[1] = splitright; if(left<=1) nodes[node].child[0] = (axis<<30) | (left>0 ? indices[0] : 0x3FFFFFFF); else { nodes[node].child[0] = (axis<<30) | (nodes.length()-node); if(left) build(indices, left, leftmin, leftmax, depth+1); } if(numindices-right<=1) nodes[node].child[1] = (1<<31) | (left<=1 ? 1<<30 : 0) | (numindices-right>0 ? indices[right] : 0x3FFFFFFF); else { nodes[node].child[1] = (left<=1 ? 1<<30 : 0) | (nodes.length()-node); if(numindices-right) build(&indices[right], numindices-right, rightmin, rightmax, depth+1); } maxdepth = max(maxdepth, depth); } } wpcaches[NUMWPCACHES]; static int invalidatedwpcaches = 0, clearedwpcaches = (1<= 1000) { numinvalidatewpcaches = 0; invalidatedwpcaches = (1<= wpcaches[i].firstwp && wp <= wpcaches[i].lastwp) || i+1 >= NUMWPCACHES) { invalidatedwpcaches |= 1< 0 ? wpcaches[i-1].lastwp+1 : 1, i+1 >= NUMWPCACHES || wpcaches[i+1].maxdepth < 0 ? -1 : wpcaches[i+1].firstwp); clearedwpcaches = 0; lastwpcache = waypoints.length(); wpavoid.clear(); loopv(waypoints) if(waypoints[i].weight < 0) wpavoid.avoidnear(NULL, waypoints[i].o.z + WAYPOINTRADIUS, waypoints[i].o, WAYPOINTRADIUS); } struct wpcachestack { wpcachenode *node; float tmin, tmax; }; vector wpcachestack; int closestwaypoint(const vec &pos, float mindist, bool links, fpsent *d) { if(waypoints.empty()) return -1; if(clearedwpcaches) buildwpcache(); #define CHECKCLOSEST(index) do { \ int n = (index); \ const waypoint &w = waypoints[n]; \ if(!links || w.links[0]) \ { \ float dist = w.o.squaredist(pos); \ if(dist < mindist*mindist) { closest = n; mindist = sqrtf(dist); } \ } \ } while(0) int closest = -1; wpcachenode *curnode; loop(which, NUMWPCACHES) for(curnode = &wpcaches[which].nodes[0], wpcachestack.setsize(0);;) { int axis = curnode->axis(); float dist1 = pos[axis] - curnode->split[0], dist2 = curnode->split[1] - pos[axis]; if(dist1 >= mindist) { if(dist2 < mindist) { if(!curnode->isleaf(1)) { curnode += curnode->childindex(1); continue; } CHECKCLOSEST(curnode->childindex(1)); } } else if(curnode->isleaf(0)) { CHECKCLOSEST(curnode->childindex(0)); if(dist2 < mindist) { if(!curnode->isleaf(1)) { curnode += curnode->childindex(1); continue; } CHECKCLOSEST(curnode->childindex(1)); } } else { if(dist2 < mindist) { if(!curnode->isleaf(1)) wpcachestack.add(curnode + curnode->childindex(1)); else CHECKCLOSEST(curnode->childindex(1)); } curnode += curnode->childindex(0); continue; } if(wpcachestack.empty()) break; curnode = wpcachestack.pop(); } for(int i = lastwpcache; i < waypoints.length(); i++) { CHECKCLOSEST(i); } return closest; } void findwaypointswithin(const vec &pos, float mindist, float maxdist, vector &results) { if(waypoints.empty()) return; if(clearedwpcaches) buildwpcache(); float mindist2 = mindist*mindist, maxdist2 = maxdist*maxdist; #define CHECKWITHIN(index) do { \ int n = (index); \ const waypoint &w = waypoints[n]; \ float dist = w.o.squaredist(pos); \ if(dist > mindist2 && dist < maxdist2) results.add(n); \ } while(0) wpcachenode *curnode; loop(which, NUMWPCACHES) for(curnode = &wpcaches[which].nodes[0], wpcachestack.setsize(0);;) { int axis = curnode->axis(); float dist1 = pos[axis] - curnode->split[0], dist2 = curnode->split[1] - pos[axis]; if(dist1 >= maxdist) { if(dist2 < maxdist) { if(!curnode->isleaf(1)) { curnode += curnode->childindex(1); continue; } CHECKWITHIN(curnode->childindex(1)); } } else if(curnode->isleaf(0)) { CHECKWITHIN(curnode->childindex(0)); if(dist2 < maxdist) { if(!curnode->isleaf(1)) { curnode += curnode->childindex(1); continue; } CHECKWITHIN(curnode->childindex(1)); } } else { if(dist2 < maxdist) { if(!curnode->isleaf(1)) wpcachestack.add(curnode + curnode->childindex(1)); else CHECKWITHIN(curnode->childindex(1)); } curnode += curnode->childindex(0); continue; } if(wpcachestack.empty()) break; curnode = wpcachestack.pop(); } for(int i = lastwpcache; i < waypoints.length(); i++) { CHECKWITHIN(i); } } void avoidset::avoidnear(void *owner, float above, const vec &pos, float limit) { if(ai::waypoints.empty()) return; if(clearedwpcaches) buildwpcache(); float limit2 = limit*limit; #define CHECKNEAR(index) do { \ int n = (index); \ const waypoint &w = ai::waypoints[n]; \ if(w.o.squaredist(pos) < limit2) add(owner, above, n); \ } while(0) wpcachenode *curnode; loop(which, NUMWPCACHES) for(curnode = &wpcaches[which].nodes[0], wpcachestack.setsize(0);;) { int axis = curnode->axis(); float dist1 = pos[axis] - curnode->split[0], dist2 = curnode->split[1] - pos[axis]; if(dist1 >= limit) { if(dist2 < limit) { if(!curnode->isleaf(1)) { curnode += curnode->childindex(1); continue; } CHECKNEAR(curnode->childindex(1)); } } else if(curnode->isleaf(0)) { CHECKNEAR(curnode->childindex(0)); if(dist2 < limit) { if(!curnode->isleaf(1)) { curnode += curnode->childindex(1); continue; } CHECKNEAR(curnode->childindex(1)); } } else { if(dist2 < limit) { if(!curnode->isleaf(1)) wpcachestack.add(curnode + curnode->childindex(1)); else CHECKNEAR(curnode->childindex(1)); } curnode += curnode->childindex(0); continue; } if(wpcachestack.empty()) break; curnode = wpcachestack.pop(); } for(int i = lastwpcache; i < waypoints.length(); i++) { CHECKNEAR(i); } } int avoidset::remap(fpsent *d, int n, vec &pos, bool retry) { if(!obstacles.empty()) { int cur = 0; loopv(obstacles) { obstacle &ob = obstacles[i]; int next = cur + ob.numwaypoints; if(ob.owner != d) { for(; cur < next; cur++) if(waypoints[cur] == n) { if(ob.above < 0) return retry ? n : -1; vec above(pos.x, pos.y, ob.above); if(above.z-d->o.z >= ai::JUMPMAX) return retry ? n : -1; // too much scotty int node = closestwaypoint(above, ai::SIGHTMIN, true, d); if(ai::iswaypoint(node) && node != n) { // try to reroute above their head? if(!find(node, d)) { pos = ai::waypoints[node].o; return node; } else return retry ? n : -1; } else { vec old = d->o; d->o = vec(above).add(vec(0, 0, d->eyeheight)); bool col = collide(d, vec(0, 0, 1)); d->o = old; if(col) { pos = above; return n; } else return retry ? n : -1; } } } cur = next; } } return n; } static inline float heapscore(waypoint *q) { return q->score(); } bool route(fpsent *d, int node, int goal, vector &route, const avoidset &obstacles, int retries) { if(waypoints.empty() || !iswaypoint(node) || !iswaypoint(goal) || goal == node || !waypoints[node].links[0]) return false; static ushort routeid = 1; static vector queue; if(!routeid) { loopv(waypoints) waypoints[i].route = 0; routeid = 1; } if(d) { if(retries <= 1 && d->ai) loopi(ai::NUMPREVNODES) if(d->ai->prevnodes[i] != node && iswaypoint(d->ai->prevnodes[i])) { waypoints[d->ai->prevnodes[i]].route = routeid; waypoints[d->ai->prevnodes[i]].curscore = -1; waypoints[d->ai->prevnodes[i]].estscore = 0; } if(retries <= 0) { loopavoid(obstacles, d, { if(iswaypoint(wp) && wp != node && wp != goal && waypoints[node].find(wp) < 0 && waypoints[goal].find(wp) < 0) { waypoints[wp].route = routeid; waypoints[wp].curscore = -1; waypoints[wp].estscore = 0; } }); } } waypoints[node].route = routeid; waypoints[node].curscore = waypoints[node].estscore = 0; waypoints[node].prev = 0; queue.setsize(0); queue.add(&waypoints[node]); route.setsize(0); int lowest = -1; while(!queue.empty()) { waypoint &m = *queue.removeheap(); float prevscore = m.curscore; m.curscore = -1; loopi(MAXWAYPOINTLINKS) { int link = m.links[i]; if(!link) break; if(iswaypoint(link) && (link == node || link == goal || waypoints[link].links[0])) { waypoint &n = waypoints[link]; int weight = max(n.weight, 1); float curscore = prevscore + n.o.dist(m.o)*weight; if(n.route == routeid && curscore >= n.curscore) continue; n.curscore = curscore; n.prev = ushort(&m - &waypoints[0]); if(n.route != routeid) { n.estscore = n.o.dist(waypoints[goal].o)*weight; if(n.estscore <= WAYPOINTRADIUS*4 && (lowest < 0 || n.estscore <= waypoints[lowest].estscore)) lowest = link; n.route = routeid; if(link == goal) goto foundgoal; queue.addheap(&n); } else loopvj(queue) if(queue[j] == &n) { queue.upheap(j); break; } } } } foundgoal: routeid++; if(lowest >= 0) // otherwise nothing got there { for(waypoint *m = &waypoints[lowest]; m > &waypoints[0]; m = &waypoints[m->prev]) route.add(m - &waypoints[0]); // just keep it stored backward } return !route.empty(); } VARF(dropwaypoints, 0, 0, 1, { player1->lastnode = -1; }); int addwaypoint(const vec &o, int weight = -1) { if(waypoints.length() > MAXWAYPOINTS) return -1; int n = waypoints.length(); waypoints.add(waypoint(o, weight >= 0 ? weight : getweight(o))); return n; } void linkwaypoint(waypoint &a, int n) { loopi(MAXWAYPOINTLINKS) { if(a.links[i] == n) return; if(!a.links[i]) { a.links[i] = n; return; } } a.links[rnd(MAXWAYPOINTLINKS)] = n; } string loadedwaypoints = ""; static inline bool shouldnavigate() { if(dropwaypoints) return true; loopvrev(players) if(players[i]->aitype != AI_NONE) return true; return false; } static inline bool shoulddrop(fpsent *d) { return !d->ai && (dropwaypoints || !loadedwaypoints[0]); } void inferwaypoints(fpsent *d, const vec &o, const vec &v, float mindist) { if(!shouldnavigate()) return; if(shoulddrop(d)) { if(waypoints.empty()) seedwaypoints(); int from = closestwaypoint(o, mindist, false), to = closestwaypoint(v, mindist, false); if(!iswaypoint(from)) from = addwaypoint(o); if(!iswaypoint(to)) to = addwaypoint(v); if(d->lastnode != from && iswaypoint(d->lastnode) && iswaypoint(from)) linkwaypoint(waypoints[d->lastnode], from); if(iswaypoint(to)) { if(from != to && iswaypoint(from) && iswaypoint(to)) linkwaypoint(waypoints[from], to); d->lastnode = to; } } else d->lastnode = closestwaypoint(v, WAYPOINTRADIUS*2, false, d); } void navigate(fpsent *d) { vec v(d->feetpos()); if(d->state != CS_ALIVE) { d->lastnode = -1; return; } bool dropping = shoulddrop(d); int mat = lookupmaterial(v); if((mat&MATF_CLIP) == MAT_CLIP || (mat&MATF_VOLUME) == MAT_LAVA || mat&MAT_DEATH) dropping = false; float dist = dropping ? WAYPOINTRADIUS : (d->ai ? WAYPOINTRADIUS : SIGHTMIN); int curnode = closestwaypoint(v, dist, false, d), prevnode = d->lastnode; if(!iswaypoint(curnode) && dropping) { if(waypoints.empty()) seedwaypoints(); curnode = addwaypoint(v); } if(iswaypoint(curnode)) { if(dropping && d->lastnode != curnode && iswaypoint(d->lastnode)) { linkwaypoint(waypoints[d->lastnode], curnode); if(!d->timeinair) linkwaypoint(waypoints[curnode], d->lastnode); } d->lastnode = curnode; if(d->ai && iswaypoint(prevnode) && d->lastnode != prevnode) d->ai->addprevnode(prevnode); } else if(!iswaypoint(d->lastnode) || waypoints[d->lastnode].o.squaredist(v) > SIGHTMIN*SIGHTMIN) d->lastnode = closestwaypoint(v, SIGHTMAX, false, d); } void navigate() { if(shouldnavigate()) loopv(players) ai::navigate(players[i]); if(invalidatedwpcaches) clearwpcache(false); } void clearwaypoints(bool full) { waypoints.setsize(0); clearwpcache(); if(full) { loadedwaypoints[0] = '\0'; dropwaypoints = 0; } } ICOMMAND(clearwaypoints, "", (), clearwaypoints()); void seedwaypoints() { if(waypoints.empty()) addwaypoint(vec(0, 0, 0)); loopv(entities::ents) { extentity &e = *entities::ents[i]; switch(e.type) { case PLAYERSTART: case TELEPORT: case JUMPPAD: case FLAG: case BASE: addwaypoint(e.o); break; default: if(e.type >= I_SHELLS && e.type <= I_QUAD) addwaypoint(e.o); break; } } } void remapwaypoints() { vector remap; int total = 0; loopv(waypoints) remap.add(waypoints[i].links[1] == 0xFFFF ? 0 : total++); total = 0; loopvj(waypoints) { if(waypoints[j].links[1] == 0xFFFF) continue; waypoint &w = waypoints[total]; if(j != total) w = waypoints[j]; int k = 0; loopi(MAXWAYPOINTLINKS) { int link = w.links[i]; if(!link) break; if((w.links[k] = remap[link])) k++; } if(k < MAXWAYPOINTLINKS) w.links[k] = 0; total++; } waypoints.setsize(total); } bool cleanwaypoints() { int cleared = 0; for(int i = 1; i < waypoints.length(); i++) { waypoint &w = waypoints[i]; if(clipped(w.o)) { w.links[0] = 0; w.links[1] = 0xFFFF; cleared++; } } if(cleared) { player1->lastnode = -1; loopv(players) if(players[i]) players[i]->lastnode = -1; remapwaypoints(); clearwpcache(); return true; } return false; } bool getwaypointfile(const char *mname, char *wptname) { if(!mname || !*mname) mname = getclientmap(); if(!*mname) return false; string pakname, mapname, cfgname; getmapfilenames(mname, NULL, pakname, mapname, cfgname); formatstring(wptname)("packages/%s.wpt", mapname); path(wptname); return true; } void loadwaypoints(bool force, const char *mname) { string wptname; if(!getwaypointfile(mname, wptname)) return; if(!force && (waypoints.length() || !strcmp(loadedwaypoints, wptname))) return; stream *f = opengzfile(wptname, "rb"); if(!f) return; char magic[4]; if(f->read(magic, 4) < 4 || memcmp(magic, "OWPT", 4)) { delete f; return; } copystring(loadedwaypoints, wptname); waypoints.setsize(0); waypoints.add(vec(0, 0, 0)); ushort numwp = f->getlil(); loopi(numwp) { if(f->end()) break; vec o; o.x = f->getlil(); o.y = f->getlil(); o.z = f->getlil(); waypoint &w = waypoints.add(waypoint(o, getweight(o))); int numlinks = f->getchar(), k = 0; loopi(numlinks) { if((w.links[k] = f->getlil())) { if(++k >= MAXWAYPOINTLINKS) break; } } } delete f; conoutf("loaded %d waypoints from %s", numwp, wptname); if(!cleanwaypoints()) clearwpcache(); } ICOMMAND(loadwaypoints, "s", (char *mname), loadwaypoints(true, mname)); void savewaypoints(bool force, const char *mname) { if((!dropwaypoints && !force) || waypoints.empty()) return; string wptname; if(!getwaypointfile(mname, wptname)) return; stream *f = opengzfile(wptname, "wb"); if(!f) return; f->write("OWPT", 4); f->putlil(waypoints.length()-1); for(int i = 1; i < waypoints.length(); i++) { waypoint &w = waypoints[i]; f->putlil(w.o.x); f->putlil(w.o.y); f->putlil(w.o.z); int numlinks = 0; loopj(MAXWAYPOINTLINKS) { if(!w.links[j]) break; numlinks++; } f->putchar(numlinks); loopj(numlinks) f->putlil(w.links[j]); } delete f; conoutf("saved %d waypoints to %s", waypoints.length()-1, wptname); } ICOMMAND(savewaypoints, "s", (char *mname), savewaypoints(true, mname)); void delselwaypoints() { if(noedit(true)) return; vec o = sel.o.tovec().sub(0.1f), s = sel.s.tovec().mul(sel.grid).add(o).add(0.1f); int cleared = 0; for(int i = 1; i < waypoints.length(); i++) { waypoint &w = waypoints[i]; if(w.o.x >= o.x && w.o.x <= s.x && w.o.y >= o.y && w.o.y <= s.y && w.o.z >= o.z && w.o.z <= s.z) { w.links[0] = 0; w.links[1] = 0xFFFF; cleared++; } } if(cleared) { player1->lastnode = -1; remapwaypoints(); clearwpcache(); } } COMMAND(delselwaypoints, ""); void movewaypoints(const vec &d) { if(noedit(true)) return; int worldsize = getworldsize(); if(d.x < -worldsize || d.x > worldsize || d.y < -worldsize || d.y > worldsize || d.z < -worldsize || d.z > worldsize) { clearwaypoints(); return; } int cleared = 0; for(int i = 1; i < waypoints.length(); i++) { waypoint &w = waypoints[i]; w.o.add(d); if(!insideworld(w.o)) { w.links[0] = 0; w.links[1] = 0xFFFF; cleared++; } } if(cleared) { player1->lastnode = -1; remapwaypoints(); } clearwpcache(); } ICOMMAND(movewaypoints, "iii", (int *dx, int *dy, int *dz), movewaypoints(vec(*dx, *dy, *dz))); } sauerbraten-0.0.20130203.dfsg/fpsgame/collect.h0000644000175000017500000007251112073125552020625 0ustar vincentvincent#ifndef PARSEMESSAGES #define collectteambase(s) (!strcmp(s, "good") ? 1 : (!strcmp(s, "evil") ? 2 : 0)) #define collectbaseteam(i) (i==1 ? "good" : (i==2 ? "evil" : NULL)) #ifdef SERVMODE struct collectservmode : servmode #else struct collectclientmode : clientmode #endif { static const int BASERADIUS = 16; static const int BASEHEIGHT = 16; static const int MAXBASES = 20; static const int TOKENRADIUS = 16; static const int TOKENLIMIT = 5; static const int UNOWNEDTOKENLIMIT = 15; static const int TOKENDIST = 16; static const int SCORELIMIT = 50; static const int RESPAWNSECS = 5; static const int EXPIRETOKENTIME = 10000; static const int STEALTOKENTIME = 5000; struct base { int id, team; vec o; int laststeal; #ifdef SERVMODE #else vec tokenpos; string info; entitylight light; #endif base() { reset(); } void reset() { o = vec(0, 0, 0); team = 0; laststeal = 0; } }; struct token { int id, team, droptime; vec o; #ifdef SERVMODE int yaw, dropper; #else entitylight light; #endif token() { reset(); } void reset() { o = vec(0, 0, 0); team = 0; #ifdef SERVMODE dropper = -1; #endif droptime = 0; } }; vector bases; int scores[2]; vector tokens; #ifdef SERVMODE int nexttoken; #endif void resetbases() { bases.shrink(0); tokens.shrink(0); loopk(2) scores[k] = 0; tokens.shrink(0); #ifdef SERVMODE nexttoken = 0; #endif } #ifdef SERVMODE bool addbase(int i, const vec &o, int team) #else bool addbase(int i, const vec &o, int team) #endif { if(i<0 || i>=MAXBASES) return false; while(bases.length()<=i) bases.add(); base &b = bases[i]; b.reset(); b.id = i; b.team = team; b.o = o; return true; } token *findtoken(int id) { loopv(tokens) if(tokens[i].id == id) return &tokens[i]; return NULL; } #ifdef SERVMODE token &droptoken(const vec &o, int yaw, int team, int droptime, int dropper) #else token &droptoken(int id, const vec &o, int team, int droptime) #endif { token &t = tokens.add(); t.o = o; t.team = team; t.droptime = droptime; #ifdef SERVMODE if(++nexttoken < 0) nexttoken = 1; t.id = nexttoken; t.dropper = dropper; t.yaw = yaw; #else t.id = id; #endif return t; } bool removetoken(int id) { loopv(tokens) if(tokens[i].id == id) { tokens.removeunordered(i); return true; } return false; } int totalscore(int team) { return team >= 1 && team <= 2 ? scores[team-1] : 0; } int setscore(int team, int score) { if(team >= 1 && team <= 2) return scores[team-1] = score; return 0; } int addscore(int team, int score) { if(team >= 1 && team <= 2) return scores[team-1] += score; return 0; } bool hidefrags() { return true; } int getteamscore(const char *team) { return totalscore(collectteambase(team)); } void getteamscores(vector &tscores) { loopk(2) if(scores[k]) tscores.add(teamscore(collectbaseteam(k+1), scores[k])); } bool insidebase(const base &b, const vec &o) { float dx = (b.o.x-o.x), dy = (b.o.y-o.y), dz = (b.o.z-o.z); return dx*dx + dy*dy <= BASERADIUS*BASERADIUS && fabs(dz) <= BASEHEIGHT; } #ifdef SERVMODE bool notgotbases; collectservmode() : notgotbases(false) {} void reset(bool empty) { resetbases(); notgotbases = !empty; } void cleanup() { reset(false); } void setup() { reset(false); if(notgotitems || ments.empty()) return; loopv(ments) { entity &e = ments[i]; if(e.type != FLAG || e.attr2 < 1 || e.attr2 > 2) continue; if(!addbase(bases.length(), e.o, e.attr2)) break; } notgotbases = false; } void newmap() { reset(true); } #if 0 void losetokens(clientinfo *ci) { if(notgotbases || ci->state.tokens <= 0) return; sendf(-1, 1, "ri2", N_LOSETOKENS, ci->clientnum); ci->state.tokens = 0; } #endif void droptokens(clientinfo *ci, bool penalty = false) { if(notgotbases) return; int team = collectteambase(ci->team), totalenemy = penalty ? 0 : ci->state.tokens, totalfriendly = 1, expired = 0; packetbuf p(300, ENET_PACKET_FLAG_RELIABLE); loopvrev(tokens) { token &t = tokens[i]; if(t.dropper == ci->clientnum && (t.team == team ? ++totalfriendly > TOKENLIMIT : ++totalenemy > TOKENLIMIT)) { if(!expired) putint(p, N_EXPIRETOKENS); expired++; putint(p, t.id); tokens.removeunordered(i); } } if(expired) putint(p, -1); putint(p, N_DROPTOKENS); putint(p, ci->clientnum); putint(p, int(ci->state.o.x*DMF)); putint(p, int(ci->state.o.y*DMF)); putint(p, int(ci->state.o.z*DMF)); int numdrops = 1 + (penalty ? 0 : ci->state.tokens), yaw = rnd(360); loopi(numdrops) { token &t = droptoken(ci->state.o, yaw + (i*360)/numdrops, !i ? team : -team, lastmillis, ci->clientnum); putint(p, t.id); putint(p, t.team); putint(p, t.yaw); } putint(p, -1); sendpacket(-1, 1, p.finalize()); ci->state.tokens = 0; } void leavegame(clientinfo *ci, bool disconnecting = false) { ci->state.tokens = 0; if(disconnecting) { int team = collectteambase(ci->team), totalfriendly = 0, totalenemy = 0; loopvrev(tokens) { token &t = tokens[i]; if(t.dropper == ci->clientnum) t.dropper = INT_MIN; else if(t.dropper > INT_MIN) continue; if(t.team == team ? ++totalfriendly > UNOWNEDTOKENLIMIT : ++totalenemy > UNOWNEDTOKENLIMIT) { packetbuf p(300, ENET_PACKET_FLAG_RELIABLE); putint(p, N_EXPIRETOKENS); putint(p, t.id); tokens.removeunordered(i); while(--i >= 0) { token &t = tokens[i]; if(t.dropper == ci->clientnum) t.dropper = INT_MIN; else if(t.dropper > INT_MIN) continue; if(t.team == team ? ++totalfriendly > UNOWNEDTOKENLIMIT : ++totalenemy > UNOWNEDTOKENLIMIT) { putint(p, t.id); tokens.removeunordered(i); } } putint(p, -1); sendpacket(-1, 1, p.finalize()); } } } } void died(clientinfo *ci, clientinfo *actor) { droptokens(ci, !actor || isteam(actor->team, ci->team)); } bool canspawn(clientinfo *ci, bool connecting) { return connecting || !ci->state.lastdeath || gamemillis+curtime-ci->state.lastdeath >= RESPAWNSECS*1000; } bool canchangeteam(clientinfo *ci, const char *oldteam, const char *newteam) { return collectteambase(newteam) > 0; } void changeteam(clientinfo *ci, const char *oldteam, const char *newteam) { } void deposittokens(clientinfo *ci, int basenum) { if(notgotbases || !bases.inrange(basenum) || ci->state.state!=CS_ALIVE || !ci->team[0]) return; base &b = bases[basenum]; if(!collectbaseteam(b.team)) return; int team = collectteambase(ci->team); if(b.team==team) return; if(ci->state.tokens > 0) { b.laststeal = gamemillis; ci->state.flags += ci->state.tokens; int score = addscore(team, ci->state.tokens); sendf(-1, 1, "ri7", N_DEPOSITTOKENS, ci->clientnum, basenum, ci->state.tokens, team, score, ci->state.flags); ci->state.tokens = 0; if(score >= SCORELIMIT) startintermission(); } else { if(gamemillis < b.laststeal + STEALTOKENTIME) return; if(totalscore(b.team) <= 0) return; int stolen = 0; loopv(tokens) if(tokens[i].dropper == -1 - basenum) stolen++; if(stolen < TOKENLIMIT) { b.laststeal = gamemillis; int score = addscore(b.team, -1); token &t = droptoken(b.o, rnd(360), team, lastmillis, -1 - basenum); sendf(-1, 1, "ri9i3", N_STEALTOKENS, ci->clientnum, team, basenum, b.team, score, int(t.o.x*DMF), int(t.o.y*DMF), int(t.o.z*DMF), t.id, t.yaw, -1); } } } void taketoken(clientinfo *ci, int id) { if(notgotbases || ci->state.state!=CS_ALIVE || !ci->team[0]) return; token *t = findtoken(id); if(!t) return; int team = collectteambase(ci->team); if(t->team != team && (t->team > 0 || -t->team == team) && ci->state.tokens < TOKENLIMIT) ci->state.tokens++; sendf(-1, 1, "ri4", N_TAKETOKEN, ci->clientnum, id, ci->state.tokens); } void update() { if(gamemillis>=gamelimit || notgotbases) return; vector resets; loopvrev(tokens) { token &t = tokens[i]; if(lastmillis - t.droptime >= EXPIRETOKENTIME) { resets.add(t.id); tokens.removeunordered(i); } } if(resets.length()) sendf(-1, 1, "rivi", N_EXPIRETOKENS, resets.length(), resets.getbuf(), -1); } void initclient(clientinfo *ci, packetbuf &p, bool connecting) { putint(p, N_INITTOKENS); loopk(2) putint(p, scores[k]); putint(p, tokens.length()); loopv(tokens) { token &t = tokens[i]; putint(p, t.id); putint(p, t.team); putint(p, t.yaw); putint(p, int(t.o.x*DMF)); putint(p, int(t.o.y*DMF)); putint(p, int(t.o.z*DMF)); } loopv(clients) if(clients[i]->state.state == CS_ALIVE && clients[i]->state.tokens > 0) { putint(p, clients[i]->clientnum); putint(p, clients[i]->state.tokens); } putint(p, -1); } void parsebases(ucharbuf &p, bool commit) { int numbases = getint(p); loopi(numbases) { int team = getint(p); vec o; loopk(3) o[k] = max(getint(p)/DMF, 0.0f); if(p.overread()) break; if(commit && notgotbases) { addbase(i, o, team); } } if(commit && notgotbases) { notgotbases = false; } } }; #else static const int TOKENHEIGHT = 5; void preload() { preloadmodel("base/red"); preloadmodel("base/blue"); preloadmodel("skull/red"); preloadmodel("skull/blue"); static const int sounds[] = { S_FLAGDROP, S_FLAGSCORE, S_FLAGFAIL }; loopi(sizeof(sounds)/sizeof(sounds[0])) preloadsound(sounds[i]); } void drawblip(fpsent *d, float x, float y, float s, const vec &pos, float size = 0.05f) { float scale = calcradarscale(); vec dir = d->o; dir.sub(pos).div(scale); float xoffset = -size, yoffset = -size, dist = dir.magnitude2(), maxdist = 1 - 0.05f - 0.05f; if(dist >= maxdist) dir.mul(maxdist/dist); dir.rotate_around_z(-camera1->yaw*RAD); drawradar(x + s*0.5f*(1.0f + dir.x + xoffset), y + s*0.5f*(1.0f + dir.y + yoffset), size*s); } void drawbaseblip(fpsent *d, float x, float y, float s, int i) { base &b = bases[i]; settexture(b.team==collectteambase(player1->team) ? "packages/hud/blip_blue.png" : "packages/hud/blip_red.png", 3); drawblip(d, x, y, s, b.o); } int clipconsole(int w, int h) { return (h*(1 + 1 + 10))/(4*10); } void drawhud(fpsent *d, int w, int h) { if(d->state == CS_ALIVE && d->tokens > 0) { int x = HICON_X + 3*HICON_STEP + (d->quadmillis ? HICON_SIZE + HICON_SPACE : 0); glPushMatrix(); glScalef(2, 2, 1); draw_textf("%d", (x + HICON_SIZE + HICON_SPACE)/2, HICON_TEXTY/2, d->tokens); glPopMatrix(); drawicon(HICON_TOKEN, x, HICON_Y); } glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int s = 1800/4, x = 1800*w/h - s - s/10, y = s/10; glColor4f(1, 1, 1, minimapalpha); if(minimapalpha >= 1) glDisable(GL_BLEND); bindminimap(); drawminimap(d, x, y, s); if(minimapalpha >= 1) glEnable(GL_BLEND); glColor3f(1, 1, 1); float margin = 0.04f, roffset = s*margin, rsize = s + 2*roffset; settexture("packages/hud/radar.png", 3); drawradar(x - roffset, y - roffset, rsize); #if 0 settexture("packages/hud/compass.png", 3); glPushMatrix(); glTranslatef(x - roffset + 0.5f*rsize, y - roffset + 0.5f*rsize, 0); glRotatef(camera1->yaw + 180, 0, 0, -1); drawradar(-0.5f*rsize, -0.5f*rsize, rsize); glPopMatrix(); #endif loopv(bases) { base &b = bases[i]; if(!collectbaseteam(b.team)) continue; drawbaseblip(d, x, y, s, i); } int team = collectteambase(d->team); settexture(team == collectteambase(player1->team) ? "packages/hud/blip_red_skull.png" : "packages/hud/blip_blue_skull.png", 3); loopv(players) { fpsent *o = players[i]; if(o != d && o->state == CS_ALIVE && o->tokens > 0 && collectteambase(o->team) != team) drawblip(d, x, y, s, o->o, 0.07f); } drawteammates(d, x, y, s); if(d->state == CS_DEAD) { int wait = respawnwait(d); if(wait>=0) { glPushMatrix(); glScalef(2, 2, 1); bool flash = wait>0 && d==player1 && lastspawnattempt>=d->lastpain && lastmillis < lastspawnattempt+100; draw_textf("%s%d", (x+s/2)/2-(wait>=10 ? 28 : 16), (y+s/2)/2-32, flash ? "\f3" : "", wait); glPopMatrix(); } } } void rendergame() { int team = collectteambase(player1->team); vec theight(0, 0, 0); abovemodel(theight, "skull/red"); loopv(bases) { base &b = bases[i]; const char *basename = b.team==team ? "base/blue" : "base/red"; rendermodel(&b.light, basename, ANIM_MAPMODEL|ANIM_LOOP, b.o, 0, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_OCCLUDED); float fradius = 1.0f, fheight = 0.5f; regular_particle_flame(PART_FLAME, vec(b.tokenpos.x, b.tokenpos.y, b.tokenpos.z - 4.5f), fradius, fheight, b.team==team ? 0x2020FF : 0x802020, 3, 2.0f); vec tokenpos(b.tokenpos); tokenpos.z -= theight.z/2 + sinf(lastmillis/100.0f)/20; float alpha = player1->state == CS_ALIVE && player1->tokens <= 0 && lastmillis < b.laststeal + STEALTOKENTIME ? 0.5f : 1.0f; rendermodel(&b.light, b.team==team ? "skull/blue" : "skull/red", ANIM_MAPMODEL|ANIM_LOOP, tokenpos, lastmillis/10.0f, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_OCCLUDED, NULL, NULL, 0, 0, alpha); formatstring(b.info)("%d", totalscore(b.team)); vec above(b.tokenpos); above.z += TOKENHEIGHT; if(b.info[0]) particle_text(above, b.info, PART_TEXT, 1, b.team==team ? 0x6496FF : 0xFF4B19, 2.0f); } loopv(tokens) { token &t = tokens[i]; vec p = t.o; p.z += 1+sinf(lastmillis/100.0+t.o.x+t.o.y)/20; rendermodel(&t.light, t.team == team || (t.team < 0 && -t.team != team) ? "skull/blue" : "skull/red", ANIM_MAPMODEL|ANIM_LOOP, p, lastmillis/10.0f, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_DIST | MDL_CULL_OCCLUDED); } fpsent *exclude = isthirdperson() ? NULL : hudplayer(); loopv(players) { fpsent *d = players[i]; if(d->state != CS_ALIVE || d->tokens <= 0 || d == exclude) continue; vec pos = d->abovehead().add(vec(0, 0, 1)); entitylight light; lightreaching(pos, light.color, light.dir, true); int dteam = collectteambase(d->team); loopj(d->tokens) { rendermodel(&light, dteam != team ? "skull/blue" : "skull/red", ANIM_MAPMODEL|ANIM_LOOP, pos, d->yaw+90, 0, MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_DIST | MDL_CULL_OCCLUDED); pos.z += TOKENHEIGHT + 1; } } } void setup() { resetbases(); vector radarents; loopv(entities::ents) { extentity *e = entities::ents[i]; if(e->type!=FLAG) continue; if(e->attr2<1 || e->attr2>2) continue; int index = bases.length(); if(!addbase(index, e->o, e->attr2)) continue; base &b = bases[index]; b.tokenpos = b.o; abovemodel(b.tokenpos, "base/blue"); b.tokenpos.z += TOKENHEIGHT-2; b.light = e->light; } } void senditems(packetbuf &p) { putint(p, N_INITTOKENS); putint(p, bases.length()); loopv(bases) { base &b = bases[i]; putint(p, b.team); loopk(3) putint(p, int(b.o[k]*DMF)); } } vec movetoken(const vec &o, int yaw) { static struct dropent : physent { dropent() { type = ENT_CAMERA; collidetype = COLLIDE_AABB; } } d; d.o = o; d.o.z += 4; d.radius = d.xradius = d.yradius = 4; d.eyeheight = d.aboveeye = 4; vecfromyawpitch(yaw, 0, 1, 0, d.vel); d.o.add(vec(d.vel).mul(4)); movecamera(&d, d.vel, TOKENDIST-4, 1); if(!droptofloor(d.o, 4, 4)) return vec(-1, -1, -1); return d.o; } void parsetokens(ucharbuf &p, bool commit) { loopk(2) { int score = getint(p); if(commit) scores[k] = score; } int numtokens = getint(p); loopi(numtokens) { int id = getint(p), team = getint(p), yaw = getint(p); vec o; loopk(3) o[k] = getint(p)/DMF; if(p.overread()) break; o = movetoken(o, yaw); if(o.z >= 0) droptoken(id, o, team, lastmillis); } for(;;) { int cn = getint(p); if(cn < 0) break; int tokens = getint(p); if(p.overread()) break; fpsent *d = cn == player1->clientnum ? player1 : newclient(cn); if(d) d->tokens = tokens; } } void baseexplosion(int i, int team, const vec &loc) { int fcolor; vec color; if(team==collectteambase(player1->team)) { fcolor = 0x2020FF; color = vec(0.25f, 0.25f, 1); } else { fcolor = 0x802020; color = vec(1, 0.25f, 0.25f); } particle_fireball(loc, 30, PART_EXPLOSION, -1, fcolor, 4.8f); adddynlight(loc, 35, color, 900, 100); particle_splash(PART_SPARK, 150, 300, loc, fcolor, 0.24f); } void baseeffect(int i, int team, const vec &from, const vec &to, bool showfrom = true, bool showto = true) { if(showfrom) baseexplosion(i, team, from); if(from==to) return; if(showto) baseexplosion(i, team, to); particle_flare(from, to, 600, PART_LIGHTNING, team==collectteambase(player1->team) ? 0x2222FF : 0xFF2222, 1.0f); } void expiretoken(int id) { token *t = findtoken(id); if(!t) return; playsound(S_ITEMAMMO, &t->o); removetoken(id); } void taketoken(fpsent *d, int id, int total) { int team = collectteambase(d->team); token *t = findtoken(id); if(t) { playsound(t->team == team || (t->team < 0 && -t->team != team) ? S_ITEMAMMO : S_ITEMHEALTH, d!=player1 ? &d->o : NULL); removetoken(id); } d->tokens = total; } token *droptoken(fpsent *d, int id, const vec &o, int team, int yaw, int n) { vec pos = movetoken(o, yaw); if(pos.z < 0) return NULL; token &t = droptoken(id, pos, team, lastmillis); lightreaching(vec(t.o).add(vec(0, 0, TOKENHEIGHT)), t.light.color, t.light.dir, true); if(!n) playsound(S_ITEMSPAWN, d ? &d->o : &pos); if(d) { if(!n) { particle_fireball(d->o, 4.8f, PART_EXPLOSION, 500, team==collectteambase(player1->team) ? 0x2020FF : 0x802020, 4.8f); particle_splash(PART_SPARK, 50, 250, d->o, team==collectteambase(player1->team) ? 0x2020FF : 0x802020, 0.24f); } particle_flare(d->o, vec(t.o.x, t.o.y, t.o.z + 0.5f*(TOKENHEIGHT + 1)), 500, PART_LIGHTNING, team==collectteambase(player1->team) ? 0x2222FF : 0xFF2222, 1.0f); } return &t; } void stealtoken(fpsent *d, int id, const vec &o, int team, int yaw, int n, int basenum, int enemyteam, int score) { if(!n) setscore(enemyteam, score); token *t = droptoken(NULL, id, o, team, yaw, n); if(bases.inrange(basenum)) { base &b = bases[basenum]; if(!n) { b.laststeal = lastmillis; conoutf(CON_GAMEINFO, "%s stole a skull from %s", teamcolorname(d), teamcolor("your team", collectbaseteam(enemyteam), "the enemy team")); playsound(S_FLAGDROP, &b.tokenpos); } if(t) particle_flare(b.tokenpos, vec(t->o.x, t->o.y, t->o.z + 0.5f*(TOKENHEIGHT + 1)), 500, PART_LIGHTNING, team==collectteambase(player1->team) ? 0x2222FF : 0xFF2222, 1.0f); } } void deposittokens(fpsent *d, int basenum, int deposited, int team, int score, int flags) { if(bases.inrange(basenum)) { base &b = bases[basenum]; b.laststeal = lastmillis; //playsound(S_FLAGSCORE, d != player1 ? &b.tokenpos : NULL); int n = 0; loopv(bases) { base &h = bases[i]; if(h.team == team) baseeffect(i, team, h.tokenpos, b.tokenpos, !n++); } } d->tokens = 0; d->flags = flags; setscore(team, score); conoutf(CON_GAMEINFO, "%s collected %d %s for %s", teamcolorname(d), deposited, deposited==1 ? "skull" : "skulls", teamcolor("your team", collectbaseteam(team), "the enemy team")); playsound(team==collectteambase(player1->team) ? S_FLAGSCORE : S_FLAGFAIL); if(score >= SCORELIMIT) conoutf(CON_GAMEINFO, "%s collected %d skulls", teamcolor("your team", collectbaseteam(team), "the enemy team"), score); } void checkitems(fpsent *d) { if(d->state!=CS_ALIVE) return; vec o = d->feetpos(); if(d->tokens > 0 || o != d->lastcollect) { int team = collectteambase(d->team); loopv(bases) { base &b = bases[i]; if(!collectbaseteam(b.team) || b.team == team) continue; if(insidebase(b, o) && (d->tokens > 0 || !insidebase(b, d->lastcollect))) { addmsg(N_DEPOSITTOKENS, "rci", d, i); d->tokens = 0; } } } if(d->tokens < TOKENLIMIT) loopv(tokens) { token &t = tokens[i]; if(o.dist(t.o) < TOKENRADIUS && d->lastcollect.dist(t.o) >= TOKENRADIUS && (lookupmaterial(o)&MATF_CLIP) != MAT_GAMECLIP && (lookupmaterial(t.o)&MATF_CLIP) != MAT_GAMECLIP) addmsg(N_TAKETOKEN, "rci", d, t.id); } d->lastcollect = o; } int respawnwait(fpsent *d) { return max(0, RESPAWNSECS-(lastmillis-d->lastpain)/1000); } void pickspawn(fpsent *d) { findplayerspawn(d, -1, collectteambase(d->team)); } bool aicheck(fpsent *d, ai::aistate &b) { if(ai::badhealth(d)) return false; int team = collectteambase(d->team), best = -1; float bestdist = 1e16f; if(d->tokens > 0) { loopv(bases) { base &b = bases[i]; if(b.team == team) continue; float dist = d->o.dist(b.o); if(best < 0 || dist < bestdist) { best = i; bestdist = dist; } } if(best < 0 || !ai::makeroute(d, b, bases[best].o)) return false; d->ai->switchstate(b, ai::AI_S_PURSUE, ai::AI_T_AFFINITY, -(best+1)); } else { loopv(tokens) { token &t = tokens[i]; float dist = d->o.dist(t.o)/(t.team != team && (t.team > 0 || -t.team == team) ? 10.0f : 1.0f); if(best < 0 || dist < bestdist) { best = i; bestdist = dist; } } if(best < 0 || !ai::makeroute(d, b, tokens[best].o)) return false; d->ai->switchstate(b, ai::AI_S_PURSUE, ai::AI_T_AFFINITY, tokens[best].id); } return true; } void aifind(fpsent *d, ai::aistate &b, vector &interests) { vec pos = d->feetpos(); int team = collectteambase(d->team); if(d->tokens > 0) { loopv(bases) { base &b = bases[i]; if(b.team == team) continue; ai::interest &n = interests.add(); n.state = ai::AI_S_PURSUE; n.node = ai::closestwaypoint(b.o, ai::SIGHTMIN, true); n.target = -(i+1); n.targtype = ai::AI_T_AFFINITY; n.score = pos.squaredist(b.o)/(d->tokens > 2 ? 1e3f : 1e2f); } } if(d->tokens < TOKENLIMIT) loopv(tokens) { token &t = tokens[i]; ai::interest &n = interests.add(); n.state = ai::AI_S_PURSUE; n.node = ai::closestwaypoint(t.o, ai::SIGHTMIN, true); n.target = t.id; n.targtype = ai::AI_T_AFFINITY; n.score = pos.squaredist(t.o)/(t.team != team && (t.team > 0 || -t.team == team) ? 10.0f : 1.0f); } } bool aipursue(fpsent *d, ai::aistate &b) { if(b.target < 0) { if(d->tokens <= 0 || !bases.inrange(-(b.target+1))) return false; base &g = bases[-(b.target+1)]; if(g.team == collectteambase(d->team)) return false; return ai::makeroute(d, b, g.o); } else if(b.target > 0) { token *t = findtoken(b.target); if(t) return ai::makeroute(d, b, t->o); } return false; } }; #endif #elif SERVMODE case N_INITTOKENS: if(smode==&collectmode) collectmode.parsebases(p, (ci->state.state!=CS_SPECTATOR || ci->privilege || ci->local) && !strcmp(ci->clientmap, smapname)); break; case N_TAKETOKEN: { int id = getint(p); if((ci->state.state!=CS_SPECTATOR || ci->local || ci->privilege) && cq && smode==&collectmode) collectmode.taketoken(cq, id); break; } case N_DEPOSITTOKENS: { int id = getint(p); if((ci->state.state!=CS_SPECTATOR || ci->local || ci->privilege) && cq && smode==&collectmode) collectmode.deposittokens(cq, id); break; } #else case N_INITTOKENS: collectmode.parsetokens(p, m_collect); break; case N_TAKETOKEN: { int ocn = getint(p), id = getint(p), total = getint(p); fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); if(o && m_collect) collectmode.taketoken(o, id, total); break; } case N_EXPIRETOKENS: for(;;) { int id = getint(p); if(p.overread() || id < 0) break; if(m_collect) collectmode.expiretoken(id); } break; case N_DROPTOKENS: { int ocn = getint(p); fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); vec droploc; loopk(3) droploc[k] = getint(p)/DMF; for(int n = 0;; n++) { int id = getint(p); if(id < 0) break; int team = getint(p), yaw = getint(p); if(p.overread()) break; if(o && m_collect) collectmode.droptoken(o, id, droploc, team, yaw, n); } break; } case N_STEALTOKENS: { int ocn = getint(p), team = getint(p), basenum = getint(p), enemyteam = getint(p), score = getint(p); fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); vec droploc; loopk(3) droploc[k] = getint(p)/DMF; for(int n = 0;; n++) { int id = getint(p); if(id < 0) break; int yaw = getint(p); if(p.overread()) break; if(o && m_collect) collectmode.stealtoken(o, id, droploc, team, yaw, n, basenum, enemyteam, score); } break; } case N_DEPOSITTOKENS: { int ocn = getint(p), base = getint(p), deposited = getint(p), team = getint(p), score = getint(p), flags = getint(p); fpsent *o = ocn==player1->clientnum ? player1 : newclient(ocn); if(o && m_collect) collectmode.deposittokens(o, base, deposited, team, score, flags); break; } #endif sauerbraten-0.0.20130203.dfsg/fpsgame/aiman.h0000644000175000017500000001776312064164321020272 0ustar vincentvincent// server-side ai manager namespace aiman { bool dorefresh = false; VARN(serverbotlimit, botlimit, 0, 8, MAXBOTS); VARN(serverbotbalance, botbalance, 0, 1, 1); void calcteams(vector &teams) { static const char * const defaults[2] = { "good", "evil" }; loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.state==CS_SPECTATOR || !ci->team[0]) continue; teamscore *t = NULL; loopvj(teams) if(!strcmp(teams[j].team, ci->team)) { t = &teams[j]; break; } if(t) t->score++; else teams.add(teamscore(ci->team, 1)); } teams.sort(teamscore::compare); if(teams.length() < int(sizeof(defaults)/sizeof(defaults[0]))) { loopi(sizeof(defaults)/sizeof(defaults[0])) if(teams.htfind(defaults[i]) < 0) teams.add(teamscore(defaults[i], 0)); } } void balanceteams() { vector teams; calcteams(teams); vector reassign; loopv(bots) if(bots[i]) reassign.add(bots[i]); while(reassign.length() && teams.length() && teams[0].score > teams.last().score + 1) { teamscore &t = teams.last(); clientinfo *bot = NULL; loopv(reassign) if(reassign[i] && !strcmp(reassign[i]->team, teams[0].team)) { bot = reassign.removeunordered(i); teams[0].score--; t.score++; for(int j = teams.length() - 2; j >= 0; j--) { if(teams[j].score >= teams[j+1].score) break; swap(teams[j], teams[j+1]); } break; } if(bot) { if(smode && bot->state.state==CS_ALIVE) smode->changeteam(bot, bot->team, t.team); copystring(bot->team, t.team, MAXTEAMLEN+1); sendf(-1, 1, "riisi", N_SETTEAM, bot->clientnum, bot->team, 0); } else teams.remove(0, 1); } } const char *chooseteam() { vector teams; calcteams(teams); return teams.length() ? teams.last().team : ""; } static inline bool validaiclient(clientinfo *ci) { return ci->clientnum >= 0 && ci->state.aitype == AI_NONE && (ci->state.state!=CS_SPECTATOR || ci->local || ci->privilege); } clientinfo *findaiclient(clientinfo *exclude = NULL) { clientinfo *least = NULL; loopv(clients) { clientinfo *ci = clients[i]; if(!validaiclient(ci) || ci==exclude) continue; if(!least || ci->bots.length() < least->bots.length()) least = ci; } return least; } bool addai(int skill, int limit) { int numai = 0, cn = -1, maxai = limit >= 0 ? min(limit, MAXBOTS) : MAXBOTS; loopv(bots) { clientinfo *ci = bots[i]; if(!ci || ci->ownernum < 0) { if(cn < 0) cn = i; continue; } numai++; } if(numai >= maxai) return false; if(bots.inrange(cn)) { clientinfo *ci = bots[cn]; if(ci) { // reuse a slot that was going to removed clientinfo *owner = findaiclient(); ci->ownernum = owner ? owner->clientnum : -1; if(owner) owner->bots.add(ci); ci->aireinit = 2; dorefresh = true; return true; } } else { cn = bots.length(); bots.add(NULL); } const char *team = m_teammode ? chooseteam() : ""; if(!bots[cn]) bots[cn] = new clientinfo; clientinfo *ci = bots[cn]; ci->clientnum = MAXCLIENTS + cn; ci->state.aitype = AI_BOT; clientinfo *owner = findaiclient(); ci->ownernum = owner ? owner->clientnum : -1; if(owner) owner->bots.add(ci); ci->state.skill = skill <= 0 ? rnd(50) + 51 : clamp(skill, 1, 101); clients.add(ci); ci->state.lasttimeplayed = lastmillis; copystring(ci->name, "bot", MAXNAMELEN+1); ci->state.state = CS_DEAD; copystring(ci->team, team, MAXTEAMLEN+1); ci->playermodel = rnd(128); ci->aireinit = 2; ci->connected = true; dorefresh = true; return true; } void deleteai(clientinfo *ci) { int cn = ci->clientnum - MAXCLIENTS; if(!bots.inrange(cn)) return; if(smode) smode->leavegame(ci, true); sendf(-1, 1, "ri2", N_CDIS, ci->clientnum); clientinfo *owner = (clientinfo *)getclientinfo(ci->ownernum); if(owner) owner->bots.removeobj(ci); clients.removeobj(ci); DELETEP(bots[cn]); dorefresh = true; } bool deleteai() { loopvrev(bots) if(bots[i] && bots[i]->ownernum >= 0) { deleteai(bots[i]); return true; } return false; } void reinitai(clientinfo *ci) { if(ci->ownernum < 0) deleteai(ci); else if(ci->aireinit >= 1) { sendf(-1, 1, "ri6ss", N_INITAI, ci->clientnum, ci->ownernum, ci->state.aitype, ci->state.skill, ci->playermodel, ci->name, ci->team); if(ci->aireinit == 2) { ci->reassign(); if(ci->state.state==CS_ALIVE) sendspawn(ci); else sendresume(ci); } ci->aireinit = 0; } } void shiftai(clientinfo *ci, clientinfo *owner = NULL) { clientinfo *prevowner = (clientinfo *)getclientinfo(ci->ownernum); if(prevowner) prevowner->bots.removeobj(ci); if(!owner) { ci->aireinit = 0; ci->ownernum = -1; } else if(ci->clientnum != owner->clientnum) { ci->aireinit = 2; ci->ownernum = owner->clientnum; owner->bots.add(ci); } dorefresh = true; } void removeai(clientinfo *ci) { // either schedules a removal, or someone else to assign to loopvrev(ci->bots) shiftai(ci->bots[i], findaiclient(ci)); } bool reassignai() { clientinfo *hi = NULL, *lo = NULL; loopv(clients) { clientinfo *ci = clients[i]; if(!validaiclient(ci)) continue; if(!lo || ci->bots.length() < lo->bots.length()) lo = ci; if(!hi || ci->bots.length() > hi->bots.length()) hi = ci; } if(hi && lo && hi->bots.length() - lo->bots.length() > 1) { loopvrev(hi->bots) { shiftai(hi->bots[i], lo); return true; } } return false; } void checksetup() { if(m_teammode && botbalance) balanceteams(); loopvrev(bots) if(bots[i]) reinitai(bots[i]); } void clearai() { // clear and remove all ai immediately loopvrev(bots) if(bots[i]) deleteai(bots[i]); } void checkai() { if(!dorefresh) return; dorefresh = false; if(m_botmode && numclients(-1, false, true)) { checksetup(); while(reassignai()); } else clearai(); } void reqadd(clientinfo *ci, int skill) { if(!ci->local && !ci->privilege) return; if(!addai(skill, !ci->local && ci->privilege < PRIV_ADMIN ? botlimit : -1)) sendf(ci->clientnum, 1, "ris", N_SERVMSG, "failed to create or assign bot"); } void reqdel(clientinfo *ci) { if(!ci->local && !ci->privilege) return; if(!deleteai()) sendf(ci->clientnum, 1, "ris", N_SERVMSG, "failed to remove any bots"); } void setbotlimit(clientinfo *ci, int limit) { if(ci && !ci->local && ci->privilege < PRIV_ADMIN) return; botlimit = clamp(limit, 0, MAXBOTS); dorefresh = true; defformatstring(msg)("bot limit is now %d", botlimit); sendservmsg(msg); } void setbotbalance(clientinfo *ci, bool balance) { if(ci && !ci->local && !ci->privilege) return; botbalance = balance ? 1 : 0; dorefresh = true; defformatstring(msg)("bot team balancing is now %s", botbalance ? "enabled" : "disabled"); sendservmsg(msg); } void changemap() { dorefresh = true; loopv(clients) if(clients[i]->local || clients[i]->privilege) return; if(!botbalance) setbotbalance(NULL, true); } void addclient(clientinfo *ci) { if(ci->state.aitype == AI_NONE) dorefresh = true; } void changeteam(clientinfo *ci) { if(ci->state.aitype == AI_NONE) dorefresh = true; } } sauerbraten-0.0.20130203.dfsg/fpsgame/server.cpp0000644000175000017500000034650012103333514021034 0ustar vincentvincent#include "game.h" namespace game { void parseoptions(vector &args) { loopv(args) #ifndef STANDALONE if(!game::clientoption(args[i])) #endif if(!server::serveroption(args[i])) conoutf(CON_ERROR, "unknown command-line option: %s", args[i]); } const char *gameident() { return "fps"; } } extern ENetAddress masteraddress; namespace server { struct server_entity // server side version of "entity" type { int type; int spawntime; char spawned; }; static const int DEATHMILLIS = 300; struct clientinfo; struct gameevent { virtual ~gameevent() {} virtual bool flush(clientinfo *ci, int fmillis); virtual void process(clientinfo *ci) {} virtual bool keepable() const { return false; } }; struct timedevent : gameevent { int millis; bool flush(clientinfo *ci, int fmillis); }; struct hitinfo { int target; int lifesequence; int rays; float dist; vec dir; }; struct shotevent : timedevent { int id, gun; vec from, to; vector hits; void process(clientinfo *ci); }; struct explodeevent : timedevent { int id, gun; vector hits; bool keepable() const { return true; } void process(clientinfo *ci); }; struct suicideevent : gameevent { void process(clientinfo *ci); }; struct pickupevent : gameevent { int ent; void process(clientinfo *ci); }; template struct projectilestate { int projs[N]; int numprojs; projectilestate() : numprojs(0) {} void reset() { numprojs = 0; } void add(int val) { if(numprojs>=N) numprojs = 0; projs[numprojs++] = val; } bool remove(int val) { loopi(numprojs) if(projs[i]==val) { projs[i] = projs[--numprojs]; return true; } return false; } }; struct gamestate : fpsstate { vec o; int state, editstate; int lastdeath, deadflush, lastspawn, lifesequence; int lastshot; projectilestate<8> rockets, grenades; int frags, flags, deaths, teamkills, shotdamage, damage, tokens; int lasttimeplayed, timeplayed; float effectiveness; gamestate() : state(CS_DEAD), editstate(CS_DEAD), lifesequence(0) {} bool isalive(int gamemillis) { return state==CS_ALIVE || (state==CS_DEAD && gamemillis - lastdeath <= DEATHMILLIS); } bool waitexpired(int gamemillis) { return gamemillis - lastshot >= gunwait; } void reset() { if(state!=CS_SPECTATOR) state = editstate = CS_DEAD; maxhealth = 100; rockets.reset(); grenades.reset(); timeplayed = 0; effectiveness = 0; frags = flags = deaths = teamkills = shotdamage = damage = tokens = 0; lastdeath = 0; respawn(); } void respawn() { fpsstate::respawn(); o = vec(-1e10f, -1e10f, -1e10f); deadflush = 0; lastspawn = -1; lastshot = 0; tokens = 0; } void reassign() { respawn(); rockets.reset(); grenades.reset(); } }; struct savedscore { uint ip; string name; int maxhealth, frags, flags, deaths, teamkills, shotdamage, damage; int timeplayed; float effectiveness; void save(gamestate &gs) { maxhealth = gs.maxhealth; frags = gs.frags; flags = gs.flags; deaths = gs.deaths; teamkills = gs.teamkills; shotdamage = gs.shotdamage; damage = gs.damage; timeplayed = gs.timeplayed; effectiveness = gs.effectiveness; } void restore(gamestate &gs) { if(gs.health==gs.maxhealth) gs.health = maxhealth; gs.maxhealth = maxhealth; gs.frags = frags; gs.flags = flags; gs.deaths = deaths; gs.teamkills = teamkills; gs.shotdamage = shotdamage; gs.damage = damage; gs.timeplayed = timeplayed; gs.effectiveness = effectiveness; } }; extern int gamemillis, nextexceeded; struct clientinfo { int clientnum, ownernum, connectmillis, sessionid, overflow; string name, team, mapvote; int playermodel; int modevote; int privilege; bool connected, local, timesync; int gameoffset, lastevent, pushed, exceeded; gamestate state; vector events; vector position, messages; uchar *wsdata; int wslen; vector bots; int ping, aireinit; string clientmap; int mapcrc; bool warned, gameclip; ENetPacket *getdemo, *getmap, *clipboard; int lastclipboard, needclipboard; int connectauth; uint authreq; string authname, authdesc; void *authchallenge; int authkickvictim; char *authkickreason; clientinfo() : getdemo(NULL), getmap(NULL), clipboard(NULL), authchallenge(NULL), authkickreason(NULL) { reset(); } ~clientinfo() { events.deletecontents(); cleanclipboard(); cleanauth(); } void addevent(gameevent *e) { if(state.state==CS_SPECTATOR || events.length()>100) delete e; else events.add(e); } enum { PUSHMILLIS = 2500 }; int calcpushrange() { ENetPeer *peer = getclientpeer(ownernum); return PUSHMILLIS + (peer ? peer->roundTripTime + peer->roundTripTimeVariance : ENET_PEER_DEFAULT_ROUND_TRIP_TIME); } bool checkpushed(int millis, int range) { return millis >= pushed - range && millis <= pushed + range; } void scheduleexceeded() { if(state.state!=CS_ALIVE || !exceeded) return; int range = calcpushrange(); if(!nextexceeded || exceeded + range < nextexceeded) nextexceeded = exceeded + range; } void setexceeded() { if(state.state==CS_ALIVE && !exceeded && !checkpushed(gamemillis, calcpushrange())) exceeded = gamemillis; scheduleexceeded(); } void setpushed() { pushed = max(pushed, gamemillis); if(exceeded && checkpushed(exceeded, calcpushrange())) exceeded = 0; } bool checkexceeded() { return state.state==CS_ALIVE && exceeded && gamemillis > exceeded + calcpushrange(); } void mapchange() { mapvote[0] = 0; modevote = INT_MAX; state.reset(); events.deletecontents(); overflow = 0; timesync = false; lastevent = 0; exceeded = 0; pushed = 0; clientmap[0] = '\0'; mapcrc = 0; warned = false; gameclip = false; } void reassign() { state.reassign(); events.deletecontents(); timesync = false; lastevent = 0; } void cleanclipboard(bool fullclean = true) { if(clipboard) { if(--clipboard->referenceCount <= 0) enet_packet_destroy(clipboard); clipboard = NULL; } if(fullclean) lastclipboard = 0; } void cleanauthkick() { authkickvictim = -1; DELETEA(authkickreason); } void cleanauth(bool full = true) { authreq = 0; if(authchallenge) { freechallenge(authchallenge); authchallenge = NULL; } if(full) cleanauthkick(); } void reset() { name[0] = team[0] = 0; playermodel = -1; privilege = PRIV_NONE; connected = local = false; connectauth = 0; position.setsize(0); messages.setsize(0); ping = 0; aireinit = 0; needclipboard = 0; cleanclipboard(); cleanauth(); mapchange(); } int geteventmillis(int servmillis, int clientmillis) { if(!timesync || (events.empty() && state.waitexpired(servmillis))) { timesync = true; gameoffset = servmillis - clientmillis; return servmillis; } else return gameoffset + clientmillis; } }; struct ban { int time, expire; uint ip; }; namespace aiman { extern void removeai(clientinfo *ci); extern void clearai(); extern void checkai(); extern void reqadd(clientinfo *ci, int skill); extern void reqdel(clientinfo *ci); extern void setbotlimit(clientinfo *ci, int limit); extern void setbotbalance(clientinfo *ci, bool balance); extern void changemap(); extern void addclient(clientinfo *ci); extern void changeteam(clientinfo *ci); } #define MM_MODE 0xF #define MM_AUTOAPPROVE 0x1000 #define MM_PRIVSERV (MM_MODE | MM_AUTOAPPROVE) #define MM_PUBSERV ((1< allowedips; vector bannedips; void addban(uint ip, int expire) { allowedips.removeobj(ip); ban b; b.time = totalmillis; b.expire = totalmillis + expire; b.ip = ip; loopv(bannedips) if(b.expire < bannedips[i].expire) { bannedips.insert(i, b); return; } bannedips.add(b); } vector connects, clients, bots; void kickclients(uint ip, clientinfo *actor = NULL) { loopvrev(clients) { clientinfo &c = *clients[i]; if(c.state.aitype != AI_NONE || c.privilege >= PRIV_ADMIN || c.local) continue; if(actor && (c.privilege > actor->privilege || c.clientnum == actor->clientnum)) continue; if(getclientip(c.clientnum) == ip) disconnect_client(c.clientnum, DISC_KICK); } } struct maprotation { static int exclude; int modes; string map; int calcmodemask() const { return modes&(1< maprotations; int curmaprotation = 0; VAR(lockmaprotation, 0, 0, 2); void maprotationreset() { maprotations.setsize(0); curmaprotation = 0; maprotation::exclude = 0; } void nextmaprotation() { curmaprotation++; if(maprotations.inrange(curmaprotation) && maprotations[curmaprotation].modes) return; do curmaprotation--; while(maprotations.inrange(curmaprotation) && maprotations[curmaprotation].modes); curmaprotation++; } int findmaprotation(int mode, const char *map) { for(int i = curmaprotation; i < maprotations.length(); i++) { maprotation &rot = maprotations[i]; if(!rot.modes) break; if(rot.match(mode, map)) return i; } int start; for(start = curmaprotation - 1; start >= 0; start--) if(!maprotations[start].modes) break; start++; for(int i = start; i < curmaprotation; i++) { maprotation &rot = maprotations[i]; if(!rot.modes) break; if(rot.match(mode, map)) return i; } int best = -1; loopv(maprotations) { maprotation &rot = maprotations[i]; if(rot.match(mode, map) && (best < 0 || maprotations[best].includes(rot))) best = i; } return best; } bool searchmodename(const char *haystack, const char *needle) { if(!needle[0]) return true; do { if(needle[0] != '.') { haystack = strchr(haystack, needle[0]); if(!haystack) break; haystack++; } const char *h = haystack, *n = needle+1; for(; *h && *n; h++) { if(*h == *n) n++; else if(*h != ' ') break; } if(!*n) return true; if(*n == '.') return !*h; } while(needle[0] != '.'); return false; } int genmodemask(vector &modes) { int modemask = 0; loopv(modes) { const char *mode = modes[i]; int op = mode[0]; switch(mode[0]) { case '*': modemask |= 1< modes, maps; for(int i = 0; i + 1 < numargs; i += 2) { explodelist(args[i].getstr(), modes); explodelist(args[i+1].getstr(), maps); int modemask = genmodemask(modes); if(maps.length()) loopvj(maps) addmaprotation(modemask, maps[j]); else addmaprotation(modemask, ""); modes.deletearrays(); maps.deletearrays(); } if(maprotations.length() && maprotations.last().modes) { maprotation &rot = maprotations.add(); rot.modes = 0; rot.map[0] = '\0'; } } COMMAND(maprotationreset, ""); COMMANDN(maprotation, addmaprotations, "ss2V"); struct demofile { string info; uchar *data; int len; }; vector demos; bool demonextmatch = false; stream *demotmp = NULL, *demorecord = NULL, *demoplayback = NULL; int nextplayback = 0, demomillis = 0; VAR(maxdemos, 0, 5, 25); VAR(maxdemosize, 0, 16, 64); VAR(restrictdemos, 0, 1, 1); VAR(restrictpausegame, 0, 1, 1); VAR(restrictgamespeed, 0, 1, 1); SVAR(serverdesc, ""); SVAR(serverpass, ""); SVAR(adminpass, ""); VARF(publicserver, 0, 0, 2, { switch(publicserver) { case 0: default: mastermask = MM_PRIVSERV; break; case 1: mastermask = MM_PUBSERV; break; case 2: mastermask = MM_COOPSERV; break; } }); SVAR(servermotd, ""); struct teamkillkick { int modes, limit, ban; bool match(int mode) const { return (modes&(1<<(mode-STARTGAMEMODE)))!=0; } bool includes(const teamkillkick &tk) const { return tk.modes != modes && (tk.modes & modes) == tk.modes; } }; vector teamkillkicks; void teamkillkickreset() { teamkillkicks.setsize(0); } void addteamkillkick(char *modestr, int *limit, int *ban) { vector modes; explodelist(modestr, modes); teamkillkick &kick = teamkillkicks.add(); kick.modes = genmodemask(modes); kick.limit = *limit; kick.ban = *ban > 0 ? *ban*60000 : (*ban < 0 ? 0 : 30*60000); modes.deletearrays(); } COMMAND(teamkillkickreset, ""); COMMANDN(teamkillkick, addteamkillkick, "sii"); struct teamkillinfo { uint ip; int teamkills; }; vector teamkills; bool shouldcheckteamkills = false; void addteamkill(clientinfo *actor, clientinfo *victim, int n) { if(!m_timed || actor->state.aitype != AI_NONE || actor->local || actor->privilege || (victim && victim->state.aitype != AI_NONE)) return; shouldcheckteamkills = true; uint ip = getclientip(actor->clientnum); loopv(teamkills) if(teamkills[i].ip == ip) { teamkills[i].teamkills += n; return; } teamkillinfo &tk = teamkills.add(); tk.ip = ip; tk.teamkills = n; } void checkteamkills() { teamkillkick *kick = NULL; if(m_timed) loopv(teamkillkicks) if(teamkillkicks[i].match(gamemode) && (!kick || kick->includes(teamkillkicks[i]))) kick = &teamkillkicks[i]; if(kick) loopvrev(teamkills) { teamkillinfo &tk = teamkills[i]; if(tk.teamkills >= kick->limit) { if(kick->ban > 0) addban(tk.ip, kick->ban); kickclients(tk.ip); teamkills.removeunordered(i); } } shouldcheckteamkills = false; } void *newclientinfo() { return new clientinfo; } void deleteclientinfo(void *ci) { delete (clientinfo *)ci; } clientinfo *getinfo(int n) { if(n < MAXCLIENTS) return (clientinfo *)getclientinfo(n); n -= MAXCLIENTS; return bots.inrange(n) ? bots[n] : NULL; } uint mcrc = 0; vector ments; vector sents; vector scores; int msgsizelookup(int msg) { static int sizetable[NUMMSG] = { -1 }; if(sizetable[0] < 0) { memset(sizetable, -1, sizeof(sizetable)); for(const int *p = msgsizes; *p >= 0; p += 2) sizetable[p[0]] = p[1]; } return msg >= 0 && msg < NUMMSG ? sizetable[msg] : -1; } const char *modename(int n, const char *unknown) { if(m_valid(n)) return gamemodes[n - STARTGAMEMODE].name; return unknown; } const char *mastermodename(int n, const char *unknown) { return (n>=MM_START && size_t(n-MM_START)clientnum!=exclude && (!nospec || ci->state.state!=CS_SPECTATOR || (priv && (ci->privilege || ci->local))) && (!noai || ci->state.aitype == AI_NONE)) n++; } return n; } bool duplicatename(clientinfo *ci, char *name) { if(!name) name = ci->name; loopv(clients) if(clients[i]!=ci && !strcmp(name, clients[i]->name)) return true; return false; } const char *colorname(clientinfo *ci, char *name = NULL) { if(!name) name = ci->name; if(name[0] && !duplicatename(ci, name) && ci->state.aitype == AI_NONE) return name; static string cname[3]; static int cidx = 0; cidx = (cidx+1)%3; formatstring(cname[cidx])(ci->state.aitype == AI_NONE ? "%s \fs\f5(%d)\fr" : "%s \fs\f5[%d]\fr", name, ci->clientnum); return cname[cidx]; } struct servmode { virtual ~servmode() {} virtual void entergame(clientinfo *ci) {} virtual void leavegame(clientinfo *ci, bool disconnecting = false) {} virtual void moved(clientinfo *ci, const vec &oldpos, bool oldclip, const vec &newpos, bool newclip) {} virtual bool canspawn(clientinfo *ci, bool connecting = false) { return true; } virtual void spawned(clientinfo *ci) {} virtual int fragvalue(clientinfo *victim, clientinfo *actor) { if(victim==actor || isteam(victim->team, actor->team)) return -1; return 1; } virtual void died(clientinfo *victim, clientinfo *actor) {} virtual bool canchangeteam(clientinfo *ci, const char *oldteam, const char *newteam) { return true; } virtual void changeteam(clientinfo *ci, const char *oldteam, const char *newteam) {} virtual void initclient(clientinfo *ci, packetbuf &p, bool connecting) {} virtual void update() {} virtual void cleanup() {} virtual void setup() {} virtual void newmap() {} virtual void intermission() {} virtual bool hidefrags() { return false; } virtual int getteamscore(const char *team) { return 0; } virtual void getteamscores(vector &scores) {} virtual bool extinfoteam(const char *team, ucharbuf &p) { return false; } }; #define SERVMODE 1 #include "capture.h" #include "ctf.h" #include "collect.h" captureservmode capturemode; ctfservmode ctfmode; collectservmode collectmode; servmode *smode = NULL; bool canspawnitem(int type) { return !m_noitems && (type>=I_SHELLS && type<=I_QUAD && (!m_noammo || typeI_CARTRIDGES)); } int spawntime(int type) { if(m_classicsp) return INT_MAX; int np = numclients(-1, true, false); np = np<3 ? 4 : (np>4 ? 2 : 3); // spawn times are dependent on number of players int sec = 0; switch(type) { case I_SHELLS: case I_BULLETS: case I_ROCKETS: case I_ROUNDS: case I_GRENADES: case I_CARTRIDGES: sec = np*4; break; case I_HEALTH: sec = np*5; break; case I_GREENARMOUR: sec = 20; break; case I_YELLOWARMOUR: sec = 30; break; case I_BOOST: sec = 60; break; case I_QUAD: sec = 70; break; } return sec*1000; } bool delayspawn(int type) { switch(type) { case I_GREENARMOUR: case I_YELLOWARMOUR: return !m_classicsp; case I_BOOST: case I_QUAD: return true; default: return false; } } bool pickup(int i, int sender) // server side item pickup, acknowledge first client that gets it { if((m_timed && gamemillis>=gamelimit) || !sents.inrange(i) || !sents[i].spawned) return false; clientinfo *ci = getinfo(sender); if(!ci || (!ci->local && !ci->state.canpickup(sents[i].type))) return false; sents[i].spawned = false; sents[i].spawntime = spawntime(sents[i].type); sendf(-1, 1, "ri3", N_ITEMACC, i, sender); ci->state.pickup(sents[i].type); return true; } static hashset teaminfos; void clearteaminfo() { teaminfos.clear(); } bool teamhasplayers(const char *team) { loopv(clients) if(!strcmp(clients[i]->team, team)) return true; return false; } bool pruneteaminfo() { int oldteams = teaminfos.numelems; enumerates(teaminfos, teaminfo, old, if(!old.frags && !teamhasplayers(old.team)) teaminfos.remove(old.team); ); return teaminfos.numelems < oldteams; } teaminfo *addteaminfo(const char *team) { teaminfo *t = teaminfos.access(team); if(!t) { if(teaminfos.numelems >= MAXTEAMS && !pruneteaminfo()) return NULL; t = &teaminfos[team]; copystring(t->team, team, sizeof(t->team)); t->frags = 0; } return t; } clientinfo *choosebestclient(float &bestrank) { clientinfo *best = NULL; bestrank = -1; loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.timeplayed<0) continue; float rank = ci->state.state!=CS_SPECTATOR ? ci->state.effectiveness/max(ci->state.timeplayed, 1) : -1; if(!best || rank > bestrank) { best = ci; bestrank = rank; } } return best; } void autoteam() { static const char * const teamnames[2] = {"good", "evil"}; vector team[2]; float teamrank[2] = {0, 0}; for(int round = 0, remaining = clients.length(); remaining>=0; round++) { int first = round&1, second = (round+1)&1, selected = 0; while(teamrank[first] <= teamrank[second]) { float rank; clientinfo *ci = choosebestclient(rank); if(!ci) break; if(smode && smode->hidefrags()) rank = 1; else if(selected && rank<=0) break; ci->state.timeplayed = -1; team[first].add(ci); if(rank>0) teamrank[first] += rank; selected++; if(rank<=0) break; } if(!selected) break; remaining -= selected; } loopi(sizeof(team)/sizeof(team[0])) { addteaminfo(teamnames[i]); loopvj(team[i]) { clientinfo *ci = team[i][j]; if(!strcmp(ci->team, teamnames[i])) continue; copystring(ci->team, teamnames[i], MAXTEAMLEN+1); sendf(-1, 1, "riisi", N_SETTEAM, ci->clientnum, teamnames[i], -1); } } } struct teamrank { const char *name; float rank; int clients; teamrank(const char *name) : name(name), rank(0), clients(0) {} }; const char *chooseworstteam(const char *suggest = NULL, clientinfo *exclude = NULL) { teamrank teamranks[2] = { teamrank("good"), teamrank("evil") }; const int numteams = sizeof(teamranks)/sizeof(teamranks[0]); loopv(clients) { clientinfo *ci = clients[i]; if(ci==exclude || ci->state.aitype!=AI_NONE || ci->state.state==CS_SPECTATOR || !ci->team[0]) continue; ci->state.timeplayed += lastmillis - ci->state.lasttimeplayed; ci->state.lasttimeplayed = lastmillis; loopj(numteams) if(!strcmp(ci->team, teamranks[j].name)) { teamrank &ts = teamranks[j]; ts.rank += ci->state.effectiveness/max(ci->state.timeplayed, 1); ts.clients++; break; } } teamrank *worst = &teamranks[numteams-1]; loopi(numteams-1) { teamrank &ts = teamranks[i]; if(smode && smode->hidefrags()) { if(ts.clients < worst->clients || (ts.clients == worst->clients && ts.rank < worst->rank)) worst = &ts; } else if(ts.rank < worst->rank || (ts.rank == worst->rank && ts.clients < worst->clients)) worst = &ts; } return worst->name; } void prunedemos(int extra = 0) { int n = clamp(demos.length() + extra - maxdemos, 0, demos.length()); if(n <= 0) return; loopi(n) delete[] demos[i].data; demos.remove(0, n); } void adddemo() { if(!demotmp) return; int len = (int)min(demotmp->size(), stream::offset((maxdemosize<<20) + 0x10000)); demofile &d = demos.add(); time_t t = time(NULL); char *timestr = ctime(&t), *trim = timestr + strlen(timestr); while(trim>timestr && iscubespace(*--trim)) *trim = '\0'; formatstring(d.info)("%s: %s, %s, %.2f%s", timestr, modename(gamemode), smapname, len > 1024*1024 ? len/(1024*1024.f) : len/1024.0f, len > 1024*1024 ? "MB" : "kB"); sendservmsgf("demo \"%s\" recorded", d.info); d.data = new uchar[len]; d.len = len; demotmp->seek(0, SEEK_SET); demotmp->read(d.data, len); DELETEP(demotmp); } void enddemorecord() { if(!demorecord) return; DELETEP(demorecord); if(!demotmp) return; if(!maxdemos || !maxdemosize) { DELETEP(demotmp); return; } prunedemos(1); adddemo(); } void writedemo(int chan, void *data, int len) { if(!demorecord) return; int stamp[3] = { gamemillis, chan, len }; lilswap(stamp, 3); demorecord->write(stamp, sizeof(stamp)); demorecord->write(data, len); if(demorecord->rawtell() >= (maxdemosize<<20)) enddemorecord(); } void recordpacket(int chan, void *data, int len) { writedemo(chan, data, len); } int welcomepacket(packetbuf &p, clientinfo *ci); void sendwelcome(clientinfo *ci); void setupdemorecord() { if(!m_mp(gamemode) || m_edit) return; demotmp = opentempfile("demorecord", "w+b"); if(!demotmp) return; stream *f = opengzfile(NULL, "wb", demotmp); if(!f) { DELETEP(demotmp); return; } sendservmsg("recording demo"); demorecord = f; demoheader hdr; memcpy(hdr.magic, DEMO_MAGIC, sizeof(hdr.magic)); hdr.version = DEMO_VERSION; hdr.protocol = PROTOCOL_VERSION; lilswap(&hdr.version, 2); demorecord->write(&hdr, sizeof(demoheader)); packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); welcomepacket(p, NULL); writedemo(1, p.buf, p.len); } void listdemos(int cn) { packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); putint(p, N_SENDDEMOLIST); putint(p, demos.length()); loopv(demos) sendstring(demos[i].info, p); sendpacket(cn, 1, p.finalize()); } void cleardemos(int n) { if(!n) { loopv(demos) delete[] demos[i].data; demos.shrink(0); sendservmsg("cleared all demos"); } else if(demos.inrange(n-1)) { delete[] demos[n-1].data; demos.remove(n-1); sendservmsgf("cleared demo %d", n); } } static void freegetmap(ENetPacket *packet) { loopv(clients) { clientinfo *ci = clients[i]; if(ci->getmap == packet) ci->getmap = NULL; } } static void freegetdemo(ENetPacket *packet) { loopv(clients) { clientinfo *ci = clients[i]; if(ci->getdemo == packet) ci->getdemo = NULL; } } void senddemo(clientinfo *ci, int num) { if(ci->getdemo) return; if(!num) num = demos.length(); if(!demos.inrange(num-1)) return; demofile &d = demos[num-1]; if((ci->getdemo = sendf(ci->clientnum, 2, "rim", N_SENDDEMO, d.len, d.data))) ci->getdemo->freeCallback = freegetdemo; } void enddemoplayback() { if(!demoplayback) return; DELETEP(demoplayback); loopv(clients) sendf(clients[i]->clientnum, 1, "ri3", N_DEMOPLAYBACK, 0, clients[i]->clientnum); sendservmsg("demo playback finished"); loopv(clients) sendwelcome(clients[i]); } void setupdemoplayback() { if(demoplayback) return; demoheader hdr; string msg; msg[0] = '\0'; defformatstring(file)("%s.dmo", smapname); demoplayback = opengzfile(file, "rb"); if(!demoplayback) formatstring(msg)("could not read demo \"%s\"", file); else if(demoplayback->read(&hdr, sizeof(demoheader))!=sizeof(demoheader) || memcmp(hdr.magic, DEMO_MAGIC, sizeof(hdr.magic))) formatstring(msg)("\"%s\" is not a demo file", file); else { lilswap(&hdr.version, 2); if(hdr.version!=DEMO_VERSION) formatstring(msg)("demo \"%s\" requires an %s version of Cube 2: Sauerbraten", file, hdr.versionread(&nextplayback, sizeof(nextplayback))!=sizeof(nextplayback)) { enddemoplayback(); return; } lilswap(&nextplayback, 1); } void readdemo() { if(!demoplayback) return; demomillis += curtime; while(demomillis>=nextplayback) { int chan, len; if(demoplayback->read(&chan, sizeof(chan))!=sizeof(chan) || demoplayback->read(&len, sizeof(len))!=sizeof(len)) { enddemoplayback(); return; } lilswap(&chan, 1); lilswap(&len, 1); ENetPacket *packet = enet_packet_create(NULL, len+1, 0); if(!packet || demoplayback->read(packet->data+1, len)!=len) { if(packet) enet_packet_destroy(packet); enddemoplayback(); return; } packet->data[0] = N_DEMOPACKET; sendpacket(-1, chan, packet); if(!packet->referenceCount) enet_packet_destroy(packet); if(!demoplayback) break; if(demoplayback->read(&nextplayback, sizeof(nextplayback))!=sizeof(nextplayback)) { enddemoplayback(); return; } lilswap(&nextplayback, 1); } } void stopdemo() { if(m_demo) enddemoplayback(); else enddemorecord(); } void pausegame(bool val, clientinfo *ci = NULL) { if(gamepaused==val) return; gamepaused = val; sendf(-1, 1, "riii", N_PAUSEGAME, gamepaused ? 1 : 0, ci ? ci->clientnum : -1); } void checkpausegame() { if(!gamepaused) return; int admins = 0; loopv(clients) if(clients[i]->privilege >= (restrictpausegame ? PRIV_ADMIN : PRIV_MASTER) || clients[i]->local) admins++; if(!admins) pausegame(false); } void forcepaused(bool paused) { pausegame(paused); } bool ispaused() { return gamepaused; } void changegamespeed(int val, clientinfo *ci = NULL) { val = clamp(val, 10, 1000); if(gamespeed==val) return; gamespeed = val; sendf(-1, 1, "riii", N_GAMESPEED, gamespeed, ci ? ci->clientnum : -1); } void forcegamespeed(int speed) { changegamespeed(speed); } int scaletime(int t) { return t*gamespeed; } SVAR(serverauth, ""); struct userkey { char *name; char *desc; userkey() : name(NULL), desc(NULL) {} userkey(char *name, char *desc) : name(name), desc(desc) {} }; static inline uint hthash(const userkey &k) { return ::hthash(k.name); } static inline bool htcmp(const userkey &x, const userkey &y) { return !strcmp(x.name, y.name) && !strcmp(x.desc, y.desc); } struct userinfo : userkey { void *pubkey; int privilege; userinfo() : pubkey(NULL), privilege(PRIV_NONE) {} ~userinfo() { delete[] name; delete[] desc; if(pubkey) freepubkey(pubkey); } }; hashset users; void adduser(char *name, char *desc, char *pubkey, char *priv) { userkey key(name, desc); userinfo &u = users[key]; if(u.pubkey) { freepubkey(u.pubkey); u.pubkey = NULL; } if(!u.name) u.name = newstring(name); if(!u.desc) u.desc = newstring(desc); u.pubkey = parsepubkey(pubkey); switch(priv[0]) { case 'a': case 'A': u.privilege = PRIV_ADMIN; break; case 'm': case 'M': default: u.privilege = PRIV_AUTH; break; } } COMMAND(adduser, "ssss"); void clearusers() { users.clear(); } COMMAND(clearusers, ""); void hashpassword(int cn, int sessionid, const char *pwd, char *result, int maxlen) { char buf[2*sizeof(string)]; formatstring(buf)("%d %d ", cn, sessionid); copystring(&buf[strlen(buf)], pwd); if(!hashstring(buf, result, maxlen)) *result = '\0'; } bool checkpassword(clientinfo *ci, const char *wanted, const char *given) { string hash; hashpassword(ci->clientnum, ci->sessionid, wanted, hash, sizeof(hash)); return !strcmp(hash, given); } void revokemaster(clientinfo *ci) { ci->privilege = PRIV_NONE; if(ci->state.state==CS_SPECTATOR && !ci->local) aiman::removeai(ci); } extern void connected(clientinfo *ci); bool setmaster(clientinfo *ci, bool val, const char *pass = "", const char *authname = NULL, const char *authdesc = NULL, int authpriv = PRIV_MASTER, bool force = false, bool trial = false) { if(authname && !val) return false; const char *name = ""; if(val) { bool haspass = adminpass[0] && checkpassword(ci, adminpass, pass); int wantpriv = ci->local || haspass ? PRIV_ADMIN : authpriv; if(ci->privilege) { if(wantpriv <= ci->privilege) return true; } else if(wantpriv <= PRIV_MASTER && !force) { if(ci->state.state==CS_SPECTATOR) { sendf(ci->clientnum, 1, "ris", N_SERVMSG, "Spectators may not claim master."); return false; } loopv(clients) if(ci!=clients[i] && clients[i]->privilege) { sendf(ci->clientnum, 1, "ris", N_SERVMSG, "Master is already claimed."); return false; } if(!authname && !(mastermask&MM_AUTOAPPROVE) && !ci->privilege && !ci->local) { sendf(ci->clientnum, 1, "ris", N_SERVMSG, "This server requires you to use the \"/auth\" command to claim master."); return false; } } if(trial) return true; ci->privilege = wantpriv; name = privname(ci->privilege); } else { if(!ci->privilege) return false; if(trial) return true; name = privname(ci->privilege); revokemaster(ci); } bool hasmaster = false; loopv(clients) if(clients[i]->local || clients[i]->privilege >= PRIV_MASTER) hasmaster = true; if(!hasmaster) { mastermode = MM_OPEN; allowedips.shrink(0); } string msg; if(val && authname) { if(authdesc && authdesc[0]) formatstring(msg)("%s claimed %s as '\fs\f5%s\fr' [\fs\f0%s\fr]", colorname(ci), name, authname, authdesc); else formatstring(msg)("%s claimed %s as '\fs\f5%s\fr'", colorname(ci), name, authname); } else formatstring(msg)("%s %s %s", colorname(ci), val ? "claimed" : "relinquished", name); packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); putint(p, N_SERVMSG); sendstring(msg, p); putint(p, N_CURRENTMASTER); putint(p, mastermode); loopv(clients) if(clients[i]->privilege >= PRIV_MASTER) { putint(p, clients[i]->clientnum); putint(p, clients[i]->privilege); } putint(p, -1); sendpacket(-1, 1, p.finalize()); checkpausegame(); return true; } bool trykick(clientinfo *ci, int victim, const char *reason = NULL, const char *authname = NULL, const char *authdesc = NULL, int authpriv = PRIV_NONE, bool trial = false) { int priv = ci->privilege; if(authname) { if(priv >= authpriv || ci->local) authname = authdesc = NULL; else priv = authpriv; } if((priv || ci->local) && ci->clientnum!=victim) { clientinfo *vinfo = (clientinfo *)getclientinfo(victim); if(vinfo && (priv >= vinfo->privilege || ci->local) && vinfo->privilege < PRIV_ADMIN && !vinfo->local) { if(trial) return true; string kicker; if(authname) { if(authdesc && authdesc[0]) formatstring(kicker)("%s as '\fs\f5%s\fr' [\fs\f0%s\fr]", colorname(ci), authname, authdesc); else formatstring(kicker)("%s as '\fs\f5%s\fr'", colorname(ci), authname); } else copystring(kicker, colorname(ci)); if(reason && reason[0]) sendservmsgf("%s kicked %s because: %s", kicker, colorname(vinfo), reason); else sendservmsgf("%s kicked %s", kicker, colorname(vinfo)); uint ip = getclientip(victim); addban(ip, 4*60*60000); kickclients(ip, ci); } } return false; } savedscore *findscore(clientinfo *ci, bool insert) { uint ip = getclientip(ci->clientnum); if(!ip && !ci->local) return 0; if(!insert) { loopv(clients) { clientinfo *oi = clients[i]; if(oi->clientnum != ci->clientnum && getclientip(oi->clientnum) == ip && !strcmp(oi->name, ci->name)) { oi->state.timeplayed += lastmillis - oi->state.lasttimeplayed; oi->state.lasttimeplayed = lastmillis; static savedscore curscore; curscore.save(oi->state); return &curscore; } } } loopv(scores) { savedscore &sc = scores[i]; if(sc.ip == ip && !strcmp(sc.name, ci->name)) return ≻ } if(!insert) return 0; savedscore &sc = scores.add(); sc.ip = ip; copystring(sc.name, ci->name); return ≻ } void savescore(clientinfo *ci) { savedscore *sc = findscore(ci, true); if(sc) sc->save(ci->state); } int checktype(int type, clientinfo *ci) { if(ci) { if(!ci->connected) return type == (ci->connectauth ? N_AUTHANS : N_CONNECT) || type == N_PING ? type : -1; if(ci->local) return type; } // only allow edit messages in coop-edit mode if(type>=N_EDITENT && type<=N_EDITVAR && !m_edit) return -1; // server only messages static const int servtypes[] = { N_SERVINFO, N_INITCLIENT, N_WELCOME, N_MAPCHANGE, N_SERVMSG, N_DAMAGE, N_HITPUSH, N_SHOTFX, N_EXPLODEFX, N_DIED, N_SPAWNSTATE, N_FORCEDEATH, N_TEAMINFO, N_ITEMACC, N_ITEMSPAWN, N_TIMEUP, N_CDIS, N_CURRENTMASTER, N_PONG, N_RESUME, N_BASESCORE, N_BASEINFO, N_BASEREGEN, N_ANNOUNCE, N_SENDDEMOLIST, N_SENDDEMO, N_DEMOPLAYBACK, N_SENDMAP, N_DROPFLAG, N_SCOREFLAG, N_RETURNFLAG, N_RESETFLAG, N_INVISFLAG, N_CLIENT, N_AUTHCHAL, N_INITAI, N_EXPIRETOKENS, N_DROPTOKENS, N_STEALTOKENS, N_DEMOPACKET }; if(ci) { loopi(sizeof(servtypes)/sizeof(int)) if(type == servtypes[i]) return -1; if(type < N_EDITENT || type > N_EDITVAR || !m_edit) { if(type != N_POS && ++ci->overflow >= 200) return -2; } } return type; } struct worldstate { int uses, len; uchar *data; worldstate() : uses(0), len(0), data(NULL) {} void setup(int n) { len = n; data = new uchar[n]; } void cleanup() { DELETEA(data); len = 0; } bool contains(const uchar *p) const { return p >= data && p < &data[len]; } }; vector worldstates; bool reliablemessages = false; void cleanworldstate(ENetPacket *packet) { loopv(worldstates) { worldstate &ws = worldstates[i]; if(!ws.contains(packet->data)) continue; ws.uses--; if(ws.uses <= 0) { ws.cleanup(); worldstates.removeunordered(i); } break; } } void flushclientposition(clientinfo &ci) { if(ci.position.empty() || (!hasnonlocalclients() && !demorecord)) return; packetbuf p(ci.position.length(), 0); p.put(ci.position.getbuf(), ci.position.length()); ci.position.setsize(0); sendpacket(-1, 0, p.finalize(), ci.ownernum); } static void sendpositions(worldstate &ws, ucharbuf &wsbuf) { if(wsbuf.empty()) return; int wslen = wsbuf.length(); recordpacket(0, wsbuf.buf, wslen); wsbuf.put(wsbuf.buf, wslen); loopv(clients) { clientinfo &ci = *clients[i]; if(ci.state.aitype != AI_NONE) continue; uchar *data = wsbuf.buf; int size = wslen; if(ci.wsdata >= wsbuf.buf) { data = ci.wsdata + ci.wslen; size -= ci.wslen; } if(size <= 0) continue; ENetPacket *packet = enet_packet_create(data, size, ENET_PACKET_FLAG_NO_ALLOCATE); sendpacket(ci.clientnum, 0, packet); if(packet->referenceCount) { ws.uses++; packet->freeCallback = cleanworldstate; } else enet_packet_destroy(packet); } wsbuf.offset(wsbuf.length()); } static inline void addposition(worldstate &ws, ucharbuf &wsbuf, int mtu, clientinfo &bi, clientinfo &ci) { if(bi.position.empty()) return; if(wsbuf.length() + bi.position.length() > mtu) sendpositions(ws, wsbuf); int offset = wsbuf.length(); wsbuf.put(bi.position.getbuf(), bi.position.length()); bi.position.setsize(0); int len = wsbuf.length() - offset; if(ci.wsdata < wsbuf.buf) { ci.wsdata = &wsbuf.buf[offset]; ci.wslen = len; } else ci.wslen += len; } static void sendmessages(worldstate &ws, ucharbuf &wsbuf) { if(wsbuf.empty()) return; int wslen = wsbuf.length(); recordpacket(1, wsbuf.buf, wslen); wsbuf.put(wsbuf.buf, wslen); loopv(clients) { clientinfo &ci = *clients[i]; if(ci.state.aitype != AI_NONE) continue; uchar *data = wsbuf.buf; int size = wslen; if(ci.wsdata >= wsbuf.buf) { data = ci.wsdata + ci.wslen; size -= ci.wslen; } if(size <= 0) continue; ENetPacket *packet = enet_packet_create(data, size, (reliablemessages ? ENET_PACKET_FLAG_RELIABLE : 0) | ENET_PACKET_FLAG_NO_ALLOCATE); sendpacket(ci.clientnum, 1, packet); if(packet->referenceCount) { ws.uses++; packet->freeCallback = cleanworldstate; } else enet_packet_destroy(packet); } wsbuf.offset(wsbuf.length()); } static inline void addmessages(worldstate &ws, ucharbuf &wsbuf, int mtu, clientinfo &bi, clientinfo &ci) { if(bi.messages.empty()) return; if(wsbuf.length() + 10 + bi.messages.length() > mtu) sendmessages(ws, wsbuf); int offset = wsbuf.length(); putint(wsbuf, N_CLIENT); putint(wsbuf, bi.clientnum); putuint(wsbuf, bi.messages.length()); wsbuf.put(bi.messages.getbuf(), bi.messages.length()); bi.messages.setsize(0); int len = wsbuf.length() - offset; if(ci.wsdata < wsbuf.buf) { ci.wsdata = &wsbuf.buf[offset]; ci.wslen = len; } else ci.wslen += len; } bool buildworldstate() { int wsmax = 0; loopv(clients) { clientinfo &ci = *clients[i]; ci.overflow = 0; ci.wsdata = NULL; wsmax += ci.position.length(); if(ci.messages.length()) wsmax += 10 + ci.messages.length(); } if(wsmax <= 0) { reliablemessages = false; return false; } worldstate &ws = worldstates.add(); ws.setup(2*wsmax); int mtu = getservermtu() - 100; if(mtu <= 0) mtu = ws.len; ucharbuf wsbuf(ws.data, ws.len); loopv(clients) { clientinfo &ci = *clients[i]; if(ci.state.aitype != AI_NONE) continue; addposition(ws, wsbuf, mtu, ci, ci); loopvj(ci.bots) addposition(ws, wsbuf, mtu, *ci.bots[j], ci); } sendpositions(ws, wsbuf); loopv(clients) { clientinfo &ci = *clients[i]; if(ci.state.aitype != AI_NONE) continue; addmessages(ws, wsbuf, mtu, ci, ci); loopvj(ci.bots) addmessages(ws, wsbuf, mtu, *ci.bots[j], ci); } sendmessages(ws, wsbuf); reliablemessages = false; if(ws.uses) return true; ws.cleanup(); worldstates.drop(); return false; } bool sendpackets(bool force) { if(clients.empty() || (!hasnonlocalclients() && !demorecord)) return false; enet_uint32 curtime = enet_time_get()-lastsend; if(curtime<33 && !force) return false; bool flush = buildworldstate(); lastsend += curtime - (curtime%33); return flush; } template void sendstate(gamestate &gs, T &p) { putint(p, gs.lifesequence); putint(p, gs.health); putint(p, gs.maxhealth); putint(p, gs.armour); putint(p, gs.armourtype); putint(p, gs.gunselect); loopi(GUN_PISTOL-GUN_SG+1) putint(p, gs.ammo[GUN_SG+i]); } void spawnstate(clientinfo *ci) { gamestate &gs = ci->state; gs.spawnstate(gamemode); gs.lifesequence = (gs.lifesequence + 1)&0x7F; } void sendspawn(clientinfo *ci) { gamestate &gs = ci->state; spawnstate(ci); sendf(ci->ownernum, 1, "rii7v", N_SPAWNSTATE, ci->clientnum, gs.lifesequence, gs.health, gs.maxhealth, gs.armour, gs.armourtype, gs.gunselect, GUN_PISTOL-GUN_SG+1, &gs.ammo[GUN_SG]); gs.lastspawn = gamemillis; } void sendwelcome(clientinfo *ci) { packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); int chan = welcomepacket(p, ci); sendpacket(ci->clientnum, chan, p.finalize()); } void putinitclient(clientinfo *ci, packetbuf &p) { if(ci->state.aitype != AI_NONE) { putint(p, N_INITAI); putint(p, ci->clientnum); putint(p, ci->ownernum); putint(p, ci->state.aitype); putint(p, ci->state.skill); putint(p, ci->playermodel); sendstring(ci->name, p); sendstring(ci->team, p); } else { putint(p, N_INITCLIENT); putint(p, ci->clientnum); sendstring(ci->name, p); sendstring(ci->team, p); putint(p, ci->playermodel); } } void welcomeinitclient(packetbuf &p, int exclude = -1) { loopv(clients) { clientinfo *ci = clients[i]; if(!ci->connected || ci->clientnum == exclude) continue; putinitclient(ci, p); } } bool hasmap(clientinfo *ci) { return (m_edit && (clients.length() > 0 || ci->local)) || (smapname[0] && (!m_timed || gamemillis < gamelimit || (ci->state.state==CS_SPECTATOR && !ci->privilege && !ci->local) || numclients(ci->clientnum, true, true, true))); } int welcomepacket(packetbuf &p, clientinfo *ci) { putint(p, N_WELCOME); putint(p, N_MAPCHANGE); sendstring(smapname, p); putint(p, gamemode); putint(p, notgotitems ? 1 : 0); if(!ci || (m_timed && smapname[0])) { putint(p, N_TIMEUP); putint(p, gamemillis < gamelimit && !interm ? max((gamelimit - gamemillis)/1000, 1) : 0); } if(!notgotitems) { putint(p, N_ITEMLIST); loopv(sents) if(sents[i].spawned) { putint(p, i); putint(p, sents[i].type); } putint(p, -1); } bool hasmaster = false; if(mastermode != MM_OPEN) { putint(p, N_CURRENTMASTER); putint(p, mastermode); hasmaster = true; } loopv(clients) if(clients[i]->privilege >= PRIV_MASTER) { if(!hasmaster) { putint(p, N_CURRENTMASTER); putint(p, mastermode); hasmaster = true; } putint(p, clients[i]->clientnum); putint(p, clients[i]->privilege); } if(hasmaster) putint(p, -1); if(gamepaused) { putint(p, N_PAUSEGAME); putint(p, 1); putint(p, -1); } if(gamespeed != 100) { putint(p, N_GAMESPEED); putint(p, gamespeed); putint(p, -1); } if(m_teammode) { putint(p, N_TEAMINFO); enumerates(teaminfos, teaminfo, t, if(t.frags) { sendstring(t.team, p); putint(p, t.frags); } ); sendstring("", p); } if(ci) { putint(p, N_SETTEAM); putint(p, ci->clientnum); sendstring(ci->team, p); putint(p, -1); } if(ci && (m_demo || m_mp(gamemode)) && ci->state.state!=CS_SPECTATOR) { if(smode && !smode->canspawn(ci, true)) { ci->state.state = CS_DEAD; putint(p, N_FORCEDEATH); putint(p, ci->clientnum); sendf(-1, 1, "ri2x", N_FORCEDEATH, ci->clientnum, ci->clientnum); } else { gamestate &gs = ci->state; spawnstate(ci); putint(p, N_SPAWNSTATE); putint(p, ci->clientnum); sendstate(gs, p); gs.lastspawn = gamemillis; } } if(ci && ci->state.state==CS_SPECTATOR) { putint(p, N_SPECTATOR); putint(p, ci->clientnum); putint(p, 1); sendf(-1, 1, "ri3x", N_SPECTATOR, ci->clientnum, 1, ci->clientnum); } if(!ci || clients.length()>1) { putint(p, N_RESUME); loopv(clients) { clientinfo *oi = clients[i]; if(ci && oi->clientnum==ci->clientnum) continue; putint(p, oi->clientnum); putint(p, oi->state.state); putint(p, oi->state.frags); putint(p, oi->state.flags); putint(p, oi->state.quadmillis); sendstate(oi->state, p); } putint(p, -1); welcomeinitclient(p, ci ? ci->clientnum : -1); } if(smode) smode->initclient(ci, p, true); return 1; } bool restorescore(clientinfo *ci) { //if(ci->local) return false; savedscore *sc = findscore(ci, false); if(sc) { sc->restore(ci->state); return true; } return false; } void sendresume(clientinfo *ci) { gamestate &gs = ci->state; sendf(-1, 1, "ri3i9vi", N_RESUME, ci->clientnum, gs.state, gs.frags, gs.flags, gs.quadmillis, gs.lifesequence, gs.health, gs.maxhealth, gs.armour, gs.armourtype, gs.gunselect, GUN_PISTOL-GUN_SG+1, &gs.ammo[GUN_SG], -1); } void sendinitclient(clientinfo *ci) { packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); putinitclient(ci, p); sendpacket(-1, 1, p.finalize(), ci->clientnum); } void loaditems() { resetitems(); notgotitems = true; if(m_edit || !loadents(smapname, ments, &mcrc)) return; loopv(ments) if(canspawnitem(ments[i].type)) { server_entity se = { NOTUSED, 0, false }; while(sents.length()<=i) sents.add(se); sents[i].type = ments[i].type; if(m_mp(gamemode) && delayspawn(sents[i].type)) sents[i].spawntime = spawntime(sents[i].type); else sents[i].spawned = true; } notgotitems = false; } void changemap(const char *s, int mode) { stopdemo(); pausegame(false); changegamespeed(100); if(smode) smode->cleanup(); aiman::clearai(); gamemode = mode; gamemillis = 0; gamelimit = (m_overtime ? 15 : 10)*60000; interm = 0; nextexceeded = 0; copystring(smapname, s); loaditems(); scores.shrink(0); shouldcheckteamkills = false; teamkills.shrink(0); loopv(clients) { clientinfo *ci = clients[i]; ci->state.timeplayed += lastmillis - ci->state.lasttimeplayed; } if(!m_mp(gamemode)) kicknonlocalclients(DISC_LOCAL); sendf(-1, 1, "risii", N_MAPCHANGE, smapname, gamemode, 1); clearteaminfo(); if(m_teammode) autoteam(); if(m_capture) smode = &capturemode; else if(m_ctf) smode = &ctfmode; else if(m_collect) smode = &collectmode; else smode = NULL; if(m_timed && smapname[0]) sendf(-1, 1, "ri2", N_TIMEUP, gamemillis < gamelimit && !interm ? max((gamelimit - gamemillis)/1000, 1) : 0); loopv(clients) { clientinfo *ci = clients[i]; ci->mapchange(); ci->state.lasttimeplayed = lastmillis; if(m_mp(gamemode) && ci->state.state!=CS_SPECTATOR) sendspawn(ci); } aiman::changemap(); if(m_demo) { if(clients.length()) setupdemoplayback(); } else if(demonextmatch) { demonextmatch = false; setupdemorecord(); } if(smode) smode->setup(); } void rotatemap(bool next) { if(!maprotations.inrange(curmaprotation)) { changemap("", 1); return; } if(next) { curmaprotation = findmaprotation(gamemode, smapname); if(curmaprotation >= 0) nextmaprotation(); else curmaprotation = smapname[0] ? max(findmaprotation(gamemode, ""), 0) : 0; } maprotation &rot = maprotations[curmaprotation]; changemap(rot.map, rot.findmode(gamemode)); } struct votecount { char *map; int mode, count; votecount() {} votecount(char *s, int n) : map(s), mode(n), count(0) {} }; void checkvotes(bool force = false) { vector votes; int maxvotes = 0; loopv(clients) { clientinfo *oi = clients[i]; if(oi->state.state==CS_SPECTATOR && !oi->privilege && !oi->local) continue; if(oi->state.aitype!=AI_NONE) continue; maxvotes++; if(!m_valid(oi->modevote)) continue; votecount *vc = NULL; loopvj(votes) if(!strcmp(oi->mapvote, votes[j].map) && oi->modevote==votes[j].mode) { vc = &votes[j]; break; } if(!vc) vc = &votes.add(votecount(oi->mapvote, oi->modevote)); vc->count++; } votecount *best = NULL; loopv(votes) if(!best || votes[i].count > best->count || (votes[i].count == best->count && rnd(2))) best = &votes[i]; if(force || (best && best->count > maxvotes/2)) { if(demorecord) enddemorecord(); if(best && (best->count > (force ? 1 : maxvotes/2))) { sendservmsg(force ? "vote passed by default" : "vote passed by majority"); changemap(best->map, best->mode); } else rotatemap(true); } } void forcemap(const char *map, int mode) { stopdemo(); if(!map[0] && !m_check(mode, M_EDIT)) { int idx = findmaprotation(mode, smapname); if(idx < 0 && smapname[0]) idx = findmaprotation(mode, ""); if(idx < 0) return; map = maprotations[idx].map; } if(hasnonlocalclients()) sendservmsgf("local player forced %s on map %s", modename(mode), map[0] ? map : "[new map]"); changemap(map, mode); } void vote(const char *map, int reqmode, int sender) { clientinfo *ci = getinfo(sender); if(!ci || (ci->state.state==CS_SPECTATOR && !ci->privilege && !ci->local) || (!ci->local && !m_mp(reqmode))) return; if(!m_valid(reqmode)) return; if(!map[0] && !m_check(reqmode, M_EDIT)) { int idx = findmaprotation(reqmode, smapname); if(idx < 0 && smapname[0]) idx = findmaprotation(reqmode, ""); if(idx < 0) return; map = maprotations[idx].map; } if(lockmaprotation && !ci->local && ci->privilege < (lockmaprotation > 1 ? PRIV_ADMIN : PRIV_MASTER) && findmaprotation(reqmode, map) < 0) { sendf(sender, 1, "ris", N_SERVMSG, "This server has locked the map rotation."); return; } copystring(ci->mapvote, map); ci->modevote = reqmode; if(ci->local || (ci->privilege && mastermode>=MM_VETO)) { if(demorecord) enddemorecord(); if(!ci->local || hasnonlocalclients()) sendservmsgf("%s forced %s on map %s", colorname(ci), modename(ci->modevote), ci->mapvote[0] ? ci->mapvote : "[new map]"); changemap(ci->mapvote, ci->modevote); } else { sendservmsgf("%s suggests %s on map %s (select map to vote)", colorname(ci), modename(reqmode), map[0] ? map : "[new map]"); checkvotes(); } } void checkintermission() { if(gamemillis >= gamelimit && !interm) { sendf(-1, 1, "ri2", N_TIMEUP, 0); if(smode) smode->intermission(); changegamespeed(100); interm = gamemillis + 10000; } } void startintermission() { gamelimit = min(gamelimit, gamemillis); checkintermission(); } void dodamage(clientinfo *target, clientinfo *actor, int damage, int gun, const vec &hitpush = vec(0, 0, 0)) { gamestate &ts = target->state; ts.dodamage(damage); if(target!=actor && !isteam(target->team, actor->team)) actor->state.damage += damage; sendf(-1, 1, "ri6", N_DAMAGE, target->clientnum, actor->clientnum, damage, ts.armour, ts.health); if(target==actor) target->setpushed(); else if(!hitpush.iszero()) { ivec v = vec(hitpush).rescale(DNF); sendf(ts.health<=0 ? -1 : target->ownernum, 1, "ri7", N_HITPUSH, target->clientnum, gun, damage, v.x, v.y, v.z); target->setpushed(); } if(ts.health<=0) { target->state.deaths++; int fragvalue = smode ? smode->fragvalue(target, actor) : (target==actor || isteam(target->team, actor->team) ? -1 : 1); actor->state.frags += fragvalue; if(fragvalue>0) { int friends = 0, enemies = 0; // note: friends also includes the fragger if(m_teammode) loopv(clients) if(strcmp(clients[i]->team, actor->team)) enemies++; else friends++; else { friends = 1; enemies = clients.length()-1; } actor->state.effectiveness += fragvalue*friends/float(max(enemies, 1)); } teaminfo *t = m_teammode ? teaminfos.access(actor->team) : NULL; if(t) t->frags += fragvalue; sendf(-1, 1, "ri5", N_DIED, target->clientnum, actor->clientnum, actor->state.frags, t ? t->frags : 0); target->position.setsize(0); if(smode) smode->died(target, actor); ts.state = CS_DEAD; ts.lastdeath = gamemillis; if(actor!=target && isteam(actor->team, target->team)) { actor->state.teamkills++; addteamkill(actor, target, 1); } ts.deadflush = ts.lastdeath + DEATHMILLIS; // don't issue respawn yet until DEATHMILLIS has elapsed // ts.respawn(); } } void suicide(clientinfo *ci) { gamestate &gs = ci->state; if(gs.state!=CS_ALIVE) return; int fragvalue = smode ? smode->fragvalue(ci, ci) : -1; ci->state.frags += fragvalue; ci->state.deaths++; teaminfo *t = m_teammode ? teaminfos.access(ci->team) : NULL; if(t) t->frags += fragvalue; sendf(-1, 1, "ri5", N_DIED, ci->clientnum, ci->clientnum, gs.frags, t ? t->frags : 0); ci->position.setsize(0); if(smode) smode->died(ci, NULL); gs.state = CS_DEAD; gs.lastdeath = gamemillis; gs.respawn(); } void suicideevent::process(clientinfo *ci) { suicide(ci); } void explodeevent::process(clientinfo *ci) { gamestate &gs = ci->state; switch(gun) { case GUN_RL: if(!gs.rockets.remove(id)) return; break; case GUN_GL: if(!gs.grenades.remove(id)) return; break; default: return; } sendf(-1, 1, "ri4x", N_EXPLODEFX, ci->clientnum, gun, id, ci->ownernum); loopv(hits) { hitinfo &h = hits[i]; clientinfo *target = getinfo(h.target); if(!target || target->state.state!=CS_ALIVE || h.lifesequence!=target->state.lifesequence || h.dist<0 || h.dist>guns[gun].exprad) continue; bool dup = false; loopj(i) if(hits[j].target==h.target) { dup = true; break; } if(dup) continue; int damage = guns[gun].damage; if(gs.quadmillis) damage *= 4; damage = int(damage*(1-h.dist/EXP_DISTSCALE/guns[gun].exprad)); if(target==ci) damage /= EXP_SELFDAMDIV; dodamage(target, ci, damage, gun, h.dir); } } void shotevent::process(clientinfo *ci) { gamestate &gs = ci->state; int wait = millis - gs.lastshot; if(!gs.isalive(gamemillis) || waitGUN_PISTOL || gs.ammo[gun]<=0 || (guns[gun].range && from.dist(to) > guns[gun].range + 1)) return; if(gun!=GUN_FIST) gs.ammo[gun]--; gs.lastshot = millis; gs.gunwait = guns[gun].attackdelay; sendf(-1, 1, "rii9x", N_SHOTFX, ci->clientnum, gun, id, int(from.x*DMF), int(from.y*DMF), int(from.z*DMF), int(to.x*DMF), int(to.y*DMF), int(to.z*DMF), ci->ownernum); gs.shotdamage += guns[gun].damage*(gs.quadmillis ? 4 : 1)*guns[gun].rays; switch(gun) { case GUN_RL: gs.rockets.add(id); break; case GUN_GL: gs.grenades.add(id); break; default: { int totalrays = 0, maxrays = guns[gun].rays; loopv(hits) { hitinfo &h = hits[i]; clientinfo *target = getinfo(h.target); if(!target || target->state.state!=CS_ALIVE || h.lifesequence!=target->state.lifesequence || h.rays<1 || h.dist > guns[gun].range + 1) continue; totalrays += h.rays; if(totalrays>maxrays) continue; int damage = h.rays*guns[gun].damage; if(gs.quadmillis) damage *= 4; dodamage(target, ci, damage, gun, h.dir); } break; } } } void pickupevent::process(clientinfo *ci) { gamestate &gs = ci->state; if(m_mp(gamemode) && !gs.isalive(gamemillis)) return; pickup(ent, ci->clientnum); } bool gameevent::flush(clientinfo *ci, int fmillis) { process(ci); return true; } bool timedevent::flush(clientinfo *ci, int fmillis) { if(millis > fmillis) return false; else if(millis >= ci->lastevent) { ci->lastevent = millis; process(ci); } return true; } void clearevent(clientinfo *ci) { delete ci->events.remove(0); } void flushevents(clientinfo *ci, int millis) { while(ci->events.length()) { gameevent *ev = ci->events[0]; if(ev->flush(ci, millis)) clearevent(ci); else break; } } void processevents() { loopv(clients) { clientinfo *ci = clients[i]; if(curtime>0 && ci->state.quadmillis) ci->state.quadmillis = max(ci->state.quadmillis-curtime, 0); flushevents(ci, gamemillis); } } void cleartimedevents(clientinfo *ci) { int keep = 0; loopv(ci->events) { if(ci->events[i]->keepable()) { if(keep < i) { for(int j = keep; j < i; j++) delete ci->events[j]; ci->events.remove(keep, i - keep); i = keep; } keep = i+1; continue; } } while(ci->events.length() > keep) delete ci->events.pop(); ci->timesync = false; } void serverupdate() { if(shouldstep && !gamepaused) { gamemillis += curtime; if(m_demo) readdemo(); else if(!m_timed || gamemillis < gamelimit) { processevents(); if(curtime) { loopv(sents) if(sents[i].spawntime) // spawn entities when timer reached { int oldtime = sents[i].spawntime; sents[i].spawntime -= curtime; if(sents[i].spawntime<=0) { sents[i].spawntime = 0; sents[i].spawned = true; sendf(-1, 1, "ri2", N_ITEMSPAWN, i); } else if(sents[i].spawntime<=10000 && oldtime>10000 && (sents[i].type==I_QUAD || sents[i].type==I_BOOST)) { sendf(-1, 1, "ri2", N_ANNOUNCE, sents[i].type); } } } aiman::checkai(); if(smode) smode->update(); } } while(bannedips.length() && bannedips[0].expire-totalmillis <= 0) bannedips.remove(0); loopv(connects) if(totalmillis-connects[i]->connectmillis>15000) disconnect_client(connects[i]->clientnum, DISC_TIMEOUT); if(nextexceeded && gamemillis > nextexceeded && (!m_timed || gamemillis < gamelimit)) { nextexceeded = 0; loopvrev(clients) { clientinfo &c = *clients[i]; if(c.state.aitype != AI_NONE) continue; if(c.checkexceeded()) disconnect_client(c.clientnum, DISC_MSGERR); else c.scheduleexceeded(); } } if(shouldcheckteamkills) checkteamkills(); if(shouldstep && !gamepaused) { if(m_timed && smapname[0] && gamemillis-curtime>0) checkintermission(); if(interm > 0 && gamemillis>interm) { if(demorecord) enddemorecord(); interm = -1; checkvotes(true); } } shouldstep = clients.length() > 0; } struct crcinfo { int crc, matches; crcinfo() {} crcinfo(int crc, int matches) : crc(crc), matches(matches) {} static bool compare(const crcinfo &x, const crcinfo &y) { return x.matches > y.matches; } }; void checkmaps(int req = -1) { if(m_edit || !smapname[0]) return; vector crcs; int total = 0, unsent = 0, invalid = 0; if(mcrc) crcs.add(crcinfo(mcrc, clients.length() + 1)); loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.state==CS_SPECTATOR || ci->state.aitype != AI_NONE) continue; total++; if(!ci->clientmap[0]) { if(ci->mapcrc < 0) invalid++; else if(!ci->mapcrc) unsent++; } else { crcinfo *match = NULL; loopvj(crcs) if(crcs[j].crc == ci->mapcrc) { match = &crcs[j]; break; } if(!match) crcs.add(crcinfo(ci->mapcrc, 1)); else match->matches++; } } if(!mcrc && total - unsent < min(total, 4)) return; crcs.sort(crcinfo::compare); string msg; loopv(clients) { clientinfo *ci = clients[i]; if(ci->state.state==CS_SPECTATOR || ci->state.aitype != AI_NONE || ci->clientmap[0] || ci->mapcrc >= 0 || (req < 0 && ci->warned)) continue; formatstring(msg)("%s has modified map \"%s\"", colorname(ci), smapname); sendf(req, 1, "ris", N_SERVMSG, msg); if(req < 0) ci->warned = true; } if(crcs.empty() || crcs.length() < 2) return; loopv(crcs) { crcinfo &info = crcs[i]; if(i || info.matches <= crcs[i+1].matches) loopvj(clients) { clientinfo *ci = clients[j]; if(ci->state.state==CS_SPECTATOR || ci->state.aitype != AI_NONE || !ci->clientmap[0] || ci->mapcrc != info.crc || (req < 0 && ci->warned)) continue; formatstring(msg)("%s has modified map \"%s\"", colorname(ci), smapname); sendf(req, 1, "ris", N_SERVMSG, msg); if(req < 0) ci->warned = true; } } } void sendservinfo(clientinfo *ci) { sendf(ci->clientnum, 1, "ri5ss", N_SERVINFO, ci->clientnum, PROTOCOL_VERSION, ci->sessionid, serverpass[0] ? 1 : 0, serverdesc, serverauth); } void noclients() { bannedips.shrink(0); aiman::clearai(); } void localconnect(int n) { clientinfo *ci = getinfo(n); ci->clientnum = ci->ownernum = n; ci->connectmillis = totalmillis; ci->sessionid = (rnd(0x1000000)*((totalmillis%10000)+1))&0xFFFFFF; ci->local = true; connects.add(ci); sendservinfo(ci); } void localdisconnect(int n) { if(m_demo) enddemoplayback(); clientdisconnect(n); } int clientconnect(int n, uint ip) { clientinfo *ci = getinfo(n); ci->clientnum = ci->ownernum = n; ci->connectmillis = totalmillis; ci->sessionid = (rnd(0x1000000)*((totalmillis%10000)+1))&0xFFFFFF; connects.add(ci); if(!m_mp(gamemode)) return DISC_LOCAL; sendservinfo(ci); return DISC_NONE; } void clientdisconnect(int n) { clientinfo *ci = getinfo(n); loopv(clients) if(clients[i]->authkickvictim == ci->clientnum) clients[i]->cleanauth(); if(ci->connected) { if(ci->privilege) setmaster(ci, false); if(smode) smode->leavegame(ci, true); ci->state.timeplayed += lastmillis - ci->state.lasttimeplayed; savescore(ci); sendf(-1, 1, "ri2", N_CDIS, n); clients.removeobj(ci); aiman::removeai(ci); if(!numclients(-1, false, true)) noclients(); // bans clear when server empties if(ci->local) checkpausegame(); } else connects.removeobj(ci); } int reserveclients() { return 3; } struct gbaninfo { enet_uint32 ip, mask; }; vector gbans; void cleargbans() { gbans.shrink(0); } bool checkgban(uint ip) { loopv(gbans) if((ip & gbans[i].mask) == gbans[i].ip) return true; return false; } void addgban(const char *name) { union { uchar b[sizeof(enet_uint32)]; enet_uint32 i; } ip, mask; ip.i = 0; mask.i = 0; loopi(4) { char *end = NULL; int n = strtol(name, &end, 10); if(!end) break; if(end > name) { ip.b[i] = n; mask.b[i] = 0xFF; } name = end; while(*name && *name++ != '.'); } gbaninfo &ban = gbans.add(); ban.ip = ip.i; ban.mask = mask.i; loopvrev(clients) { clientinfo *ci = clients[i]; if(ci->local || ci->privilege >= PRIV_ADMIN) continue; if(checkgban(getclientip(ci->clientnum))) disconnect_client(ci->clientnum, DISC_IPBAN); } } int allowconnect(clientinfo *ci, const char *pwd = "") { if(ci->local) return DISC_NONE; if(!m_mp(gamemode)) return DISC_LOCAL; if(serverpass[0]) { if(!checkpassword(ci, serverpass, pwd)) return DISC_PASSWORD; return DISC_NONE; } if(adminpass[0] && checkpassword(ci, adminpass, pwd)) return DISC_NONE; if(numclients(-1, false, true)>=maxclients) return DISC_MAXCLIENTS; uint ip = getclientip(ci->clientnum); loopv(bannedips) if(bannedips[i].ip==ip) return DISC_IPBAN; if(checkgban(ip)) return DISC_IPBAN; if(mastermode>=MM_PRIVATE && allowedips.find(ip)<0) return DISC_PRIVATE; return DISC_NONE; } bool allowbroadcast(int n) { clientinfo *ci = getinfo(n); return ci && ci->connected; } clientinfo *findauth(uint id) { loopv(clients) if(clients[i]->authreq == id) return clients[i]; return NULL; } void authfailed(uint id) { clientinfo *ci = findauth(id); if(!ci) return; ci->cleanauth(); if(ci->connectauth) disconnect_client(ci->clientnum, ci->connectauth); } void authsucceeded(uint id) { clientinfo *ci = findauth(id); if(!ci) return; ci->cleanauth(ci->connectauth!=0); if(ci->connectauth) connected(ci); if(ci->authkickvictim >= 0) { if(setmaster(ci, true, "", ci->authname, NULL, PRIV_AUTH, false, true)) trykick(ci, ci->authkickvictim, ci->authkickreason, ci->authname, NULL, PRIV_AUTH); ci->cleanauthkick(); } else setmaster(ci, true, "", ci->authname, NULL, PRIV_AUTH); } void authchallenged(uint id, const char *val, const char *desc = "") { clientinfo *ci = findauth(id); if(!ci) return; sendf(ci->clientnum, 1, "risis", N_AUTHCHAL, desc, id, val); } uint nextauthreq = 0; bool tryauth(clientinfo *ci, const char *user, const char *desc) { ci->cleanauth(); if(!nextauthreq) nextauthreq = 1; ci->authreq = nextauthreq++; filtertext(ci->authname, user, false, 100); copystring(ci->authdesc, desc); if(ci->authdesc[0]) { userinfo *u = users.access(userkey(ci->authname, ci->authdesc)); if(u) { uint seed[3] = { ::hthash(serverauth) + detrnd(size_t(ci) + size_t(user) + size_t(desc), 0x10000), uint(totalmillis), randomMT() }; vector buf; ci->authchallenge = genchallenge(u->pubkey, seed, sizeof(seed), buf); sendf(ci->clientnum, 1, "risis", N_AUTHCHAL, desc, ci->authreq, buf.getbuf()); } else ci->cleanauth(); } else if(!requestmasterf("reqauth %u %s\n", ci->authreq, ci->authname)) { ci->cleanauth(); sendf(ci->clientnum, 1, "ris", N_SERVMSG, "not connected to authentication server"); } if(ci->authreq) return true; if(ci->connectauth) disconnect_client(ci->clientnum, ci->connectauth); return false; } void answerchallenge(clientinfo *ci, uint id, char *val, const char *desc) { if(ci->authreq != id || strcmp(ci->authdesc, desc)) { ci->cleanauth(); if(ci->connectauth) disconnect_client(ci->clientnum, ci->connectauth); return; } for(char *s = val; *s; s++) { if(!isxdigit(*s)) { *s = '\0'; break; } } if(desc[0]) { if(ci->authchallenge && checkchallenge(val, ci->authchallenge)) { userinfo *u = users.access(userkey(ci->authname, ci->authdesc)); if(u) { if(ci->connectauth) connected(ci); if(ci->authkickvictim >= 0) { if(setmaster(ci, true, "", ci->authname, ci->authdesc, u->privilege, false, true)) trykick(ci, ci->authkickvictim, ci->authkickreason, ci->authname, ci->authdesc, u->privilege); } else setmaster(ci, true, "", ci->authname, ci->authdesc, u->privilege); } } ci->cleanauth(); } else if(!requestmasterf("confauth %u %s\n", id, val)) { ci->cleanauth(); sendf(ci->clientnum, 1, "ris", N_SERVMSG, "not connected to authentication server"); } if(!ci->authreq && ci->connectauth) disconnect_client(ci->clientnum, ci->connectauth); } void processmasterinput(const char *cmd, int cmdlen, const char *args) { uint id; string val; if(sscanf(cmd, "failauth %u", &id) == 1) authfailed(id); else if(sscanf(cmd, "succauth %u", &id) == 1) authsucceeded(id); else if(sscanf(cmd, "chalauth %u %255s", &id, val) == 2) authchallenged(id, val); else if(!strncmp(cmd, "cleargbans", cmdlen)) cleargbans(); else if(sscanf(cmd, "addgban %100s", val) == 1) addgban(val); } void receivefile(int sender, uchar *data, int len) { if(!m_edit || len > 4*1024*1024) return; clientinfo *ci = getinfo(sender); if(ci->state.state==CS_SPECTATOR && !ci->privilege && !ci->local) return; if(mapdata) DELETEP(mapdata); if(!len) return; mapdata = opentempfile("mapdata", "w+b"); if(!mapdata) { sendf(sender, 1, "ris", N_SERVMSG, "failed to open temporary file for map"); return; } mapdata->write(data, len); sendservmsgf("[%s sent a map to server, \"/getmap\" to receive it]", colorname(ci)); } void sendclipboard(clientinfo *ci) { if(!ci->lastclipboard || !ci->clipboard) return; bool flushed = false; loopv(clients) { clientinfo &e = *clients[i]; if(e.clientnum != ci->clientnum && e.needclipboard - ci->lastclipboard >= 0) { if(!flushed) { flushserver(true); flushed = true; } sendpacket(e.clientnum, 1, ci->clipboard); } } } void connected(clientinfo *ci) { if(m_demo) enddemoplayback(); if(!hasmap(ci)) rotatemap(false); shouldstep = true; connects.removeobj(ci); clients.add(ci); ci->connectauth = 0; ci->connected = true; ci->needclipboard = totalmillis ? totalmillis : 1; if(mastermode>=MM_LOCKED) ci->state.state = CS_SPECTATOR; ci->state.lasttimeplayed = lastmillis; const char *worst = m_teammode ? chooseworstteam(NULL, ci) : NULL; copystring(ci->team, worst ? worst : "good", MAXTEAMLEN+1); sendwelcome(ci); if(restorescore(ci)) sendresume(ci); sendinitclient(ci); aiman::addclient(ci); if(m_demo) setupdemoplayback(); if(servermotd[0]) sendf(ci->clientnum, 1, "ris", N_SERVMSG, servermotd); } void parsepacket(int sender, int chan, packetbuf &p) // has to parse exactly each byte of the packet { if(sender<0 || p.packet->flags&ENET_PACKET_FLAG_UNSEQUENCED || chan > 2) return; char text[MAXTRANS]; int type; clientinfo *ci = sender>=0 ? getinfo(sender) : NULL, *cq = ci, *cm = ci; if(ci && !ci->connected) { if(chan==0) return; else if(chan!=1) { disconnect_client(sender, DISC_MSGERR); return; } else while(p.length() < p.maxlen) switch(checktype(getint(p), ci)) { case N_CONNECT: { getstring(text, p); filtertext(text, text, false, MAXNAMELEN); if(!text[0]) copystring(text, "unnamed"); copystring(ci->name, text, MAXNAMELEN+1); ci->playermodel = getint(p); string password, authdesc, authname; getstring(password, p, sizeof(password)); getstring(authdesc, p, sizeof(authdesc)); getstring(authname, p, sizeof(authname)); int disc = allowconnect(ci, password); if(disc) { if(disc == DISC_LOCAL || !serverauth[0] || strcmp(serverauth, authdesc) || !tryauth(ci, authname, authdesc)) { disconnect_client(sender, disc); return; } ci->connectauth = disc; } else connected(ci); break; } case N_AUTHANS: { string desc, ans; getstring(desc, p, sizeof(desc)); uint id = (uint)getint(p); getstring(ans, p, sizeof(ans)); answerchallenge(ci, id, ans, desc); break; } case N_PING: getint(p); break; default: disconnect_client(sender, DISC_MSGERR); break; } return; } else if(chan==2) { receivefile(sender, p.buf, p.maxlen); return; } if(p.packet->flags&ENET_PACKET_FLAG_RELIABLE) reliablemessages = true; #define QUEUE_AI clientinfo *cm = cq; #define QUEUE_MSG { if(cm && (!cm->local || demorecord || hasnonlocalclients())) while(curmsgmessages.add(p.buf[curmsg++]); } #define QUEUE_BUF(body) { \ if(cm && (!cm->local || demorecord || hasnonlocalclients())) \ { \ curmsg = p.length(); \ { body; } \ } \ } #define QUEUE_INT(n) QUEUE_BUF(putint(cm->messages, n)) #define QUEUE_UINT(n) QUEUE_BUF(putuint(cm->messages, n)) #define QUEUE_STR(text) QUEUE_BUF(sendstring(text, cm->messages)) int curmsg; while((curmsg = p.length()) < p.maxlen) switch(type = checktype(getint(p), ci)) { case N_POS: { int pcn = getuint(p); p.get(); uint flags = getuint(p); clientinfo *cp = getinfo(pcn); if(cp && pcn != sender && cp->ownernum != sender) cp = NULL; vec pos; loopk(3) { int n = p.get(); n |= p.get()<<8; if(flags&(1<local || demorecord || hasnonlocalclients()) && (cp->state.state==CS_ALIVE || cp->state.state==CS_EDITING)) { if(!ci->local && !m_edit && max(vel.magnitude2(), (float)fabs(vel.z)) >= 180) cp->setexceeded(); cp->position.setsize(0); while(curmsgposition.add(p.buf[curmsg++]); } if(smode && cp->state.state==CS_ALIVE) smode->moved(cp, cp->state.o, cp->gameclip, pos, (flags&0x80)!=0); cp->state.o = pos; cp->gameclip = (flags&0x80)!=0; } break; } case N_TELEPORT: { int pcn = getint(p), teleport = getint(p), teledest = getint(p); clientinfo *cp = getinfo(pcn); if(cp && pcn != sender && cp->ownernum != sender) cp = NULL; if(cp && (!ci->local || demorecord || hasnonlocalclients()) && (cp->state.state==CS_ALIVE || cp->state.state==CS_EDITING)) { flushclientposition(*cp); sendf(-1, 0, "ri4x", N_TELEPORT, pcn, teleport, teledest, cp->ownernum); } break; } case N_JUMPPAD: { int pcn = getint(p), jumppad = getint(p); clientinfo *cp = getinfo(pcn); if(cp && pcn != sender && cp->ownernum != sender) cp = NULL; if(cp && (!ci->local || demorecord || hasnonlocalclients()) && (cp->state.state==CS_ALIVE || cp->state.state==CS_EDITING)) { cp->setpushed(); flushclientposition(*cp); sendf(-1, 0, "ri3x", N_JUMPPAD, pcn, jumppad, cp->ownernum); } break; } case N_FROMAI: { int qcn = getint(p); if(qcn < 0) cq = ci; else { cq = getinfo(qcn); if(cq && qcn != sender && cq->ownernum != sender) cq = NULL; } break; } case N_EDITMODE: { int val = getint(p); if(!ci->local && !m_edit) break; if(val ? ci->state.state!=CS_ALIVE && ci->state.state!=CS_DEAD : ci->state.state!=CS_EDITING) break; if(smode) { if(val) smode->leavegame(ci); else smode->entergame(ci); } if(val) { ci->state.editstate = ci->state.state; ci->state.state = CS_EDITING; ci->events.setsize(0); ci->state.rockets.reset(); ci->state.grenades.reset(); } else ci->state.state = ci->state.editstate; QUEUE_MSG; break; } case N_MAPCRC: { getstring(text, p); int crc = getint(p); if(!ci) break; if(strcmp(text, smapname)) { if(ci->clientmap[0]) { ci->clientmap[0] = '\0'; ci->mapcrc = 0; } else if(ci->mapcrc > 0) ci->mapcrc = 0; break; } copystring(ci->clientmap, text); ci->mapcrc = text[0] ? crc : 1; checkmaps(); break; } case N_CHECKMAPS: checkmaps(sender); break; case N_TRYSPAWN: if(!ci || !cq || cq->state.state!=CS_DEAD || cq->state.lastspawn>=0 || (smode && !smode->canspawn(cq))) break; if(!ci->clientmap[0] && !ci->mapcrc) { ci->mapcrc = -1; checkmaps(); } if(cq->state.deadflush) { flushevents(cq, cq->state.deadflush); cq->state.respawn(); } cleartimedevents(cq); sendspawn(cq); break; case N_GUNSELECT: { int gunselect = getint(p); if(!cq || cq->state.state!=CS_ALIVE) break; cq->state.gunselect = gunselect >= GUN_FIST && gunselect <= GUN_PISTOL ? gunselect : GUN_FIST; QUEUE_AI; QUEUE_MSG; break; } case N_SPAWN: { int ls = getint(p), gunselect = getint(p); if(!cq || (cq->state.state!=CS_ALIVE && cq->state.state!=CS_DEAD) || ls!=cq->state.lifesequence || cq->state.lastspawn<0) break; cq->state.lastspawn = -1; cq->state.state = CS_ALIVE; cq->state.gunselect = gunselect >= GUN_FIST && gunselect <= GUN_PISTOL ? gunselect : GUN_FIST; cq->exceeded = 0; if(smode) smode->spawned(cq); QUEUE_AI; QUEUE_BUF({ putint(cm->messages, N_SPAWN); sendstate(cq->state, cm->messages); }); break; } case N_SUICIDE: { if(cq) cq->addevent(new suicideevent); break; } case N_SHOOT: { shotevent *shot = new shotevent; shot->id = getint(p); shot->millis = cq ? cq->geteventmillis(gamemillis, shot->id) : 0; shot->gun = getint(p); loopk(3) shot->from[k] = getint(p)/DMF; loopk(3) shot->to[k] = getint(p)/DMF; int hits = getint(p); loopk(hits) { if(p.overread()) break; hitinfo &hit = shot->hits.add(); hit.target = getint(p); hit.lifesequence = getint(p); hit.dist = getint(p)/DMF; hit.rays = getint(p); loopk(3) hit.dir[k] = getint(p)/DNF; } if(cq) { cq->addevent(shot); cq->setpushed(); } else delete shot; break; } case N_EXPLODE: { explodeevent *exp = new explodeevent; int cmillis = getint(p); exp->millis = cq ? cq->geteventmillis(gamemillis, cmillis) : 0; exp->gun = getint(p); exp->id = getint(p); int hits = getint(p); loopk(hits) { if(p.overread()) break; hitinfo &hit = exp->hits.add(); hit.target = getint(p); hit.lifesequence = getint(p); hit.dist = getint(p)/DMF; hit.rays = getint(p); loopk(3) hit.dir[k] = getint(p)/DNF; } if(cq) cq->addevent(exp); else delete exp; break; } case N_ITEMPICKUP: { int n = getint(p); if(!cq) break; pickupevent *pickup = new pickupevent; pickup->ent = n; cq->addevent(pickup); break; } case N_TEXT: { QUEUE_AI; QUEUE_MSG; getstring(text, p); filtertext(text, text); QUEUE_STR(text); if(isdedicatedserver()) logoutf("%s: %s", colorname(cq), text); break; } case N_SAYTEAM: { getstring(text, p); if(!ci || !cq || (ci->state.state==CS_SPECTATOR && !ci->local && !ci->privilege) || !m_teammode || !cq->team[0]) break; loopv(clients) { clientinfo *t = clients[i]; if(t==cq || t->state.state==CS_SPECTATOR || t->state.aitype != AI_NONE || strcmp(cq->team, t->team)) continue; sendf(t->clientnum, 1, "riis", N_SAYTEAM, cq->clientnum, text); } if(isdedicatedserver()) logoutf("%s <%s>: %s", colorname(cq), cq->team, text); break; } case N_SWITCHNAME: { QUEUE_MSG; getstring(text, p); filtertext(ci->name, text, false, MAXNAMELEN); if(!ci->name[0]) copystring(ci->name, "unnamed"); QUEUE_STR(ci->name); break; } case N_SWITCHMODEL: { ci->playermodel = getint(p); QUEUE_MSG; break; } case N_SWITCHTEAM: { getstring(text, p); filtertext(text, text, false, MAXTEAMLEN); if(m_teammode && text[0] && strcmp(ci->team, text) && (!smode || smode->canchangeteam(ci, ci->team, text)) && addteaminfo(text)) { if(ci->state.state==CS_ALIVE) suicide(ci); copystring(ci->team, text); aiman::changeteam(ci); sendf(-1, 1, "riisi", N_SETTEAM, sender, ci->team, ci->state.state==CS_SPECTATOR ? -1 : 0); } break; } case N_MAPVOTE: { getstring(text, p); filtertext(text, text, false); int reqmode = getint(p); vote(text, reqmode, sender); break; } case N_ITEMLIST: { if((ci->state.state==CS_SPECTATOR && !ci->privilege && !ci->local) || !notgotitems || strcmp(ci->clientmap, smapname)) { while(getint(p)>=0 && !p.overread()) getint(p); break; } int n; while((n = getint(p))>=0 && nstate.state==CS_SPECTATOR) break; QUEUE_MSG; bool canspawn = canspawnitem(type); if(istate.state!=CS_SPECTATOR) QUEUE_MSG; break; } case N_PING: sendf(sender, 1, "i2", N_PONG, getint(p)); break; case N_CLIENTPING: { int ping = getint(p); if(ci) { ci->ping = ping; loopv(ci->bots) ci->bots[i]->ping = ping; } QUEUE_MSG; break; } case N_MASTERMODE: { int mm = getint(p); if((ci->privilege || ci->local) && mm>=MM_OPEN && mm<=MM_PRIVATE) { if((ci->privilege>=PRIV_ADMIN || ci->local) || (mastermask&(1<=MM_PRIVATE) { loopv(clients) allowedips.add(getclientip(clients[i]->clientnum)); } sendf(-1, 1, "rii", N_MASTERMODE, mastermode); //sendservmsgf("mastermode is now %s (%d)", mastermodename(mastermode), mastermode); } else { defformatstring(s)("mastermode %d is disabled on this server", mm); sendf(sender, 1, "ris", N_SERVMSG, s); } } break; } case N_CLEARBANS: { if(ci->privilege || ci->local) { bannedips.shrink(0); sendservmsg("cleared all bans"); } break; } case N_KICK: { int victim = getint(p); getstring(text, p); filtertext(text, text); trykick(ci, victim, text); break; } case N_SPECTATOR: { int spectator = getint(p), val = getint(p); if(!ci->privilege && !ci->local && (spectator!=sender || (ci->state.state==CS_SPECTATOR && mastermode>=MM_LOCKED))) break; clientinfo *spinfo = (clientinfo *)getclientinfo(spectator); // no bots if(!spinfo || (spinfo->state.state==CS_SPECTATOR ? val : !val)) break; if(spinfo->state.state!=CS_SPECTATOR && val) { if(spinfo->state.state==CS_ALIVE) suicide(spinfo); if(smode) smode->leavegame(spinfo); spinfo->state.state = CS_SPECTATOR; spinfo->state.timeplayed += lastmillis - spinfo->state.lasttimeplayed; if(!spinfo->local && !spinfo->privilege) aiman::removeai(spinfo); } else if(spinfo->state.state==CS_SPECTATOR && !val) { spinfo->state.state = CS_DEAD; spinfo->state.respawn(); spinfo->state.lasttimeplayed = lastmillis; aiman::addclient(spinfo); if(spinfo->clientmap[0] || spinfo->mapcrc) checkmaps(); } sendf(-1, 1, "ri3", N_SPECTATOR, spectator, val); if(!val && !hasmap(spinfo)) rotatemap(true); break; } case N_SETTEAM: { int who = getint(p); getstring(text, p); filtertext(text, text, false, MAXTEAMLEN); if(!ci->privilege && !ci->local) break; clientinfo *wi = getinfo(who); if(!m_teammode || !text[0] || !wi || !strcmp(wi->team, text)) break; if((!smode || smode->canchangeteam(wi, wi->team, text)) && addteaminfo(text)) { if(wi->state.state==CS_ALIVE) suicide(wi); copystring(wi->team, text, MAXTEAMLEN+1); } aiman::changeteam(wi); sendf(-1, 1, "riisi", N_SETTEAM, who, wi->team, 1); break; } case N_FORCEINTERMISSION: if(ci->local && !hasnonlocalclients()) startintermission(); break; case N_RECORDDEMO: { int val = getint(p); if(ci->privilege < (restrictdemos ? PRIV_ADMIN : PRIV_MASTER) && !ci->local) break; if(!maxdemos || !maxdemosize) { sendf(ci->clientnum, 1, "ris", N_SERVMSG, "the server has disabled demo recording"); break; } demonextmatch = val!=0; sendservmsgf("demo recording is %s for next match", demonextmatch ? "enabled" : "disabled"); break; } case N_STOPDEMO: { if(ci->privilege < (restrictdemos ? PRIV_ADMIN : PRIV_MASTER) && !ci->local) break; stopdemo(); break; } case N_CLEARDEMOS: { int demo = getint(p); if(ci->privilege < (restrictdemos ? PRIV_ADMIN : PRIV_MASTER) && !ci->local) break; cleardemos(demo); break; } case N_LISTDEMOS: if(!ci->privilege && !ci->local && ci->state.state==CS_SPECTATOR) break; listdemos(sender); break; case N_GETDEMO: { int n = getint(p); if(!ci->privilege && !ci->local && ci->state.state==CS_SPECTATOR) break; senddemo(ci, n); break; } case N_GETMAP: if(!mapdata) sendf(sender, 1, "ris", N_SERVMSG, "no map to send"); else if(ci->getmap) sendf(sender, 1, "ris", N_SERVMSG, "already sending map"); else { sendservmsgf("[%s is getting the map]", colorname(ci)); if((ci->getmap = sendfile(sender, 2, mapdata, "ri", N_SENDMAP))) ci->getmap->freeCallback = freegetmap; ci->needclipboard = totalmillis ? totalmillis : 1; } break; case N_NEWMAP: { int size = getint(p); if(!ci->privilege && !ci->local && ci->state.state==CS_SPECTATOR) break; if(size>=0) { smapname[0] = '\0'; resetitems(); notgotitems = false; if(smode) smode->newmap(); } QUEUE_MSG; break; } case N_SETMASTER: { int mn = getint(p), val = getint(p); getstring(text, p); if(mn != ci->clientnum) { if(!ci->privilege && !ci->local) break; clientinfo *minfo = (clientinfo *)getclientinfo(mn); if(!minfo || (!ci->local && minfo->privilege >= ci->privilege) || (val && minfo->privilege)) break; setmaster(minfo, val!=0, "", NULL, NULL, PRIV_MASTER, true); } else setmaster(ci, val!=0, text); // don't broadcast the master password break; } case N_ADDBOT: { aiman::reqadd(ci, getint(p)); break; } case N_DELBOT: { aiman::reqdel(ci); break; } case N_BOTLIMIT: { int limit = getint(p); if(ci) aiman::setbotlimit(ci, limit); break; } case N_BOTBALANCE: { int balance = getint(p); if(ci) aiman::setbotbalance(ci, balance!=0); break; } case N_AUTHTRY: { string desc, name; getstring(desc, p, sizeof(desc)); getstring(name, p, sizeof(name)); tryauth(ci, name, desc); break; } case N_AUTHKICK: { string desc, name; getstring(desc, p, sizeof(desc)); getstring(name, p, sizeof(name)); int victim = getint(p); getstring(text, p); filtertext(text, text); int authpriv = PRIV_AUTH; if(desc[0]) { userinfo *u = users.access(userkey(name, desc)); if(u) authpriv = u->privilege; else break; } if(trykick(ci, victim, text, name, desc, authpriv, true) && tryauth(ci, name, desc)) { ci->authkickvictim = victim; ci->authkickreason = newstring(text); } break; } case N_AUTHANS: { string desc, ans; getstring(desc, p, sizeof(desc)); uint id = (uint)getint(p); getstring(ans, p, sizeof(ans)); answerchallenge(ci, id, ans, desc); break; } case N_PAUSEGAME: { int val = getint(p); if(ci->privilege < (restrictpausegame ? PRIV_ADMIN : PRIV_MASTER) && !ci->local) break; pausegame(val > 0, ci); break; } case N_GAMESPEED: { int val = getint(p); if(ci->privilege < (restrictgamespeed ? PRIV_ADMIN : PRIV_MASTER) && !ci->local) break; changegamespeed(val, ci); break; } case N_COPY: ci->cleanclipboard(); ci->lastclipboard = totalmillis ? totalmillis : 1; goto genericmsg; case N_PASTE: if(ci->state.state!=CS_SPECTATOR) sendclipboard(ci); goto genericmsg; case N_CLIPBOARD: { int unpacklen = getint(p), packlen = getint(p); ci->cleanclipboard(false); if(ci->state.state==CS_SPECTATOR) { if(packlen > 0) p.subbuf(packlen); break; } if(packlen <= 0 || packlen > (1<<16) || unpacklen <= 0) { if(packlen > 0) p.subbuf(packlen); packlen = unpacklen = 0; } packetbuf q(32 + packlen, ENET_PACKET_FLAG_RELIABLE); putint(q, N_CLIPBOARD); putint(q, ci->clientnum); putint(q, unpacklen); putint(q, packlen); if(packlen > 0) p.get(q.subbuf(packlen).buf, packlen); ci->clipboard = q.finalize(); ci->clipboard->referenceCount++; break; } case N_SERVCMD: getstring(text, p); break; #define PARSEMESSAGES 1 #include "capture.h" #include "ctf.h" #include "collect.h" #undef PARSEMESSAGES case -1: disconnect_client(sender, DISC_MSGERR); return; case -2: disconnect_client(sender, DISC_OVERFLOW); return; default: genericmsg: { int size = server::msgsizelookup(type); if(size<=0) { disconnect_client(sender, DISC_MSGERR); return; } loopi(size-1) getint(p); if(ci && cq && (ci != cq || ci->state.state!=CS_SPECTATOR)) { QUEUE_AI; QUEUE_MSG; } break; } } } int laninfoport() { return SAUERBRATEN_LANINFO_PORT; } int serverinfoport(int servport) { return servport < 0 ? SAUERBRATEN_SERVINFO_PORT : servport+1; } int serverport(int infoport) { return infoport < 0 ? SAUERBRATEN_SERVER_PORT : infoport-1; } const char *defaultmaster() { return "sauerbraten.org"; } int masterport() { return SAUERBRATEN_MASTER_PORT; } int numchannels() { return 3; } #include "extinfo.h" void serverinforeply(ucharbuf &req, ucharbuf &p) { if(!getint(req)) { extserverinforeply(req, p); return; } putint(p, numclients(-1, false, true)); putint(p, gamepaused || gamespeed != 100 ? 7 : 5); // number of attrs following putint(p, PROTOCOL_VERSION); // generic attributes, passed back below putint(p, gamemode); putint(p, m_timed ? max((gamelimit - gamemillis)/1000, 0) : 0); putint(p, maxclients); putint(p, serverpass[0] ? MM_PASSWORD : (!m_mp(gamemode) ? MM_PRIVATE : (mastermode || mastermask&MM_AUTOAPPROVE ? mastermode : MM_AUTH))); if(gamepaused || gamespeed != 100) { putint(p, gamepaused ? 1 : 0); putint(p, gamespeed); } sendstring(smapname, p); sendstring(serverdesc, p); sendserverinforeply(p); } bool servercompatible(char *name, char *sdec, char *map, int ping, const vector &attr, int np) { return attr.length() && attr[0]==PROTOCOL_VERSION; } #include "aiman.h" } sauerbraten-0.0.20130203.dfsg/fpsgame/client.cpp0000644000175000017500000020630612075052370021011 0ustar vincentvincent#include "game.h" namespace game { VARP(minradarscale, 0, 384, 10000); VARP(maxradarscale, 1, 1024, 10000); VARP(radarteammates, 0, 1, 1); FVARP(minimapalpha, 0, 1, 1); float calcradarscale() { return clamp(max(minimapradius.x, minimapradius.y)/3, float(minradarscale), float(maxradarscale)); } void drawminimap(fpsent *d, float x, float y, float s) { vec pos = vec(d->o).sub(minimapcenter).mul(minimapscale).add(0.5f), dir; vecfromyawpitch(camera1->yaw, 0, 1, 0, dir); float scale = calcradarscale(); glBegin(GL_TRIANGLE_FAN); loopi(16) { vec tc = vec(dir).rotate_around_z(i/16.0f*2*M_PI); glTexCoord2f(pos.x + tc.x*scale*minimapscale.x, pos.y + tc.y*scale*minimapscale.y); vec v = vec(0, -1, 0).rotate_around_z(i/16.0f*2*M_PI); glVertex2f(x + 0.5f*s*(1.0f + v.x), y + 0.5f*s*(1.0f + v.y)); } glEnd(); } void drawradar(float x, float y, float s) { glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0.0f, 0.0f); glVertex2f(x, y); glTexCoord2f(1.0f, 0.0f); glVertex2f(x+s, y); glTexCoord2f(0.0f, 1.0f); glVertex2f(x, y+s); glTexCoord2f(1.0f, 1.0f); glVertex2f(x+s, y+s); glEnd(); } void drawteammate(fpsent *d, float x, float y, float s, fpsent *o, float scale) { vec dir = d->o; dir.sub(o->o).div(scale); float dist = dir.magnitude2(), maxdist = 1 - 0.05f - 0.05f; if(dist >= maxdist) dir.mul(maxdist/dist); dir.rotate_around_z(-camera1->yaw*RAD); float bs = 0.06f*s, bx = x + s*0.5f*(1.0f + dir.x), by = y + s*0.5f*(1.0f + dir.y); vec v(-0.5f, -0.5f, 0); v.rotate_around_z((90+o->yaw-camera1->yaw)*RAD); glTexCoord2f(0.0f, 0.0f); glVertex2f(bx + bs*v.x, by + bs*v.y); glTexCoord2f(1.0f, 0.0f); glVertex2f(bx + bs*v.y, by - bs*v.x); glTexCoord2f(1.0f, 1.0f); glVertex2f(bx - bs*v.x, by - bs*v.y); glTexCoord2f(0.0f, 1.0f); glVertex2f(bx - bs*v.y, by + bs*v.x); } void drawteammates(fpsent *d, float x, float y, float s) { if(!radarteammates) return; float scale = calcradarscale(); int alive = 0, dead = 0; loopv(players) { fpsent *o = players[i]; if(o != d && o->state == CS_ALIVE && isteam(o->team, d->team)) { if(!alive++) { settexture(isteam(d->team, player1->team) ? "packages/hud/blip_blue_alive.png" : "packages/hud/blip_red_alive.png"); glBegin(GL_QUADS); } drawteammate(d, x, y, s, o, scale); } } if(alive) glEnd(); loopv(players) { fpsent *o = players[i]; if(o != d && o->state == CS_DEAD && isteam(o->team, d->team)) { if(!dead++) { settexture(isteam(d->team, player1->team) ? "packages/hud/blip_blue_dead.png" : "packages/hud/blip_red_dead.png"); glBegin(GL_QUADS); } drawteammate(d, x, y, s, o, scale); } } if(dead) glEnd(); } #include "capture.h" #include "ctf.h" #include "collect.h" clientmode *cmode = NULL; captureclientmode capturemode; ctfclientmode ctfmode; collectclientmode collectmode; void setclientmode() { if(m_capture) cmode = &capturemode; else if(m_ctf) cmode = &ctfmode; else if(m_collect) cmode = &collectmode; else cmode = NULL; } bool senditemstoserver = false, sendcrc = false; // after a map change, since server doesn't have map data int lastping = 0; bool connected = false, remote = false, demoplayback = false, gamepaused = false; int sessionid = 0, mastermode = MM_OPEN, gamespeed = 100; string servinfo = "", servauth = "", connectpass = ""; VARP(deadpush, 1, 2, 20); void switchname(const char *name) { if(name[0]) { filtertext(player1->name, name, false, MAXNAMELEN); if(!player1->name[0]) copystring(player1->name, "unnamed"); addmsg(N_SWITCHNAME, "rs", player1->name); } else conoutf("your name is: %s", colorname(player1)); } ICOMMAND(name, "s", (char *s), switchname(s)); ICOMMAND(getname, "", (), result(player1->name)); void switchteam(const char *team) { if(team[0]) { if(player1->clientnum < 0) filtertext(player1->team, team, false, MAXTEAMLEN); else addmsg(N_SWITCHTEAM, "rs", team); } else conoutf("your team is: %s", player1->team); } ICOMMAND(team, "s", (char *s), switchteam(s)); ICOMMAND(getteam, "", (), result(player1->team)); void switchplayermodel(int playermodel) { player1->playermodel = playermodel; addmsg(N_SWITCHMODEL, "ri", player1->playermodel); } struct authkey { char *name, *key, *desc; int lastauth; authkey(const char *name, const char *key, const char *desc) : name(newstring(name)), key(newstring(key)), desc(newstring(desc)), lastauth(0) { } ~authkey() { DELETEA(name); DELETEA(key); DELETEA(desc); } }; vector authkeys; authkey *findauthkey(const char *desc = "") { loopv(authkeys) if(!strcmp(authkeys[i]->desc, desc) && !strcasecmp(authkeys[i]->name, player1->name)) return authkeys[i]; loopv(authkeys) if(!strcmp(authkeys[i]->desc, desc)) return authkeys[i]; return NULL; } VARP(autoauth, 0, 1, 1); void addauthkey(const char *name, const char *key, const char *desc) { loopvrev(authkeys) if(!strcmp(authkeys[i]->desc, desc) && !strcmp(authkeys[i]->name, name)) delete authkeys.remove(i); if(name[0] && key[0]) authkeys.add(new authkey(name, key, desc)); } ICOMMAND(authkey, "sss", (char *name, char *key, char *desc), addauthkey(name, key, desc)); bool hasauthkey(const char *name, const char *desc) { if(!name[0] && !desc[0]) return authkeys.length() > 0; loopvrev(authkeys) if(!strcmp(authkeys[i]->desc, desc) && !strcmp(authkeys[i]->name, name)) return true; return false; } ICOMMAND(hasauthkey, "ss", (char *name, char *desc), intret(hasauthkey(name, desc) ? 1 : 0)); void genauthkey(const char *secret) { if(!secret[0]) { conoutf(CON_ERROR, "you must specify a secret password"); return; } vector privkey, pubkey; genprivkey(secret, privkey, pubkey); conoutf("private key: %s", privkey.getbuf()); conoutf("public key: %s", pubkey.getbuf()); } COMMAND(genauthkey, "s"); void saveauthkeys() { stream *f = openfile("auth.cfg", "w"); if(!f) { conoutf(CON_ERROR, "failed to open auth.cfg for writing"); return; } loopv(authkeys) { authkey *a = authkeys[i]; f->printf("authkey %s %s %s\n", escapestring(a->name), escapestring(a->key), escapestring(a->desc)); } conoutf("saved authkeys to auth.cfg"); delete f; } COMMAND(saveauthkeys, ""); void sendmapinfo() { if(!connected) return; sendcrc = true; if(player1->state!=CS_SPECTATOR || player1->privilege || !remote) senditemstoserver = true; } void writeclientinfo(stream *f) { f->printf("name %s\n", escapestring(player1->name)); } bool allowedittoggle() { if(editmode) return true; if(connected && multiplayer(false) && !m_edit) { conoutf(CON_ERROR, "editing in multiplayer requires coop edit mode (1)"); return false; } if(identexists("allowedittoggle") && !execute("allowedittoggle")) return false; return true; } void edittoggled(bool on) { addmsg(N_EDITMODE, "ri", on ? 1 : 0); if(player1->state==CS_DEAD) deathstate(player1, true); else if(player1->state==CS_EDITING && player1->editstate==CS_DEAD) showscores(false); disablezoom(); player1->suicided = player1->respawned = -2; } const char *getclientname(int cn) { fpsent *d = getclient(cn); return d ? d->name : ""; } ICOMMAND(getclientname, "i", (int *cn), result(getclientname(*cn))); const char *getclientteam(int cn) { fpsent *d = getclient(cn); return d ? d->team : ""; } ICOMMAND(getclientteam, "i", (int *cn), result(getclientteam(*cn))); int getclientmodel(int cn) { fpsent *d = getclient(cn); return d ? d->playermodel : -1; } ICOMMAND(getclientmodel, "i", (int *cn), intret(getclientmodel(*cn))); const char *getclienticon(int cn) { fpsent *d = getclient(cn); if(!d || d->state==CS_SPECTATOR) return "spectator"; const playermodelinfo &mdl = getplayermodelinfo(d); return m_teammode ? (isteam(player1->team, d->team) ? mdl.blueicon : mdl.redicon) : mdl.ffaicon; } ICOMMAND(getclienticon, "i", (int *cn), result(getclienticon(*cn))); bool ismaster(int cn) { fpsent *d = getclient(cn); return d && d->privilege >= PRIV_MASTER; } ICOMMAND(ismaster, "i", (int *cn), intret(ismaster(*cn) ? 1 : 0)); bool isauth(int cn) { fpsent *d = getclient(cn); return d && d->privilege >= PRIV_AUTH; } ICOMMAND(isauth, "i", (int *cn), intret(isauth(*cn) ? 1 : 0)); bool isadmin(int cn) { fpsent *d = getclient(cn); return d && d->privilege >= PRIV_ADMIN; } ICOMMAND(isadmin, "i", (int *cn), intret(isadmin(*cn) ? 1 : 0)); ICOMMAND(getmastermode, "", (), intret(mastermode)); ICOMMAND(mastermodename, "i", (int *mm), result(server::mastermodename(*mm, ""))); bool isspectator(int cn) { fpsent *d = getclient(cn); return d && d->state==CS_SPECTATOR; } ICOMMAND(isspectator, "i", (int *cn), intret(isspectator(*cn) ? 1 : 0)); bool isai(int cn, int type) { fpsent *d = getclient(cn); int aitype = type > 0 && type < AI_MAX ? type : AI_BOT; return d && d->aitype==aitype; } ICOMMAND(isai, "ii", (int *cn, int *type), intret(isai(*cn, *type) ? 1 : 0)); int parseplayer(const char *arg) { char *end; int n = strtol(arg, &end, 10); if(*arg && !*end) { if(n!=player1->clientnum && !clients.inrange(n)) return -1; return n; } // try case sensitive first loopv(players) { fpsent *o = players[i]; if(!strcmp(arg, o->name)) return o->clientnum; } // nothing found, try case insensitive loopv(players) { fpsent *o = players[i]; if(!strcasecmp(arg, o->name)) return o->clientnum; } return -1; } ICOMMAND(getclientnum, "s", (char *name), intret(name[0] ? parseplayer(name) : player1->clientnum)); void listclients(bool local, bool bots) { vector buf; string cn; int numclients = 0; if(local && connected) { formatstring(cn)("%d", player1->clientnum); buf.put(cn, strlen(cn)); numclients++; } loopv(clients) if(clients[i] && (bots || clients[i]->aitype == AI_NONE)) { formatstring(cn)("%d", clients[i]->clientnum); if(numclients++) buf.add(' '); buf.put(cn, strlen(cn)); } buf.add('\0'); result(buf.getbuf()); } ICOMMAND(listclients, "bb", (int *local, int *bots), listclients(*local>0, *bots!=0)); void clearbans() { addmsg(N_CLEARBANS, "r"); } COMMAND(clearbans, ""); void kick(const char *victim, const char *reason) { int vn = parseplayer(victim); if(vn>=0 && vn!=player1->clientnum) addmsg(N_KICK, "ris", vn, reason); } COMMAND(kick, "ss"); void authkick(const char *desc, const char *victim, const char *reason) { authkey *a = findauthkey(desc); int vn = parseplayer(victim); if(a && vn>=0 && vn!=player1->clientnum) { a->lastauth = lastmillis; addmsg(N_AUTHKICK, "rssis", a->desc, a->name, vn, reason); } } ICOMMAND(authkick, "ss", (const char *victim, const char *reason), authkick("", victim, reason)); ICOMMAND(sauthkick, "ss", (const char *victim, const char *reason), if(servauth[0]) authkick(servauth, victim, reason)); ICOMMAND(dauthkick, "sss", (const char *desc, const char *victim, const char *reason), if(desc[0]) authkick(desc, victim, reason)); vector ignores; void ignore(int cn) { fpsent *d = getclient(cn); if(!d || d == player1) return; conoutf("ignoring %s", d->name); if(ignores.find(cn) < 0) ignores.add(cn); } void unignore(int cn) { if(ignores.find(cn) < 0) return; fpsent *d = getclient(cn); if(d) conoutf("stopped ignoring %s", d->name); ignores.removeobj(cn); } bool isignored(int cn) { return ignores.find(cn) >= 0; } ICOMMAND(ignore, "s", (char *arg), ignore(parseplayer(arg))); ICOMMAND(unignore, "s", (char *arg), unignore(parseplayer(arg))); ICOMMAND(isignored, "s", (char *arg), intret(isignored(parseplayer(arg)) ? 1 : 0)); void setteam(const char *arg1, const char *arg2) { int i = parseplayer(arg1); if(i>=0) addmsg(N_SETTEAM, "ris", i, arg2); } COMMAND(setteam, "ss"); void hashpwd(const char *pwd) { if(player1->clientnum<0) return; string hash; server::hashpassword(player1->clientnum, sessionid, pwd, hash); result(hash); } COMMAND(hashpwd, "s"); void setmaster(const char *arg, const char *who) { if(!arg[0]) return; int val = 1, cn = player1->clientnum; if(who[0]) { cn = parseplayer(who); if(cn < 0) return; } string hash = ""; if(!arg[1] && isdigit(arg[0])) val = parseint(arg); else { if(cn != player1->clientnum) return; server::hashpassword(player1->clientnum, sessionid, arg, hash); } addmsg(N_SETMASTER, "riis", cn, val, hash); } COMMAND(setmaster, "ss"); ICOMMAND(mastermode, "i", (int *val), addmsg(N_MASTERMODE, "ri", *val)); bool tryauth(const char *desc) { authkey *a = findauthkey(desc); if(!a) return false; a->lastauth = lastmillis; addmsg(N_AUTHTRY, "rss", a->desc, a->name); return true; } ICOMMAND(auth, "s", (char *desc), tryauth(desc)); ICOMMAND(sauth, "", (), if(servauth[0]) tryauth(servauth)); ICOMMAND(dauth, "s", (char *desc), if(desc[0]) tryauth(desc)); void togglespectator(int val, const char *who) { int i = who[0] ? parseplayer(who) : player1->clientnum; if(i>=0) addmsg(N_SPECTATOR, "rii", i, val); } ICOMMAND(spectator, "is", (int *val, char *who), togglespectator(*val, who)); ICOMMAND(checkmaps, "", (), addmsg(N_CHECKMAPS, "r")); int gamemode = INT_MAX, nextmode = INT_MAX; string clientmap = ""; void changemapserv(const char *name, int mode) // forced map change from the server { if(multiplayer(false) && !m_mp(mode)) { conoutf(CON_ERROR, "mode %s (%d) not supported in multiplayer", server::modename(gamemode), gamemode); loopi(NUMGAMEMODES) if(m_mp(STARTGAMEMODE + i)) { mode = STARTGAMEMODE + i; break; } } gamemode = mode; nextmode = mode; if(editmode) toggleedit(); if(m_demo) { entities::resetspawns(); return; } if((m_edit && !name[0]) || !load_world(name)) { emptymap(0, true, name); senditemstoserver = false; } startgame(); } void setmode(int mode) { if(multiplayer(false) && !m_mp(mode)) { conoutf(CON_ERROR, "mode %s (%d) not supported in multiplayer", server::modename(mode), mode); intret(0); return; } nextmode = mode; intret(1); } ICOMMAND(mode, "i", (int *val), setmode(*val)); ICOMMAND(getmode, "", (), intret(gamemode)); ICOMMAND(timeremaining, "i", (int *formatted), { int val = max(maplimit - lastmillis, 0)/1000; if(*formatted) { defformatstring(str)("%d:%02d", val/60, val%60); result(str); } else intret(val); }); ICOMMANDS("m_noitems", "i", (int *mode), { int gamemode = *mode; intret(m_noitems); }); ICOMMANDS("m_noammo", "i", (int *mode), { int gamemode = *mode; intret(m_noammo); }); ICOMMANDS("m_insta", "i", (int *mode), { int gamemode = *mode; intret(m_insta); }); ICOMMANDS("m_tactics", "i", (int *mode), { int gamemode = *mode; intret(m_tactics); }); ICOMMANDS("m_efficiency", "i", (int *mode), { int gamemode = *mode; intret(m_efficiency); }); ICOMMANDS("m_capture", "i", (int *mode), { int gamemode = *mode; intret(m_capture); }); ICOMMANDS("m_regencapture", "i", (int *mode), { int gamemode = *mode; intret(m_regencapture); }); ICOMMANDS("m_ctf", "i", (int *mode), { int gamemode = *mode; intret(m_ctf); }); ICOMMANDS("m_protect", "i", (int *mode), { int gamemode = *mode; intret(m_protect); }); ICOMMANDS("m_hold", "i", (int *mode), { int gamemode = *mode; intret(m_hold); }); ICOMMANDS("m_collect", "i", (int *mode), { int gamemode = *mode; intret(m_collect); }); ICOMMANDS("m_teammode", "i", (int *mode), { int gamemode = *mode; intret(m_teammode); }); ICOMMANDS("m_demo", "i", (int *mode), { int gamemode = *mode; intret(m_demo); }); ICOMMANDS("m_edit", "i", (int *mode), { int gamemode = *mode; intret(m_edit); }); ICOMMANDS("m_lobby", "i", (int *mode), { int gamemode = *mode; intret(m_lobby); }); ICOMMANDS("m_sp", "i", (int *mode), { int gamemode = *mode; intret(m_sp); }); ICOMMANDS("m_dmsp", "i", (int *mode), { int gamemode = *mode; intret(m_dmsp); }); ICOMMANDS("m_classicsp", "i", (int *mode), { int gamemode = *mode; intret(m_classicsp); }); void changemap(const char *name, int mode) // request map change, server may ignore { if(!remote) { server::forcemap(name, mode); if(!connected) localconnect(); } else if(player1->state!=CS_SPECTATOR || player1->privilege) addmsg(N_MAPVOTE, "rsi", name, mode); } void changemap(const char *name) { changemap(name, m_valid(nextmode) ? nextmode : (remote ? 0 : 1)); } ICOMMAND(map, "s", (char *name), changemap(name)); void forceedit(const char *name) { changemap(name, 1); } void newmap(int size) { addmsg(N_NEWMAP, "ri", size); } int needclipboard = -1; void sendclipboard() { uchar *outbuf = NULL; int inlen = 0, outlen = 0; if(!packeditinfo(localedit, inlen, outbuf, outlen)) { outbuf = NULL; inlen = outlen = 0; } packetbuf p(16 + outlen, ENET_PACKET_FLAG_RELIABLE); putint(p, N_CLIPBOARD); putint(p, inlen); putint(p, outlen); if(outlen > 0) p.put(outbuf, outlen); sendclientpacket(p.finalize(), 1); needclipboard = -1; } void edittrigger(const selinfo &sel, int op, int arg1, int arg2, int arg3) { if(m_edit) switch(op) { case EDIT_FLIP: case EDIT_COPY: case EDIT_PASTE: case EDIT_DELCUBE: { switch(op) { case EDIT_COPY: needclipboard = 0; break; case EDIT_PASTE: if(needclipboard > 0) { c2sinfo(true); sendclipboard(); } break; } addmsg(N_EDITF + op, "ri9i4", sel.o.x, sel.o.y, sel.o.z, sel.s.x, sel.s.y, sel.s.z, sel.grid, sel.orient, sel.cx, sel.cxs, sel.cy, sel.cys, sel.corner); break; } case EDIT_ROTATE: { addmsg(N_EDITF + op, "ri9i5", sel.o.x, sel.o.y, sel.o.z, sel.s.x, sel.s.y, sel.s.z, sel.grid, sel.orient, sel.cx, sel.cxs, sel.cy, sel.cys, sel.corner, arg1); break; } case EDIT_MAT: case EDIT_FACE: case EDIT_TEX: { addmsg(N_EDITF + op, "ri9i6", sel.o.x, sel.o.y, sel.o.z, sel.s.x, sel.s.y, sel.s.z, sel.grid, sel.orient, sel.cx, sel.cxs, sel.cy, sel.cys, sel.corner, arg1, arg2); break; } case EDIT_REPLACE: { addmsg(N_EDITF + op, "ri9i7", sel.o.x, sel.o.y, sel.o.z, sel.s.x, sel.s.y, sel.s.z, sel.grid, sel.orient, sel.cx, sel.cxs, sel.cy, sel.cys, sel.corner, arg1, arg2, arg3); break; } case EDIT_REMIP: { addmsg(N_EDITF + op, "r"); break; } } } void printvar(fpsent *d, ident *id) { if(id) switch(id->type) { case ID_VAR: { int val = *id->storage.i; string str; if(val < 0) formatstring(str)("%d", val); else if(id->flags&IDF_HEX && id->maxval==0xFFFFFF) formatstring(str)("0x%.6X (%d, %d, %d)", val, (val>>16)&0xFF, (val>>8)&0xFF, val&0xFF); else formatstring(str)(id->flags&IDF_HEX ? "0x%X" : "%d", val); conoutf("%s set map var \"%s\" to %s", colorname(d), id->name, str); break; } case ID_FVAR: conoutf("%s set map var \"%s\" to %s", colorname(d), id->name, floatstr(*id->storage.f)); break; case ID_SVAR: conoutf("%s set map var \"%s\" to \"%s\"", colorname(d), id->name, *id->storage.s); break; } } void vartrigger(ident *id) { if(!m_edit) return; switch(id->type) { case ID_VAR: addmsg(N_EDITVAR, "risi", ID_VAR, id->name, *id->storage.i); break; case ID_FVAR: addmsg(N_EDITVAR, "risf", ID_FVAR, id->name, *id->storage.f); break; case ID_SVAR: addmsg(N_EDITVAR, "riss", ID_SVAR, id->name, *id->storage.s); break; default: return; } printvar(player1, id); } void pausegame(bool val) { if(!connected) return; if(!remote) server::forcepaused(val); else addmsg(N_PAUSEGAME, "ri", val ? 1 : 0); } ICOMMAND(pausegame, "i", (int *val), pausegame(*val > 0)); ICOMMAND(paused, "iN$", (int *val, int *numargs, ident *id), { if(*numargs > 0) pausegame(clampvar(id, *val, 0, 1) > 0); else if(*numargs < 0) intret(gamepaused ? 1 : 0); else printvar(id, gamepaused ? 1 : 0); }); bool ispaused() { return gamepaused; } bool allowmouselook() { return !gamepaused || !remote || m_edit; } void changegamespeed(int val) { if(!connected) return; if(!remote) server::forcegamespeed(val); else addmsg(N_GAMESPEED, "ri", val); } ICOMMAND(gamespeed, "iN$", (int *val, int *numargs, ident *id), { if(*numargs > 0) changegamespeed(clampvar(id, *val, 10, 1000)); else if(*numargs < 0) intret(gamespeed); else printvar(id, gamespeed); }); int scaletime(int t) { return t*gamespeed; } // collect c2s messages conveniently vector messages; int messagecn = -1, messagereliable = false; void addmsg(int type, const char *fmt, ...) { if(!connected) return; static uchar buf[MAXTRANS]; ucharbuf p(buf, sizeof(buf)); putint(p, type); int numi = 1, numf = 0, nums = 0, mcn = -1; bool reliable = false; if(fmt) { va_list args; va_start(args, fmt); while(*fmt) switch(*fmt++) { case 'r': reliable = true; break; case 'c': { fpsent *d = va_arg(args, fpsent *); mcn = !d || d == player1 ? -1 : d->clientnum; break; } case 'v': { int n = va_arg(args, int); int *v = va_arg(args, int *); loopi(n) putint(p, v[i]); numi += n; break; } case 'i': { int n = isdigit(*fmt) ? *fmt++-'0' : 1; loopi(n) putint(p, va_arg(args, int)); numi += n; break; } case 'f': { int n = isdigit(*fmt) ? *fmt++-'0' : 1; loopi(n) putfloat(p, (float)va_arg(args, double)); numf += n; break; } case 's': sendstring(va_arg(args, const char *), p); nums++; break; } va_end(args); } int num = nums || numf ? 0 : numi, msgsize = server::msgsizelookup(type); if(msgsize && num!=msgsize) { fatal("inconsistent msg size for %d (%d != %d)", type, num, msgsize); } if(reliable) messagereliable = true; if(mcn != messagecn) { static uchar mbuf[16]; ucharbuf m(mbuf, sizeof(mbuf)); putint(m, N_FROMAI); putint(m, mcn); messages.put(mbuf, m.length()); messagecn = mcn; } messages.put(buf, p.length()); } void connectattempt(const char *name, const char *password, const ENetAddress &address) { copystring(connectpass, password); } void connectfail() { memset(connectpass, 0, sizeof(connectpass)); } void gameconnect(bool _remote) { connected = true; remote = _remote; if(editmode) toggleedit(); } void gamedisconnect(bool cleanup) { if(remote) stopfollowing(); ignores.setsize(0); connected = remote = false; player1->clientnum = -1; sessionid = 0; mastermode = MM_OPEN; messages.setsize(0); messagereliable = false; messagecn = -1; player1->respawn(); player1->lifesequence = 0; player1->state = CS_ALIVE; player1->privilege = PRIV_NONE; sendcrc = senditemstoserver = false; demoplayback = false; gamepaused = false; gamespeed = 100; clearclients(false); if(cleanup) { nextmode = gamemode = INT_MAX; clientmap[0] = '\0'; } } void toserver(char *text) { conoutf(CON_CHAT, "%s:\f0 %s", colorname(player1), text); addmsg(N_TEXT, "rcs", player1, text); } COMMANDN(say, toserver, "C"); void sayteam(char *text) { conoutf(CON_TEAMCHAT, "%s:\f1 %s", colorname(player1), text); addmsg(N_SAYTEAM, "rcs", player1, text); } COMMAND(sayteam, "C"); ICOMMAND(servcmd, "C", (char *cmd), addmsg(N_SERVCMD, "rs", cmd)); static void sendposition(fpsent *d, packetbuf &q) { putint(q, N_POS); putuint(q, d->clientnum); // 3 bits phys state, 1 bit life sequence, 2 bits move, 2 bits strafe uchar physstate = d->physstate | ((d->lifesequence&1)<<3) | ((d->move&3)<<4) | ((d->strafe&3)<<6); q.put(physstate); ivec o = ivec(vec(d->o.x, d->o.y, d->o.z-d->eyeheight).mul(DMF)); uint vel = min(int(d->vel.magnitude()*DVELF), 0xFFFF), fall = min(int(d->falling.magnitude()*DVELF), 0xFFFF); // 3 bits position, 1 bit velocity, 3 bits falling, 1 bit material uint flags = 0; if(o.x < 0 || o.x > 0xFFFF) flags |= 1<<0; if(o.y < 0 || o.y > 0xFFFF) flags |= 1<<1; if(o.z < 0 || o.z > 0xFFFF) flags |= 1<<2; if(vel > 0xFF) flags |= 1<<3; if(fall > 0) { flags |= 1<<4; if(fall > 0xFF) flags |= 1<<5; if(d->falling.x || d->falling.y || d->falling.z > 0) flags |= 1<<6; } if((lookupmaterial(d->feetpos())&MATF_CLIP) == MAT_GAMECLIP) flags |= 1<<7; putuint(q, flags); loopk(3) { q.put(o[k]&0xFF); q.put((o[k]>>8)&0xFF); if(o[k] < 0 || o[k] > 0xFFFF) q.put((o[k]>>16)&0xFF); } uint dir = (d->yaw < 0 ? 360 + int(d->yaw)%360 : int(d->yaw)%360) + clamp(int(d->pitch+90), 0, 180)*360; q.put(dir&0xFF); q.put((dir>>8)&0xFF); q.put(clamp(int(d->roll+90), 0, 180)); q.put(vel&0xFF); if(vel > 0xFF) q.put((vel>>8)&0xFF); float velyaw, velpitch; vectoyawpitch(d->vel, velyaw, velpitch); uint veldir = (velyaw < 0 ? 360 + int(velyaw)%360 : int(velyaw)%360) + clamp(int(velpitch+90), 0, 180)*360; q.put(veldir&0xFF); q.put((veldir>>8)&0xFF); if(fall > 0) { q.put(fall&0xFF); if(fall > 0xFF) q.put((fall>>8)&0xFF); if(d->falling.x || d->falling.y || d->falling.z > 0) { float fallyaw, fallpitch; vectoyawpitch(d->falling, fallyaw, fallpitch); uint falldir = (fallyaw < 0 ? 360 + int(fallyaw)%360 : int(fallyaw)%360) + clamp(int(fallpitch+90), 0, 180)*360; q.put(falldir&0xFF); q.put((falldir>>8)&0xFF); } } } void sendposition(fpsent *d, bool reliable) { if(d->state != CS_ALIVE && d->state != CS_EDITING) return; packetbuf q(100, reliable ? ENET_PACKET_FLAG_RELIABLE : 0); sendposition(d, q); sendclientpacket(q.finalize(), 0); } void sendpositions() { loopv(players) { fpsent *d = players[i]; if((d == player1 || d->ai) && (d->state == CS_ALIVE || d->state == CS_EDITING)) { packetbuf q(100); sendposition(d, q); for(int j = i+1; j < players.length(); j++) { fpsent *d = players[j]; if((d == player1 || d->ai) && (d->state == CS_ALIVE || d->state == CS_EDITING)) sendposition(d, q); } sendclientpacket(q.finalize(), 0); break; } } } void sendmessages() { packetbuf p(MAXTRANS); if(sendcrc) { p.reliable(); sendcrc = false; const char *mname = getclientmap(); putint(p, N_MAPCRC); sendstring(mname, p); putint(p, mname[0] ? getmapcrc() : 0); } if(senditemstoserver) { if(!m_noitems || cmode!=NULL) p.reliable(); if(!m_noitems) entities::putitems(p); if(cmode) cmode->senditems(p); senditemstoserver = false; } if(messages.length()) { p.put(messages.getbuf(), messages.length()); messages.setsize(0); if(messagereliable) p.reliable(); messagereliable = false; messagecn = -1; } if(totalmillis-lastping>250) { putint(p, N_PING); putint(p, totalmillis); lastping = totalmillis; } sendclientpacket(p.finalize(), 1); } void c2sinfo(bool force) // send update to the server { static int lastupdate = -1000; if(totalmillis - lastupdate < 33 && !force) return; // don't update faster than 30fps lastupdate = totalmillis; sendpositions(); sendmessages(); flushclient(); } void sendintro() { packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE); putint(p, N_CONNECT); sendstring(player1->name, p); putint(p, player1->playermodel); string hash = ""; if(connectpass[0]) { server::hashpassword(player1->clientnum, sessionid, connectpass, hash); memset(connectpass, 0, sizeof(connectpass)); } sendstring(hash, p); authkey *a = servauth[0] && autoauth ? findauthkey(servauth) : NULL; if(a) { a->lastauth = lastmillis; sendstring(a->desc, p); sendstring(a->name, p); } else { sendstring("", p); sendstring("", p); } sendclientpacket(p.finalize(), 1); } void updatepos(fpsent *d) { // update the position of other clients in the game in our world // don't care if he's in the scenery or other players, // just don't overlap with our client const float r = player1->radius+d->radius; const float dx = player1->o.x-d->o.x; const float dy = player1->o.y-d->o.y; const float dz = player1->o.z-d->o.z; const float rz = player1->aboveeye+d->eyeheight; const float fx = (float)fabs(dx), fy = (float)fabs(dy), fz = (float)fabs(dz); if(fxstate!=CS_SPECTATOR && d->state!=CS_DEAD) { if(fxo.y += dy<0 ? r-fy : -(r-fy); // push aside else d->o.x += dx<0 ? r-fx : -(r-fx); } int lagtime = totalmillis-d->lastupdate; if(lagtime) { if(d->state!=CS_SPAWNING && d->lastupdate) d->plag = (d->plag*5+lagtime)/6; d->lastupdate = totalmillis; } } void parsepositions(ucharbuf &p) { int type; while(p.remaining()) switch(type = getint(p)) { case N_DEMOPACKET: break; case N_POS: // position of another client { int cn = getuint(p), physstate = p.get(), flags = getuint(p); vec o, vel, falling; float yaw, pitch, roll; loopk(3) { int n = p.get(); n |= p.get()<<8; if(flags&(1<>3)&1; fpsent *d = getclient(cn); if(!d || d->lifesequence < 0 || seqcolor!=(d->lifesequence&1) || d->state==CS_DEAD) continue; float oldyaw = d->yaw, oldpitch = d->pitch, oldroll = d->roll; d->yaw = yaw; d->pitch = pitch; d->roll = roll; d->move = (physstate>>4)&2 ? -1 : (physstate>>4)&1; d->strafe = (physstate>>6)&2 ? -1 : (physstate>>6)&1; vec oldpos(d->o); if(allowmove(d)) { d->o = o; d->o.z += d->eyeheight; d->vel = vel; d->falling = falling; d->physstate = physstate&7; } updatephysstate(d); updatepos(d); if(smoothmove && d->smoothmillis>=0 && oldpos.dist(d->o) < smoothdist) { d->newpos = d->o; d->newyaw = d->yaw; d->newpitch = d->pitch; d->newroll = d->roll; d->o = oldpos; d->yaw = oldyaw; d->pitch = oldpitch; d->roll = oldroll; (d->deltapos = oldpos).sub(d->newpos); d->deltayaw = oldyaw - d->newyaw; if(d->deltayaw > 180) d->deltayaw -= 360; else if(d->deltayaw < -180) d->deltayaw += 360; d->deltapitch = oldpitch - d->newpitch; d->deltaroll = oldroll - d->newroll; d->smoothmillis = lastmillis; } else d->smoothmillis = 0; if(d->state==CS_LAGGED || d->state==CS_SPAWNING) d->state = CS_ALIVE; break; } case N_TELEPORT: { int cn = getint(p), tp = getint(p), td = getint(p); fpsent *d = getclient(cn); if(!d || d->lifesequence < 0 || d->state==CS_DEAD) continue; entities::teleporteffects(d, tp, td, false); break; } case N_JUMPPAD: { int cn = getint(p), jp = getint(p); fpsent *d = getclient(cn); if(!d || d->lifesequence < 0 || d->state==CS_DEAD) continue; entities::jumppadeffects(d, jp, false); break; } default: neterr("type"); return; } } void parsestate(fpsent *d, ucharbuf &p, bool resume = false) { if(!d) { static fpsent dummy; d = &dummy; } if(resume) { if(d==player1) getint(p); else d->state = getint(p); d->frags = getint(p); d->flags = getint(p); if(d==player1) getint(p); else d->quadmillis = getint(p); } d->lifesequence = getint(p); d->health = getint(p); d->maxhealth = getint(p); d->armour = getint(p); d->armourtype = getint(p); if(resume && d==player1) { getint(p); loopi(GUN_PISTOL-GUN_SG+1) getint(p); } else { int gun = getint(p); d->gunselect = clamp(gun, int(GUN_FIST), int(GUN_PISTOL)); loopi(GUN_PISTOL-GUN_SG+1) d->ammo[GUN_SG+i] = getint(p); } } extern int deathscore; void parsemessages(int cn, fpsent *d, ucharbuf &p) { static char text[MAXTRANS]; int type; bool mapchanged = false, demopacket = false; while(p.remaining()) switch(type = getint(p)) { case N_DEMOPACKET: demopacket = true; break; case N_SERVINFO: // welcome messsage from the server { int mycn = getint(p), prot = getint(p); if(prot!=PROTOCOL_VERSION) { conoutf(CON_ERROR, "you are using a different game protocol (you: %d, server: %d)", PROTOCOL_VERSION, prot); disconnect(); return; } sessionid = getint(p); player1->clientnum = mycn; // we are now connected if(getint(p) > 0) conoutf("this server is password protected"); getstring(servinfo, p, sizeof(servinfo)); getstring(servauth, p, sizeof(servauth)); sendintro(); break; } case N_WELCOME: { notifywelcome(); break; } case N_PAUSEGAME: { bool val = getint(p) > 0; int cn = getint(p); fpsent *a = cn >= 0 ? getclient(cn) : NULL; if(!demopacket) { gamepaused = val; player1->attacking = false; } if(a) conoutf("%s %s the game", colorname(a), val ? "paused" : "resumed"); else conoutf("game is %s", val ? "paused" : "resumed"); break; } case N_GAMESPEED: { int val = clamp(getint(p), 10, 1000), cn = getint(p); fpsent *a = cn >= 0 ? getclient(cn) : NULL; if(!demopacket) gamespeed = val; extern int slowmosp; if(m_sp && slowmosp) break; if(a) conoutf("%s set gamespeed to %d", colorname(a), val); else conoutf("gamespeed is %d", val); break; } case N_CLIENT: { int cn = getint(p), len = getuint(p); ucharbuf q = p.subbuf(len); parsemessages(cn, getclient(cn), q); break; } case N_SOUND: if(!d) return; playsound(getint(p), &d->o); break; case N_TEXT: { if(!d) return; getstring(text, p); filtertext(text, text); if(isignored(d->clientnum)) break; if(d->state!=CS_DEAD && d->state!=CS_SPECTATOR) particle_textcopy(d->abovehead(), text, PART_TEXT, 2000, 0x32FF64, 4.0f, -8); conoutf(CON_CHAT, "%s:\f0 %s", colorname(d), text); break; } case N_SAYTEAM: { int tcn = getint(p); fpsent *t = getclient(tcn); getstring(text, p); filtertext(text, text); if(!t || isignored(t->clientnum)) break; if(t->state!=CS_DEAD && t->state!=CS_SPECTATOR) particle_textcopy(t->abovehead(), text, PART_TEXT, 2000, 0x6496FF, 4.0f, -8); conoutf(CON_TEAMCHAT, "%s:\f1 %s", colorname(t), text); break; } case N_MAPCHANGE: getstring(text, p); changemapserv(text, getint(p)); mapchanged = true; if(getint(p)) entities::spawnitems(); else senditemstoserver = false; break; case N_FORCEDEATH: { int cn = getint(p); fpsent *d = cn==player1->clientnum ? player1 : newclient(cn); if(!d) break; if(d==player1) { if(editmode) toggleedit(); stopfollowing(); if(deathscore) showscores(true); } else d->resetinterp(); d->state = CS_DEAD; break; } case N_ITEMLIST: { int n; while((n = getint(p))>=0 && !p.overread()) { if(mapchanged) entities::setspawn(n, true); getint(p); // type } break; } case N_INITCLIENT: // another client either connected or changed name/team { int cn = getint(p); fpsent *d = newclient(cn); if(!d) { getstring(text, p); getstring(text, p); getint(p); break; } getstring(text, p); filtertext(text, text, false, MAXNAMELEN); if(!text[0]) copystring(text, "unnamed"); if(d->name[0]) // already connected { if(strcmp(d->name, text) && !isignored(d->clientnum)) conoutf("%s is now known as %s", colorname(d), colorname(d, text)); } else // new client { conoutf("\f0join:\f7 %s", colorname(d, text)); if(needclipboard >= 0) needclipboard++; } copystring(d->name, text, MAXNAMELEN+1); getstring(text, p); filtertext(d->team, text, false, MAXTEAMLEN); d->playermodel = getint(p); break; } case N_SWITCHNAME: getstring(text, p); if(d) { filtertext(text, text, false, MAXNAMELEN); if(!text[0]) copystring(text, "unnamed"); if(strcmp(text, d->name)) { if(!isignored(d->clientnum)) conoutf("%s is now known as %s", colorname(d), colorname(d, text)); copystring(d->name, text, MAXNAMELEN+1); } } break; case N_SWITCHMODEL: { int model = getint(p); if(d) { d->playermodel = model; if(d->ragdoll) cleanragdoll(d); } break; } case N_CDIS: clientdisconnected(getint(p)); break; case N_SPAWN: { if(d) { if(d->state==CS_DEAD && d->lastpain) saveragdoll(d); d->respawn(); } parsestate(d, p); if(!d) break; d->state = CS_SPAWNING; if(player1->state==CS_SPECTATOR && following==d->clientnum) lasthit = 0; break; } case N_SPAWNSTATE: { int scn = getint(p); fpsent *s = getclient(scn); if(!s) { parsestate(NULL, p); break; } if(s->state==CS_DEAD && s->lastpain) saveragdoll(s); if(s==player1) { if(editmode) toggleedit(); stopfollowing(); } s->respawn(); parsestate(s, p); s->state = CS_ALIVE; if(cmode) cmode->pickspawn(s); else findplayerspawn(s); if(s == player1) { showscores(false); lasthit = 0; } if(cmode) cmode->respawned(s); ai::spawned(s); addmsg(N_SPAWN, "rcii", s, s->lifesequence, s->gunselect); break; } case N_SHOTFX: { int scn = getint(p), gun = getint(p), id = getint(p); vec from, to; loopk(3) from[k] = getint(p)/DMF; loopk(3) to[k] = getint(p)/DMF; fpsent *s = getclient(scn); if(!s) break; if(gun>GUN_FIST && gun<=GUN_PISTOL && s->ammo[gun]) s->ammo[gun]--; s->gunselect = clamp(gun, (int)GUN_FIST, (int)GUN_PISTOL); s->gunwait = guns[s->gunselect].attackdelay; int prevaction = s->lastaction; s->lastaction = lastmillis; s->lastattackgun = s->gunselect; shoteffects(s->gunselect, from, to, s, false, id, prevaction); break; } case N_EXPLODEFX: { int ecn = getint(p), gun = getint(p), id = getint(p); fpsent *e = getclient(ecn); if(!e) break; explodeeffects(gun, e, false, id); break; } case N_DAMAGE: { int tcn = getint(p), acn = getint(p), damage = getint(p), armour = getint(p), health = getint(p); fpsent *target = getclient(tcn), *actor = getclient(acn); if(!target || !actor) break; target->armour = armour; target->health = health; if(target->state == CS_ALIVE && actor != player1) target->lastpain = lastmillis; damaged(damage, target, actor, false); break; } case N_HITPUSH: { int tcn = getint(p), gun = getint(p), damage = getint(p); fpsent *target = getclient(tcn); vec dir; loopk(3) dir[k] = getint(p)/DNF; if(target) target->hitpush(damage * (target->health<=0 ? deadpush : 1), dir, NULL, gun); break; } case N_DIED: { int vcn = getint(p), acn = getint(p), frags = getint(p), tfrags = getint(p); fpsent *victim = getclient(vcn), *actor = getclient(acn); if(!actor) break; actor->frags = frags; if(m_teammode) setteaminfo(actor->team, tfrags); if(actor!=player1 && (!cmode || !cmode->hidefrags())) { defformatstring(ds)("%d", actor->frags); particle_textcopy(actor->abovehead(), ds, PART_TEXT, 2000, 0x32FF64, 4.0f, -8); } if(!victim) break; killed(victim, actor); break; } case N_TEAMINFO: for(;;) { getstring(text, p); if(p.overread() || !text[0]) break; int frags = getint(p); if(p.overread()) break; if(m_teammode) setteaminfo(text, frags); } break; case N_GUNSELECT: { if(!d) return; int gun = getint(p); d->gunselect = clamp(gun, int(GUN_FIST), int(GUN_PISTOL)); playsound(S_WEAPLOAD, &d->o); break; } case N_TAUNT: { if(!d) return; d->lasttaunt = lastmillis; break; } case N_RESUME: { for(;;) { int cn = getint(p); if(p.overread() || cn<0) break; fpsent *d = (cn == player1->clientnum ? player1 : newclient(cn)); parsestate(d, p, true); } break; } case N_ITEMSPAWN: { int i = getint(p); if(!entities::ents.inrange(i)) break; entities::setspawn(i, true); ai::itemspawned(i); playsound(S_ITEMSPAWN, &entities::ents[i]->o, NULL, 0, 0, 0, -1, 0, 1500); #if 0 const char *name = entities::itemname(i); if(name) particle_text(entities::ents[i]->o, name, PART_TEXT, 2000, 0x32FF64, 4.0f, -8); #endif int icon = entities::itemicon(i); if(icon >= 0) particle_icon(vec(0.0f, 0.0f, 4.0f).add(entities::ents[i]->o), icon%4, icon/4, PART_HUD_ICON, 2000, 0xFFFFFF, 2.0f, -8); break; } case N_ITEMACC: // server acknowledges that I picked up this item { int i = getint(p), cn = getint(p); fpsent *d = getclient(cn); entities::pickupeffects(i, d); break; } case N_CLIPBOARD: { int cn = getint(p), unpacklen = getint(p), packlen = getint(p); fpsent *d = getclient(cn); ucharbuf q = p.subbuf(max(packlen, 0)); if(d) unpackeditinfo(d->edit, q.buf, q.maxlen, unpacklen); break; } case N_EDITF: // coop editing messages case N_EDITT: case N_EDITM: case N_FLIP: case N_COPY: case N_PASTE: case N_ROTATE: case N_REPLACE: case N_DELCUBE: { if(!d) return; selinfo sel; sel.o.x = getint(p); sel.o.y = getint(p); sel.o.z = getint(p); sel.s.x = getint(p); sel.s.y = getint(p); sel.s.z = getint(p); sel.grid = getint(p); sel.orient = getint(p); sel.cx = getint(p); sel.cxs = getint(p); sel.cy = getint(p), sel.cys = getint(p); sel.corner = getint(p); int dir, mode, tex, newtex, mat, filter, allfaces, insel; ivec moveo; switch(type) { case N_EDITF: dir = getint(p); mode = getint(p); if(sel.validate()) mpeditface(dir, mode, sel, false); break; case N_EDITT: tex = getint(p); allfaces = getint(p); if(sel.validate()) mpedittex(tex, allfaces, sel, false); break; case N_EDITM: mat = getint(p); filter = getint(p); if(sel.validate()) mpeditmat(mat, filter, sel, false); break; case N_FLIP: if(sel.validate()) mpflip(sel, false); break; case N_COPY: if(d && sel.validate()) mpcopy(d->edit, sel, false); break; case N_PASTE: if(d && sel.validate()) mppaste(d->edit, sel, false); break; case N_ROTATE: dir = getint(p); if(sel.validate()) mprotate(dir, sel, false); break; case N_REPLACE: tex = getint(p); newtex = getint(p); insel = getint(p); if(sel.validate()) mpreplacetex(tex, newtex, insel>0, sel, false); break; case N_DELCUBE: if(sel.validate()) mpdelcube(sel, false); break; } break; } case N_REMIP: { if(!d) return; conoutf("%s remipped", colorname(d)); mpremip(false); break; } case N_EDITENT: // coop edit of ent { if(!d) return; int i = getint(p); float x = getint(p)/DMF, y = getint(p)/DMF, z = getint(p)/DMF; int type = getint(p); int attr1 = getint(p), attr2 = getint(p), attr3 = getint(p), attr4 = getint(p), attr5 = getint(p); mpeditent(i, vec(x, y, z), type, attr1, attr2, attr3, attr4, attr5, false); break; } case N_EDITVAR: { if(!d) return; int type = getint(p); getstring(text, p); string name; filtertext(name, text, false, MAXSTRLEN-1); ident *id = getident(name); switch(type) { case ID_VAR: { int val = getint(p); if(id && id->flags&IDF_OVERRIDE && !(id->flags&IDF_READONLY)) setvar(name, val); break; } case ID_FVAR: { float val = getfloat(p); if(id && id->flags&IDF_OVERRIDE && !(id->flags&IDF_READONLY)) setfvar(name, val); break; } case ID_SVAR: { getstring(text, p); if(id && id->flags&IDF_OVERRIDE && !(id->flags&IDF_READONLY)) setsvar(name, text); break; } } printvar(d, id); break; } case N_PONG: addmsg(N_CLIENTPING, "i", player1->ping = (player1->ping*5+totalmillis-getint(p))/6); break; case N_CLIENTPING: if(!d) return; d->ping = getint(p); break; case N_TIMEUP: timeupdate(getint(p)); break; case N_SERVMSG: getstring(text, p); conoutf("%s", text); break; case N_SENDDEMOLIST: { int demos = getint(p); if(demos <= 0) conoutf("no demos available"); else loopi(demos) { getstring(text, p); if(p.overread()) break; conoutf("%d. %s", i+1, text); } break; } case N_DEMOPLAYBACK: { int on = getint(p); if(on) player1->state = CS_SPECTATOR; else clearclients(); demoplayback = on!=0; player1->clientnum = getint(p); gamepaused = false; const char *alias = on ? "demostart" : "demoend"; if(identexists(alias)) execute(alias); break; } case N_CURRENTMASTER: { int mm = getint(p), mn; loopv(players) players[i]->privilege = PRIV_NONE; while((mn = getint(p))>=0 && !p.overread()) { fpsent *m = mn==player1->clientnum ? player1 : newclient(mn); int priv = getint(p); if(m) m->privilege = priv; } if(mm != mastermode) { mastermode = mm; conoutf("mastermode is %s (%d)", server::mastermodename(mastermode), mastermode); } break; } case N_MASTERMODE: { mastermode = getint(p); conoutf("mastermode is %s (%d)", server::mastermodename(mastermode), mastermode); break; } case N_EDITMODE: { int val = getint(p); if(!d) break; if(val) { d->editstate = d->state; d->state = CS_EDITING; } else { d->state = d->editstate; if(d->state==CS_DEAD) deathstate(d, true); } break; } case N_SPECTATOR: { int sn = getint(p), val = getint(p); fpsent *s; if(sn==player1->clientnum) { s = player1; if(val && remote && !player1->privilege) senditemstoserver = false; } else s = newclient(sn); if(!s) return; if(val) { if(s==player1) { if(editmode) toggleedit(); if(s->state==CS_DEAD) showscores(false); disablezoom(); } s->state = CS_SPECTATOR; } else if(s->state==CS_SPECTATOR) { if(s==player1) stopfollowing(); deathstate(s, true); } break; } case N_SETTEAM: { int wn = getint(p); getstring(text, p); int reason = getint(p); fpsent *w = getclient(wn); if(!w) return; filtertext(w->team, text, false, MAXTEAMLEN); static const char *fmt[2] = { "%s switched to team %s", "%s forced to team %s"}; if(reason >= 0 && size_t(reason) < sizeof(fmt)/sizeof(fmt[0])) conoutf(fmt[reason], colorname(w), w->team); break; } #define PARSEMESSAGES 1 #include "capture.h" #include "ctf.h" #include "collect.h" #undef PARSEMESSAGES case N_ANNOUNCE: { int t = getint(p); if (t==I_QUAD) { playsound(S_V_QUAD10, NULL, NULL, 0, 0, 0, -1, 0, 3000); conoutf(CON_GAMEINFO, "\f2quad damage will spawn in 10 seconds!"); } else if(t==I_BOOST) { playsound(S_V_BOOST10, NULL, NULL, 0, 0, 0, -1, 0, 3000); conoutf(CON_GAMEINFO, "\f2+10 health will spawn in 10 seconds!"); } break; } case N_NEWMAP: { int size = getint(p); if(size>=0) emptymap(size, true, NULL); else enlargemap(true); if(d && d!=player1) { int newsize = 0; while(1<=0 ? "%s started a new map of size %d" : "%s enlarged the map to size %d", colorname(d), newsize); } break; } case N_REQAUTH: { getstring(text, p); if(autoauth && text[0] && tryauth(text)) conoutf("server requested authkey \"%s\"", text); break; } case N_AUTHCHAL: { getstring(text, p); authkey *a = findauthkey(text); uint id = (uint)getint(p); getstring(text, p); if(a && a->lastauth && lastmillis - a->lastauth < 60*1000) { vector buf; answerchallenge(a->key, text, buf); //conoutf(CON_DEBUG, "answering %u, challenge %s with %s", id, text, buf.getbuf()); addmsg(N_AUTHANS, "rsis", a->desc, id, buf.getbuf()); } break; } case N_INITAI: { int bn = getint(p), on = getint(p), at = getint(p), sk = clamp(getint(p), 1, 101), pm = getint(p); string name, team; getstring(text, p); filtertext(name, text, false, MAXNAMELEN); getstring(text, p); filtertext(team, text, false, MAXTEAMLEN); fpsent *b = newclient(bn); if(!b) break; ai::init(b, at, on, sk, bn, pm, name, team); break; } case N_SERVCMD: getstring(text, p); break; default: neterr("type", cn < 0); return; } } void receivefile(packetbuf &p) { int type; while(p.remaining()) switch(type = getint(p)) { case N_DEMOPACKET: return; case N_SENDDEMO: { defformatstring(fname)("%d.dmo", lastmillis); stream *demo = openrawfile(fname, "wb"); if(!demo) return; conoutf("received demo \"%s\"", fname); ucharbuf b = p.subbuf(p.remaining()); demo->write(b.buf, b.maxlen); delete demo; break; } case N_SENDMAP: { if(!m_edit) return; string oldname; copystring(oldname, getclientmap()); defformatstring(mname)("getmap_%d", lastmillis); defformatstring(fname)("packages/base/%s.ogz", mname); stream *map = openrawfile(path(fname), "wb"); if(!map) return; conoutf("received map"); ucharbuf b = p.subbuf(p.remaining()); map->write(b.buf, b.maxlen); delete map; if(load_world(mname, oldname[0] ? oldname : NULL)) entities::spawnitems(true); remove(findfile(fname, "rb")); break; } } } void parsepacketclient(int chan, packetbuf &p) // processes any updates from the server { if(p.packet->flags&ENET_PACKET_FLAG_UNSEQUENCED) return; switch(chan) { case 0: parsepositions(p); break; case 1: parsemessages(-1, NULL, p); break; case 2: receivefile(p); break; } } void getmap() { if(!m_edit) { conoutf(CON_ERROR, "\"getmap\" only works in coop edit mode"); return; } conoutf("getting map..."); addmsg(N_GETMAP, "r"); } COMMAND(getmap, ""); void stopdemo() { if(remote) { if(player1->privilegeprivilegeprivilegestate==CS_SPECTATOR && remote && !player1->privilege)) { conoutf(CON_ERROR, "\"sendmap\" only works in coop edit mode"); return; } conoutf("sending map..."); defformatstring(mname)("sendmap_%d", lastmillis); save_world(mname, true); defformatstring(fname)("packages/base/%s.ogz", mname); stream *map = openrawfile(path(fname), "rb"); if(map) { stream::offset len = map->size(); if(len > 4*1024*1024) conoutf(CON_ERROR, "map is too large"); else if(len <= 0) conoutf(CON_ERROR, "could not read map"); else { sendfile(-1, 2, map); if(needclipboard >= 0) needclipboard++; } delete map; } else conoutf(CON_ERROR, "could not read map"); remove(findfile(fname, "rb")); } COMMAND(sendmap, ""); void gotoplayer(const char *arg) { if(player1->state!=CS_SPECTATOR && player1->state!=CS_EDITING) return; int i = parseplayer(arg); if(i>=0) { fpsent *d = getclient(i); if(!d || d==player1) return; player1->o = d->o; vec dir; vecfromyawpitch(player1->yaw, player1->pitch, 1, 0, dir); player1->o.add(dir.mul(-32)); player1->resetinterp(); } } COMMANDN(goto, gotoplayer, "s"); void gotosel() { if(player1->state!=CS_EDITING) return; player1->o = getselpos(); vec dir; vecfromyawpitch(player1->yaw, player1->pitch, 1, 0, dir); player1->o.add(dir.mul(-32)); player1->resetinterp(); } COMMAND(gotosel, ""); } sauerbraten-0.0.20130203.dfsg/fpsgame/pch.cpp0000644000175000017500000000002311164573771020304 0ustar vincentvincent#include "game.h" sauerbraten-0.0.20130203.dfsg/fpsgame/movable.cpp0000644000175000017500000001327212067451473021166 0ustar vincentvincent// movable.cpp: implements physics for inanimate models #include "game.h" extern int physsteps; namespace game { enum { BOXWEIGHT = 25, BARRELHEALTH = 50, BARRELWEIGHT = 25, PLATFORMWEIGHT = 1000, PLATFORMSPEED = 8, EXPLODEDELAY = 200 }; struct movable : dynent { int etype, mapmodel, health, weight, exploding, tag, dir; physent *stacked; vec stackpos; movable(const entity &e) : etype(e.type), mapmodel(e.attr2), health(e.type==BARREL ? (e.attr4 ? e.attr4 : BARRELHEALTH) : 0), weight(e.type==PLATFORM || e.type==ELEVATOR ? PLATFORMWEIGHT : (e.attr3 ? e.attr3 : (e.type==BARREL ? BARRELWEIGHT : BOXWEIGHT))), exploding(0), tag(e.type==PLATFORM || e.type==ELEVATOR ? e.attr3 : 0), dir(e.type==PLATFORM || e.type==ELEVATOR ? (e.attr4 < 0 ? -1 : 1) : 0), stacked(NULL), stackpos(0, 0, 0) { state = CS_ALIVE; type = ENT_INANIMATE; yaw = e.attr1; if(e.type==PLATFORM || e.type==ELEVATOR) { maxspeed = e.attr4 ? fabs(float(e.attr4)) : PLATFORMSPEED; if(tag) vel = vec(0, 0, 0); else if(e.type==PLATFORM) { vecfromyawpitch(yaw, 0, 1, 0, vel); vel.mul(dir*maxspeed); } else vel = vec(0, 0, dir*maxspeed); } const char *mdlname = mapmodelname(e.attr2); if(mdlname) setbbfrommodel(this, mdlname); } void hitpush(int damage, const vec &dir, fpsent *actor, int gun) { if(etype!=BOX && etype!=BARREL) return; vec push(dir); push.mul(80*damage/weight); vel.add(push); } void explode(dynent *at) { state = CS_DEAD; exploding = 0; game::explode(true, (fpsent *)at, o, this, guns[GUN_BARREL].damage, GUN_BARREL); } void damaged(int damage, fpsent *at, int gun = -1) { if(etype!=BARREL || state!=CS_ALIVE || exploding) return; health -= damage; if(health>0) return; if(gun==GUN_BARREL) exploding = lastmillis + EXPLODEDELAY; else explode(at); } void suicide() { state = CS_DEAD; if(etype==BARREL) explode(player1); } }; vector movables; void clearmovables() { if(movables.length()) { cleardynentcache(); movables.deletecontents(); } if(!m_dmsp && !m_classicsp) return; loopv(entities::ents) { const entity &e = *entities::ents[i]; if(e.type!=BOX && e.type!=BARREL && e.type!=PLATFORM && e.type!=ELEVATOR) continue; movable *m = new movable(e); movables.add(m); m->o = e.o; entinmap(m); updatedynentcache(m); } } void triggerplatform(int tag, int newdir) { newdir = max(-1, min(1, newdir)); loopv(movables) { movable *m = movables[i]; if(m->state!=CS_ALIVE || (m->etype!=PLATFORM && m->etype!=ELEVATOR) || m->tag!=tag) continue; if(!newdir) { if(m->tag) m->vel = vec(0, 0, 0); else m->vel.neg(); } else { if(m->etype==PLATFORM) { vecfromyawpitch(m->yaw, 0, 1, 0, m->vel); m->vel.mul(newdir*m->dir*m->maxspeed); } else m->vel = vec(0, 0, newdir*m->dir*m->maxspeed); } } } ICOMMAND(platform, "ii", (int *tag, int *newdir), triggerplatform(*tag, *newdir)); void stackmovable(movable *d, physent *o) { d->stacked = o; d->stackpos = o->o; } void updatemovables(int curtime) { if(!curtime) return; loopv(movables) { movable *m = movables[i]; if(m->state!=CS_ALIVE) continue; if(m->etype==PLATFORM || m->etype==ELEVATOR) { if(m->vel.iszero()) continue; for(int remaining = curtime; remaining>0;) { int step = min(remaining, 20); remaining -= step; if(!moveplatform(m, vec(m->vel).mul(step/1000.0f))) { if(m->tag) { m->vel = vec(0, 0, 0); break; } else m->vel.neg(); } } } else if(m->exploding && lastmillis >= m->exploding) { m->explode(m); adddecal(DECAL_SCORCH, m->o, vec(0, 0, 1), guns[GUN_BARREL].exprad/2); } else if(m->maymove() || (m->stacked && (m->stacked->state!=CS_ALIVE || m->stackpos != m->stacked->o))) { if(physsteps > 0) m->stacked = NULL; moveplayer(m, 1, true); } } } void rendermovables() { loopv(movables) { movable &m = *movables[i]; if(m.state!=CS_ALIVE) continue; vec o = m.feetpos(); const char *mdlname = mapmodelname(m.mapmodel); if(!mdlname) continue; rendermodel(NULL, mdlname, ANIM_MAPMODEL|ANIM_LOOP, o, m.yaw, 0, MDL_LIGHT | MDL_SHADOW | MDL_CULL_VFC | MDL_CULL_DIST | MDL_CULL_OCCLUDED, &m); } } void suicidemovable(movable *m) { m->suicide(); } void hitmovable(int damage, movable *m, fpsent *at, const vec &vel, int gun) { m->hitpush(damage, vel, at, gun); m->damaged(damage, at, gun); } } sauerbraten-0.0.20130203.dfsg/fpsgame/scoreboard.cpp0000644000175000017500000003240212071311257021646 0ustar vincentvincent// creation of scoreboard #include "game.h" namespace game { VARP(scoreboard2d, 0, 1, 1); VARP(showservinfo, 0, 1, 1); VARP(showclientnum, 0, 0, 1); VARP(showpj, 0, 0, 1); VARP(showping, 0, 1, 1); VARP(showspectators, 0, 1, 1); VARP(highlightscore, 0, 1, 1); VARP(showconnecting, 0, 0, 1); static hashset teaminfos; void clearteaminfo() { teaminfos.clear(); } void setteaminfo(const char *team, int frags) { teaminfo *t = teaminfos.access(team); if(!t) { t = &teaminfos[team]; copystring(t->team, team, sizeof(t->team)); } t->frags = frags; } static inline bool playersort(const fpsent *a, const fpsent *b) { if(a->state==CS_SPECTATOR) { if(b->state==CS_SPECTATOR) return strcmp(a->name, b->name) < 0; else return false; } else if(b->state==CS_SPECTATOR) return true; if(m_ctf || m_collect) { if(a->flags > b->flags) return true; if(a->flags < b->flags) return false; } if(a->frags > b->frags) return true; if(a->frags < b->frags) return false; return strcmp(a->name, b->name) < 0; } void getbestplayers(vector &best) { loopv(players) { fpsent *o = players[i]; if(o->state!=CS_SPECTATOR) best.add(o); } best.sort(playersort); while(best.length() > 1 && best.last()->frags < best[0]->frags) best.drop(); } void getbestteams(vector &best) { if(cmode && cmode->hidefrags()) { vector teamscores; cmode->getteamscores(teamscores); teamscores.sort(teamscore::compare); while(teamscores.length() > 1 && teamscores.last().score < teamscores[0].score) teamscores.drop(); loopv(teamscores) best.add(teamscores[i].team); } else { int bestfrags = INT_MIN; enumerates(teaminfos, teaminfo, t, bestfrags = max(bestfrags, t.frags)); if(bestfrags <= 0) loopv(players) { fpsent *o = players[i]; if(o->state!=CS_SPECTATOR && !teaminfos.access(o->team) && best.htfind(o->team) < 0) { bestfrags = 0; best.add(o->team); } } enumerates(teaminfos, teaminfo, t, if(t.frags >= bestfrags) best.add(t.team)); } } struct scoregroup : teamscore { vector players; }; static vector groups; static vector spectators; static inline bool scoregroupcmp(const scoregroup *x, const scoregroup *y) { if(!x->team) { if(y->team) return false; } else if(!y->team) return true; if(x->score > y->score) return true; if(x->score < y->score) return false; if(x->players.length() > y->players.length()) return true; if(x->players.length() < y->players.length()) return false; return x->team && y->team && strcmp(x->team, y->team) < 0; } static int groupplayers() { int numgroups = 0; spectators.setsize(0); loopv(players) { fpsent *o = players[i]; if(!showconnecting && !o->name[0]) continue; if(o->state==CS_SPECTATOR) { spectators.add(o); continue; } const char *team = m_teammode && o->team[0] ? o->team : NULL; bool found = false; loopj(numgroups) { scoregroup &g = *groups[j]; if(team!=g.team && (!team || !g.team || strcmp(team, g.team))) continue; g.players.add(o); found = true; } if(found) continue; if(numgroups>=groups.length()) groups.add(new scoregroup); scoregroup &g = *groups[numgroups++]; g.team = team; if(!team) g.score = 0; else if(cmode && cmode->hidefrags()) g.score = cmode->getteamscore(o->team); else { teaminfo *ti = teaminfos.access(team); g.score = ti ? ti->frags : 0; } g.players.setsize(0); g.players.add(o); } loopi(numgroups) groups[i]->players.sort(playersort); spectators.sort(playersort); groups.sort(scoregroupcmp, 0, numgroups); return numgroups; } void renderscoreboard(g3d_gui &g, bool firstpass) { const ENetAddress *address = connectedpeer(); if(showservinfo && address) { string hostname; if(enet_address_get_host_ip(address, hostname, sizeof(hostname)) >= 0) { if(servinfo[0]) g.titlef("%.25s", 0xFFFF80, NULL, servinfo); else g.titlef("%s:%d", 0xFFFF80, NULL, hostname, address->port); } } g.pushlist(); g.spring(); g.text(server::modename(gamemode), 0xFFFF80); g.separator(); const char *mname = getclientmap(); g.text(mname[0] ? mname : "[new map]", 0xFFFF80); extern int gamespeed; if(gamespeed != 100) { g.separator(); g.textf("%d.%02dx", 0xFFFF80, NULL, gamespeed/100, gamespeed%100); } if(m_timed && mname[0] && (maplimit >= 0 || intermission)) { g.separator(); if(intermission) g.text("intermission", 0xFFFF80); else { int secs = max(maplimit-lastmillis, 0)/1000, mins = secs/60; secs %= 60; g.pushlist(); g.strut(mins >= 10 ? 4.5f : 3.5f); g.textf("%d:%02d", 0xFFFF80, NULL, mins, secs); g.poplist(); } } if(ispaused()) { g.separator(); g.text("paused", 0xFFFF80); } g.spring(); g.poplist(); g.separator(); int numgroups = groupplayers(); loopk(numgroups) { if((k%2)==0) g.pushlist(); // horizontal scoregroup &sg = *groups[k]; int bgcolor = sg.team && m_teammode ? (isteam(player1->team, sg.team) ? 0x3030C0 : 0xC03030) : 0, fgcolor = 0xFFFF80; g.pushlist(); // vertical g.pushlist(); // horizontal #define loopscoregroup(o, b) \ loopv(sg.players) \ { \ fpsent *o = sg.players[i]; \ b; \ } g.pushlist(); if(sg.team && m_teammode) { g.pushlist(); g.background(bgcolor, numgroups>1 ? 3 : 5); g.strut(1); g.poplist(); } g.text("", 0, " "); loopscoregroup(o, { if(o==player1 && highlightscore && (multiplayer(false) || demoplayback || players.length() > 1)) { g.pushlist(); g.background(0x808080, numgroups>1 ? 3 : 5); } const playermodelinfo &mdl = getplayermodelinfo(o); const char *icon = sg.team && m_teammode ? (isteam(player1->team, sg.team) ? mdl.blueicon : mdl.redicon) : mdl.ffaicon; g.text("", 0, icon); if(o==player1 && highlightscore && (multiplayer(false) || demoplayback || players.length() > 1)) g.poplist(); }); g.poplist(); if(sg.team && m_teammode) { g.pushlist(); // vertical if(sg.score>=10000) g.textf("%s: WIN", fgcolor, NULL, sg.team); else g.textf("%s: %d", fgcolor, NULL, sg.team, sg.score); g.pushlist(); // horizontal } if(!cmode || !cmode->hidefrags()) { g.pushlist(); g.strut(6); g.text("frags", fgcolor); loopscoregroup(o, g.textf("%d", 0xFFFFDD, NULL, o->frags)); g.poplist(); } g.pushlist(); g.text("name", fgcolor); g.strut(13); loopscoregroup(o, { int status = o->state!=CS_DEAD ? 0xFFFFDD : 0x606060; if(o->privilege) { status = o->privilege>=PRIV_ADMIN ? 0xFF8000 : 0x40FF80; if(o->state==CS_DEAD) status = (status>>1)&0x7F7F7F; } g.textf("%s ", status, NULL, colorname(o)); }); g.poplist(); if(multiplayer(false) || demoplayback) { if(showpj) { g.pushlist(); g.strut(6); g.text("pj", fgcolor); loopscoregroup(o, { if(o->state==CS_LAGGED) g.text("LAG", 0xFFFFDD); else g.textf("%d", 0xFFFFDD, NULL, o->plag); }); g.poplist(); } if(showping) { g.pushlist(); g.text("ping", fgcolor); g.strut(6); loopscoregroup(o, { fpsent *p = o->ownernum >= 0 ? getclient(o->ownernum) : o; if(!p) p = o; if(!showpj && p->state==CS_LAGGED) g.text("LAG", 0xFFFFDD); else g.textf("%d", 0xFFFFDD, NULL, p->ping); }); g.poplist(); } } if(showclientnum || player1->privilege>=PRIV_MASTER) { g.space(1); g.pushlist(); g.text("cn", fgcolor); loopscoregroup(o, g.textf("%d", 0xFFFFDD, NULL, o->clientnum)); g.poplist(); } if(sg.team && m_teammode) { g.poplist(); // horizontal g.poplist(); // vertical } g.poplist(); // horizontal g.poplist(); // vertical if(k+1privilege>=PRIV_MASTER) { g.pushlist(); g.pushlist(); g.text("spectator", 0xFFFF80, " "); loopv(spectators) { fpsent *o = spectators[i]; int status = 0xFFFFDD; if(o->privilege) status = o->privilege>=PRIV_ADMIN ? 0xFF8000 : 0x40FF80; if(o==player1 && highlightscore) { g.pushlist(); g.background(0x808080, 3); } g.text(colorname(o), status, "spectator"); if(o==player1 && highlightscore) g.poplist(); } g.poplist(); g.space(1); g.pushlist(); g.text("cn", 0xFFFF80); loopv(spectators) g.textf("%d", 0xFFFFDD, NULL, spectators[i]->clientnum); g.poplist(); g.poplist(); } else { g.textf("%d spectator%s", 0xFFFF80, " ", spectators.length(), spectators.length()!=1 ? "s" : ""); loopv(spectators) { if((i%3)==0) { g.pushlist(); g.text("", 0xFFFFDD, "spectator"); } fpsent *o = spectators[i]; int status = 0xFFFFDD; if(o->privilege) status = o->privilege>=PRIV_ADMIN ? 0xFF8000 : 0x40FF80; if(o==player1 && highlightscore) { g.pushlist(); g.background(0x808080); } g.text(colorname(o), status); if(o==player1 && highlightscore) g.poplist(); if(i+1= STARTGAMEMODE && (mode) < STARTGAMEMODE + NUMGAMEMODES) #define m_check(mode, flag) (m_valid(mode) && gamemodes[(mode) - STARTGAMEMODE].flags&(flag)) #define m_checknot(mode, flag) (m_valid(mode) && !(gamemodes[(mode) - STARTGAMEMODE].flags&(flag))) #define m_checkall(mode, flag) (m_valid(mode) && (gamemodes[(mode) - STARTGAMEMODE].flags&(flag)) == (flag)) #define m_noitems (m_check(gamemode, M_NOITEMS)) #define m_noammo (m_check(gamemode, M_NOAMMO|M_NOITEMS)) #define m_insta (m_check(gamemode, M_INSTA)) #define m_tactics (m_check(gamemode, M_TACTICS)) #define m_efficiency (m_check(gamemode, M_EFFICIENCY)) #define m_capture (m_check(gamemode, M_CAPTURE)) #define m_regencapture (m_checkall(gamemode, M_CAPTURE | M_REGEN)) #define m_ctf (m_check(gamemode, M_CTF)) #define m_protect (m_checkall(gamemode, M_CTF | M_PROTECT)) #define m_hold (m_checkall(gamemode, M_CTF | M_HOLD)) #define m_collect (m_check(gamemode, M_COLLECT)) #define m_teammode (m_check(gamemode, M_TEAM)) #define m_overtime (m_check(gamemode, M_OVERTIME)) #define isteam(a,b) (m_teammode && strcmp(a, b)==0) #define m_demo (m_check(gamemode, M_DEMO)) #define m_edit (m_check(gamemode, M_EDIT)) #define m_lobby (m_check(gamemode, M_LOBBY)) #define m_timed (m_checknot(gamemode, M_DEMO|M_EDIT|M_LOCAL)) #define m_botmode (m_checknot(gamemode, M_DEMO|M_LOCAL)) #define m_mp(mode) (m_checknot(mode, M_LOCAL)) #define m_sp (m_check(gamemode, M_DMSP | M_CLASSICSP)) #define m_dmsp (m_check(gamemode, M_DMSP)) #define m_classicsp (m_check(gamemode, M_CLASSICSP)) enum { MM_AUTH = -1, MM_OPEN = 0, MM_VETO, MM_LOCKED, MM_PRIVATE, MM_PASSWORD, MM_START = MM_AUTH }; static const char * const mastermodenames[] = { "auth", "open", "veto", "locked", "private", "password" }; static const char * const mastermodecolors[] = { "", "\f0", "\f2", "\f2", "\f3", "\f3" }; static const char * const mastermodeicons[] = { "server", "server", "serverlock", "serverlock", "serverpriv", "serverpriv" }; // hardcoded sounds, defined in sounds.cfg enum { S_JUMP = 0, S_LAND, S_RIFLE, S_PUNCH1, S_SG, S_CG, S_RLFIRE, S_RLHIT, S_WEAPLOAD, S_ITEMAMMO, S_ITEMHEALTH, S_ITEMARMOUR, S_ITEMPUP, S_ITEMSPAWN, S_TELEPORT, S_NOAMMO, S_PUPOUT, S_PAIN1, S_PAIN2, S_PAIN3, S_PAIN4, S_PAIN5, S_PAIN6, S_DIE1, S_DIE2, S_FLAUNCH, S_FEXPLODE, S_SPLASH1, S_SPLASH2, S_GRUNT1, S_GRUNT2, S_RUMBLE, S_PAINO, S_PAINR, S_DEATHR, S_PAINE, S_DEATHE, S_PAINS, S_DEATHS, S_PAINB, S_DEATHB, S_PAINP, S_PIGGR2, S_PAINH, S_DEATHH, S_PAIND, S_DEATHD, S_PIGR1, S_ICEBALL, S_SLIMEBALL, S_JUMPPAD, S_PISTOL, S_V_BASECAP, S_V_BASELOST, S_V_FIGHT, S_V_BOOST, S_V_BOOST10, S_V_QUAD, S_V_QUAD10, S_V_RESPAWNPOINT, S_FLAGPICKUP, S_FLAGDROP, S_FLAGRETURN, S_FLAGSCORE, S_FLAGRESET, S_BURN, S_CHAINSAW_ATTACK, S_CHAINSAW_IDLE, S_HIT, S_FLAGFAIL }; // network messages codes, c2s, c2c, s2c enum { PRIV_NONE = 0, PRIV_MASTER, PRIV_AUTH, PRIV_ADMIN }; enum { N_CONNECT = 0, N_SERVINFO, N_WELCOME, N_INITCLIENT, N_POS, N_TEXT, N_SOUND, N_CDIS, N_SHOOT, N_EXPLODE, N_SUICIDE, N_DIED, N_DAMAGE, N_HITPUSH, N_SHOTFX, N_EXPLODEFX, N_TRYSPAWN, N_SPAWNSTATE, N_SPAWN, N_FORCEDEATH, N_GUNSELECT, N_TAUNT, N_MAPCHANGE, N_MAPVOTE, N_TEAMINFO, N_ITEMSPAWN, N_ITEMPICKUP, N_ITEMACC, N_TELEPORT, N_JUMPPAD, N_PING, N_PONG, N_CLIENTPING, N_TIMEUP, N_FORCEINTERMISSION, N_SERVMSG, N_ITEMLIST, N_RESUME, N_EDITMODE, N_EDITENT, N_EDITF, N_EDITT, N_EDITM, N_FLIP, N_COPY, N_PASTE, N_ROTATE, N_REPLACE, N_DELCUBE, N_REMIP, N_NEWMAP, N_GETMAP, N_SENDMAP, N_CLIPBOARD, N_EDITVAR, N_MASTERMODE, N_KICK, N_CLEARBANS, N_CURRENTMASTER, N_SPECTATOR, N_SETMASTER, N_SETTEAM, N_BASES, N_BASEINFO, N_BASESCORE, N_REPAMMO, N_BASEREGEN, N_ANNOUNCE, N_LISTDEMOS, N_SENDDEMOLIST, N_GETDEMO, N_SENDDEMO, N_DEMOPLAYBACK, N_RECORDDEMO, N_STOPDEMO, N_CLEARDEMOS, N_TAKEFLAG, N_RETURNFLAG, N_RESETFLAG, N_INVISFLAG, N_TRYDROPFLAG, N_DROPFLAG, N_SCOREFLAG, N_INITFLAGS, N_SAYTEAM, N_CLIENT, N_AUTHTRY, N_AUTHKICK, N_AUTHCHAL, N_AUTHANS, N_REQAUTH, N_PAUSEGAME, N_GAMESPEED, N_ADDBOT, N_DELBOT, N_INITAI, N_FROMAI, N_BOTLIMIT, N_BOTBALANCE, N_MAPCRC, N_CHECKMAPS, N_SWITCHNAME, N_SWITCHMODEL, N_SWITCHTEAM, N_INITTOKENS, N_TAKETOKEN, N_EXPIRETOKENS, N_DROPTOKENS, N_DEPOSITTOKENS, N_STEALTOKENS, N_SERVCMD, N_DEMOPACKET, NUMMSG }; static const int msgsizes[] = // size inclusive message token, 0 for variable or not-checked sizes { N_CONNECT, 0, N_SERVINFO, 0, N_WELCOME, 1, N_INITCLIENT, 0, N_POS, 0, N_TEXT, 0, N_SOUND, 2, N_CDIS, 2, N_SHOOT, 0, N_EXPLODE, 0, N_SUICIDE, 1, N_DIED, 5, N_DAMAGE, 6, N_HITPUSH, 7, N_SHOTFX, 10, N_EXPLODEFX, 4, N_TRYSPAWN, 1, N_SPAWNSTATE, 14, N_SPAWN, 3, N_FORCEDEATH, 2, N_GUNSELECT, 2, N_TAUNT, 1, N_MAPCHANGE, 0, N_MAPVOTE, 0, N_TEAMINFO, 0, N_ITEMSPAWN, 2, N_ITEMPICKUP, 2, N_ITEMACC, 3, N_PING, 2, N_PONG, 2, N_CLIENTPING, 2, N_TIMEUP, 2, N_FORCEINTERMISSION, 1, N_SERVMSG, 0, N_ITEMLIST, 0, N_RESUME, 0, N_EDITMODE, 2, N_EDITENT, 11, N_EDITF, 16, N_EDITT, 16, N_EDITM, 16, N_FLIP, 14, N_COPY, 14, N_PASTE, 14, N_ROTATE, 15, N_REPLACE, 17, N_DELCUBE, 14, N_REMIP, 1, N_NEWMAP, 2, N_GETMAP, 1, N_SENDMAP, 0, N_EDITVAR, 0, N_MASTERMODE, 2, N_KICK, 0, N_CLEARBANS, 1, N_CURRENTMASTER, 0, N_SPECTATOR, 3, N_SETMASTER, 0, N_SETTEAM, 0, N_BASES, 0, N_BASEINFO, 0, N_BASESCORE, 0, N_REPAMMO, 1, N_BASEREGEN, 6, N_ANNOUNCE, 2, N_LISTDEMOS, 1, N_SENDDEMOLIST, 0, N_GETDEMO, 2, N_SENDDEMO, 0, N_DEMOPLAYBACK, 3, N_RECORDDEMO, 2, N_STOPDEMO, 1, N_CLEARDEMOS, 2, N_TAKEFLAG, 3, N_RETURNFLAG, 4, N_RESETFLAG, 6, N_INVISFLAG, 3, N_TRYDROPFLAG, 1, N_DROPFLAG, 7, N_SCOREFLAG, 10, N_INITFLAGS, 0, N_SAYTEAM, 0, N_CLIENT, 0, N_AUTHTRY, 0, N_AUTHKICK, 0, N_AUTHCHAL, 0, N_AUTHANS, 0, N_REQAUTH, 0, N_PAUSEGAME, 0, N_GAMESPEED, 0, N_ADDBOT, 2, N_DELBOT, 1, N_INITAI, 0, N_FROMAI, 2, N_BOTLIMIT, 2, N_BOTBALANCE, 2, N_MAPCRC, 0, N_CHECKMAPS, 1, N_SWITCHNAME, 0, N_SWITCHMODEL, 2, N_SWITCHTEAM, 0, N_INITTOKENS, 0, N_TAKETOKEN, 2, N_EXPIRETOKENS, 0, N_DROPTOKENS, 0, N_DEPOSITTOKENS, 2, N_STEALTOKENS, 0, N_SERVCMD, 0, N_DEMOPACKET, 0, -1 }; #define SAUERBRATEN_LANINFO_PORT 28784 #define SAUERBRATEN_SERVER_PORT 28785 #define SAUERBRATEN_SERVINFO_PORT 28786 #define SAUERBRATEN_MASTER_PORT 28787 #define PROTOCOL_VERSION 259 // bump when protocol changes #define DEMO_VERSION 1 // bump when demo format changes #define DEMO_MAGIC "SAUERBRATEN_DEMO" struct demoheader { char magic[16]; int version, protocol; }; #define MAXNAMELEN 15 #define MAXTEAMLEN 4 enum { HICON_BLUE_ARMOUR = 0, HICON_GREEN_ARMOUR, HICON_YELLOW_ARMOUR, HICON_HEALTH, HICON_FIST, HICON_SG, HICON_CG, HICON_RL, HICON_RIFLE, HICON_GL, HICON_PISTOL, HICON_QUAD, HICON_RED_FLAG, HICON_BLUE_FLAG, HICON_NEUTRAL_FLAG, HICON_TOKEN, HICON_X = 20, HICON_Y = 1650, HICON_TEXTY = 1644, HICON_STEP = 490, HICON_SIZE = 120, HICON_SPACE = 40 }; static struct itemstat { int add, max, sound; const char *name; int icon, info; } itemstats[] = { {10, 30, S_ITEMAMMO, "SG", HICON_SG, GUN_SG}, {20, 60, S_ITEMAMMO, "CG", HICON_CG, GUN_CG}, {5, 15, S_ITEMAMMO, "RL", HICON_RL, GUN_RL}, {5, 15, S_ITEMAMMO, "RI", HICON_RIFLE, GUN_RIFLE}, {10, 30, S_ITEMAMMO, "GL", HICON_GL, GUN_GL}, {30, 120, S_ITEMAMMO, "PI", HICON_PISTOL, GUN_PISTOL}, {25, 100, S_ITEMHEALTH, "H", HICON_HEALTH}, {10, 1000, S_ITEMHEALTH, "MH", HICON_HEALTH}, {100, 100, S_ITEMARMOUR, "GA", HICON_GREEN_ARMOUR, A_GREEN}, {200, 200, S_ITEMARMOUR, "YA", HICON_YELLOW_ARMOUR, A_YELLOW}, {20000, 30000, S_ITEMPUP, "Q", HICON_QUAD}, }; #define MAXRAYS 20 #define EXP_SELFDAMDIV 2 #define EXP_SELFPUSH 2.5f #define EXP_DISTSCALE 1.5f static const struct guninfo { int sound, attackdelay, damage, spread, projspeed, kickamount, range, rays, hitpush, exprad, ttl; const char *name, *file; short part; } guns[NUMGUNS] = { { S_PUNCH1, 250, 50, 0, 0, 0, 14, 1, 80, 0, 0, "fist", "fist", 0 }, { S_SG, 1400, 10, 400, 0, 20, 1024, 20, 80, 0, 0, "shotgun", "shotg", 0 }, { S_CG, 100, 30, 100, 0, 7, 1024, 1, 80, 0, 0, "chaingun", "chaing", 0 }, { S_RLFIRE, 800, 120, 0, 320, 10, 1024, 1, 160, 40, 0, "rocketlauncher", "rocket", 0 }, { S_RIFLE, 1500, 100, 0, 0, 30, 2048, 1, 80, 0, 0, "rifle", "rifle", 0 }, { S_FLAUNCH, 600, 90, 0, 200, 10, 1024, 1, 250, 45, 1500, "grenadelauncher", "gl", 0 }, { S_PISTOL, 500, 35, 50, 0, 7, 1024, 1, 80, 0, 0, "pistol", "pistol", 0 }, { S_FLAUNCH, 200, 20, 0, 200, 1, 1024, 1, 80, 40, 0, "fireball", NULL, PART_FIREBALL1 }, { S_ICEBALL, 200, 40, 0, 120, 1, 1024, 1, 80, 40, 0, "iceball", NULL, PART_FIREBALL2 }, { S_SLIMEBALL, 200, 30, 0, 640, 1, 1024, 1, 80, 40, 0, "slimeball", NULL, PART_FIREBALL3 }, { S_PIGR1, 250, 50, 0, 0, 1, 12, 1, 80, 0, 0, "bite", NULL, 0 }, { -1, 0, 120, 0, 0, 0, 0, 1, 80, 40, 0, "barrel", NULL, 0 } }; #include "ai.h" // inherited by fpsent and server clients struct fpsstate { int health, maxhealth; int armour, armourtype; int quadmillis; int gunselect, gunwait; int ammo[NUMGUNS]; int aitype, skill; fpsstate() : maxhealth(100), aitype(AI_NONE), skill(0) {} void baseammo(int gun, int k = 2, int scale = 1) { ammo[gun] = (itemstats[gun-GUN_SG].add*k)/scale; } void addammo(int gun, int k = 1, int scale = 1) { itemstat &is = itemstats[gun-GUN_SG]; ammo[gun] = min(ammo[gun] + (is.add*k)/scale, is.max); } bool hasmaxammo(int type) { const itemstat &is = itemstats[type-I_SHELLS]; return ammo[type-I_SHELLS+GUN_SG]>=is.max; } bool canpickup(int type) { if(typeI_QUAD) return false; itemstat &is = itemstats[type-I_SHELLS]; switch(type) { case I_BOOST: return maxhealth=100) return false; case I_YELLOWARMOUR: return !armourtype || armourI_QUAD) return; itemstat &is = itemstats[type-I_SHELLS]; switch(type) { case I_BOOST: maxhealth = min(maxhealth+is.add, is.max); case I_HEALTH: // boost also adds to health health = min(health+is.add, maxhealth); break; case I_GREENARMOUR: case I_YELLOWARMOUR: armour = min(armour+is.add, is.max); armourtype = is.info; break; case I_QUAD: quadmillis = min(quadmillis+is.add, is.max); break; default: ammo[is.info] = min(ammo[is.info]+is.add, is.max); break; } } void respawn() { health = maxhealth; armour = 0; armourtype = A_BLUE; quadmillis = 0; gunselect = GUN_PISTOL; gunwait = 0; loopi(NUMGUNS) ammo[i] = 0; ammo[GUN_FIST] = 1; } void spawnstate(int gamemode) { if(m_demo) { gunselect = GUN_FIST; } else if(m_insta) { armour = 0; health = 1; gunselect = GUN_RIFLE; ammo[GUN_RIFLE] = 100; } else if(m_regencapture) { armourtype = A_BLUE; armour = 25; gunselect = GUN_PISTOL; ammo[GUN_PISTOL] = 40; ammo[GUN_GL] = 1; } else if(m_tactics) { armourtype = A_GREEN; armour = 100; ammo[GUN_PISTOL] = 40; int spawngun1 = rnd(5)+1, spawngun2; gunselect = spawngun1; baseammo(spawngun1, m_noitems ? 2 : 1); do spawngun2 = rnd(5)+1; while(spawngun1==spawngun2); baseammo(spawngun2, m_noitems ? 2 : 1); if(m_noitems) ammo[GUN_GL] += 1; } else if(m_efficiency) { armourtype = A_GREEN; armour = 100; loopi(5) baseammo(i+1); gunselect = GUN_CG; ammo[GUN_CG] /= 2; } else if(m_ctf || m_collect) { armourtype = A_BLUE; armour = 50; ammo[GUN_PISTOL] = 40; ammo[GUN_GL] = 1; } else if(m_sp) { if(m_dmsp) { armourtype = A_BLUE; armour = 25; } ammo[GUN_PISTOL] = 80; ammo[GUN_GL] = 1; } else { armourtype = A_BLUE; armour = 25; ammo[GUN_PISTOL] = 40; ammo[GUN_GL] = 1; } } // just subtract damage here, can set death, etc. later in code calling this int dodamage(int damage) { int ad = damage*(armourtype+1)*25/100; // let armour absorb when possible if(ad>armour) ad = armour; armour -= ad; damage -= ad; health -= damage; return damage; } int hasammo(int gun, int exclude = -1) { return gun >= 0 && gun <= NUMGUNS && gun != exclude && ammo[gun] > 0; } }; struct fpsent : dynent, fpsstate { int weight; // affects the effectiveness of hitpush int clientnum, privilege, lastupdate, plag, ping; int lifesequence; // sequence id for each respawn, used in damage test int respawned, suicided; int lastpain; int lastaction, lastattackgun; bool attacking; int attacksound, attackchan, idlesound, idlechan; int lasttaunt; int lastpickup, lastpickupmillis, lastbase, lastrepammo, flagpickup, tokens; vec lastcollect; int frags, flags, deaths, totaldamage, totalshots; editinfo *edit; float deltayaw, deltapitch, deltaroll, newyaw, newpitch, newroll; int smoothmillis; string name, team, info; int playermodel; ai::aiinfo *ai; int ownernum, lastnode; vec muzzle; fpsent() : weight(100), clientnum(-1), privilege(PRIV_NONE), lastupdate(0), plag(0), ping(0), lifesequence(0), respawned(-1), suicided(-1), lastpain(0), attacksound(-1), attackchan(-1), idlesound(-1), idlechan(-1), frags(0), flags(0), deaths(0), totaldamage(0), totalshots(0), edit(NULL), smoothmillis(-1), playermodel(-1), ai(NULL), ownernum(-1), muzzle(-1, -1, -1) { name[0] = team[0] = info[0] = 0; respawn(); } ~fpsent() { freeeditinfo(edit); if(attackchan >= 0) stopsound(attacksound, attackchan); if(idlechan >= 0) stopsound(idlesound, idlechan); if(ai) delete ai; } void hitpush(int damage, const vec &dir, fpsent *actor, int gun) { vec push(dir); push.mul((actor==this && guns[gun].exprad ? EXP_SELFPUSH : 1.0f)*guns[gun].hitpush*damage/weight); vel.add(push); } void stopattacksound() { if(attackchan >= 0) stopsound(attacksound, attackchan, 250); attacksound = attackchan = -1; } void stopidlesound() { if(idlechan >= 0) stopsound(idlesound, idlechan, 100); idlesound = idlechan = -1; } void respawn() { dynent::reset(); fpsstate::respawn(); respawned = suicided = -1; lastaction = 0; lastattackgun = gunselect; attacking = false; lasttaunt = 0; lastpickup = -1; lastpickupmillis = 0; lastbase = lastrepammo = -1; flagpickup = 0; tokens = 0; lastcollect = vec(-1e10f, -1e10f, -1e10f); stopattacksound(); lastnode = -1; } }; struct teamscore { const char *team; int score; teamscore() {} teamscore(const char *s, int n) : team(s), score(n) {} static bool compare(const teamscore &x, const teamscore &y) { if(x.score > y.score) return true; if(x.score < y.score) return false; return strcmp(x.team, y.team) < 0; } }; static inline uint hthash(const teamscore &t) { return hthash(t.team); } static inline bool htcmp(const char *key, const teamscore &t) { return htcmp(key, t.team); } #define MAXTEAMS 128 struct teaminfo { char team[MAXTEAMLEN+1]; int frags; }; static inline uint hthash(const teaminfo &t) { return hthash(t.team); } static inline bool htcmp(const char *team, const teaminfo &t) { return !strcmp(team, t.team); } namespace entities { extern vector ents; extern const char *entmdlname(int type); extern const char *itemname(int i); extern int itemicon(int i); extern void preloadentities(); extern void renderentities(); extern void resettriggers(); extern void checktriggers(); extern void checkitems(fpsent *d); extern void checkquad(int time, fpsent *d); extern void resetspawns(); extern void spawnitems(bool force = false); extern void putitems(packetbuf &p); extern void setspawn(int i, bool on); extern void teleport(int n, fpsent *d); extern void pickupeffects(int n, fpsent *d); extern void teleporteffects(fpsent *d, int tp, int td, bool local = true); extern void jumppadeffects(fpsent *d, int jp, bool local = true); extern void repammo(fpsent *d, int type, bool local = true); } namespace game { struct clientmode { virtual ~clientmode() {} virtual void preload() {} virtual int clipconsole(int w, int h) { return 0; } virtual void drawhud(fpsent *d, int w, int h) {} virtual void rendergame() {} virtual void respawned(fpsent *d) {} virtual void setup() {} virtual void checkitems(fpsent *d) {} virtual int respawnwait(fpsent *d) { return 0; } virtual void pickspawn(fpsent *d) { findplayerspawn(d); } virtual void senditems(packetbuf &p) {} virtual void removeplayer(fpsent *d) {} virtual void gameover() {} virtual bool hidefrags() { return false; } virtual int getteamscore(const char *team) { return 0; } virtual void getteamscores(vector &scores) {} virtual void aifind(fpsent *d, ai::aistate &b, vector &interests) {} virtual bool aicheck(fpsent *d, ai::aistate &b) { return false; } virtual bool aidefend(fpsent *d, ai::aistate &b) { return false; } virtual bool aipursue(fpsent *d, ai::aistate &b) { return false; } }; extern clientmode *cmode; extern void setclientmode(); // fps extern int gamemode, nextmode; extern string clientmap; extern bool intermission; extern int maptime, maprealtime, maplimit; extern fpsent *player1; extern vector players, clients; extern int lastspawnattempt; extern int lasthit; extern int respawnent; extern int following; extern int smoothmove, smoothdist; extern bool clientoption(const char *arg); extern fpsent *getclient(int cn); extern fpsent *newclient(int cn); extern const char *colorname(fpsent *d, const char *name = NULL, const char *prefix = "", const char *suffix = "", const char *alt = NULL); extern const char *teamcolorname(fpsent *d, const char *alt = "you"); extern const char *teamcolor(const char *name, bool sameteam, const char *alt = NULL); extern const char *teamcolor(const char *name, const char *team, const char *alt = NULL); extern fpsent *pointatplayer(); extern fpsent *hudplayer(); extern fpsent *followingplayer(); extern void stopfollowing(); extern void clientdisconnected(int cn, bool notify = true); extern void clearclients(bool notify = true); extern void startgame(); extern void spawnplayer(fpsent *); extern void deathstate(fpsent *d, bool restore = false); extern void damaged(int damage, fpsent *d, fpsent *actor, bool local = true); extern void killed(fpsent *d, fpsent *actor); extern void timeupdate(int timeremain); extern void msgsound(int n, physent *d = NULL); extern void drawicon(int icon, float x, float y, float sz = 120); const char *mastermodecolor(int n, const char *unknown); const char *mastermodeicon(int n, const char *unknown); // client extern bool connected, remote, demoplayback; extern string servinfo; extern int parseplayer(const char *arg); extern void ignore(int cn); extern void unignore(int cn); extern bool isignored(int cn); extern void addmsg(int type, const char *fmt = NULL, ...); extern void switchname(const char *name); extern void switchteam(const char *name); extern void switchplayermodel(int playermodel); extern void sendmapinfo(); extern void stopdemo(); extern void changemap(const char *name, int mode); extern void c2sinfo(bool force = false); extern void sendposition(fpsent *d, bool reliable = false); // monster struct monster; extern vector monsters; extern void clearmonsters(); extern void preloadmonsters(); extern void stackmonster(monster *d, physent *o); extern void updatemonsters(int curtime); extern void rendermonsters(); extern void suicidemonster(monster *m); extern void hitmonster(int damage, monster *m, fpsent *at, const vec &vel, int gun); extern void monsterkilled(); extern void endsp(bool allkilled); extern void spsummary(int accuracy); // movable struct movable; extern vector movables; extern void clearmovables(); extern void stackmovable(movable *d, physent *o); extern void updatemovables(int curtime); extern void rendermovables(); extern void suicidemovable(movable *m); extern void hitmovable(int damage, movable *m, fpsent *at, const vec &vel, int gun); // weapon extern int getweapon(const char *name); extern void shoot(fpsent *d, const vec &targ); extern void shoteffects(int gun, const vec &from, const vec &to, fpsent *d, bool local, int id, int prevaction); extern void explode(bool local, fpsent *owner, const vec &v, dynent *safe, int dam, int gun); extern void explodeeffects(int gun, fpsent *d, bool local, int id = 0); extern void damageeffect(int damage, fpsent *d, bool thirdperson = true); extern void gibeffect(int damage, const vec &vel, fpsent *d); extern float intersectdist; extern bool intersect(dynent *d, const vec &from, const vec &to, float &dist = intersectdist); extern dynent *intersectclosest(const vec &from, const vec &to, fpsent *at, float &dist = intersectdist); extern void clearbouncers(); extern void updatebouncers(int curtime); extern void removebouncers(fpsent *owner); extern void renderbouncers(); extern void clearprojectiles(); extern void updateprojectiles(int curtime); extern void removeprojectiles(fpsent *owner); extern void renderprojectiles(); extern void preloadbouncers(); extern void removeweapons(fpsent *owner); extern void updateweapons(int curtime); extern void gunselect(int gun, fpsent *d); extern void weaponswitch(fpsent *d); extern void avoidweapons(ai::avoidset &obstacles, float radius); // scoreboard extern void showscores(bool on); extern void getbestplayers(vector &best); extern void getbestteams(vector &best); extern void clearteaminfo(); extern void setteaminfo(const char *team, int frags); // render struct playermodelinfo { const char *ffa, *blueteam, *redteam, *hudguns, *vwep, *quad, *armour[3], *ffaicon, *blueicon, *redicon; bool ragdoll; }; extern int playermodel, teamskins, testteam; extern void saveragdoll(fpsent *d); extern void clearragdolls(); extern void moveragdolls(); extern void changedplayermodel(); extern const playermodelinfo &getplayermodelinfo(fpsent *d); extern int chooserandomplayermodel(int seed); extern void swayhudgun(int curtime); extern vec hudgunorigin(int gun, const vec &from, const vec &to, fpsent *d); } namespace server { extern const char *modename(int n, const char *unknown = "unknown"); extern const char *mastermodename(int n, const char *unknown = "unknown"); extern void startintermission(); extern void stopdemo(); extern void forcemap(const char *map, int mode); extern void forcepaused(bool paused); extern void forcegamespeed(int speed); extern void hashpassword(int cn, int sessionid, const char *pwd, char *result, int maxlen = MAXSTRLEN); extern int msgsizelookup(int msg); extern bool serveroption(const char *arg); extern bool delayspawn(int type); } #endif sauerbraten-0.0.20130203.dfsg/fpsgame/monster.cpp0000644000175000017500000004322312067465167021234 0ustar vincentvincent// monster.h: implements AI for single player monsters, currently client only #include "game.h" extern int physsteps; namespace game { static vector teleports; static const int TOTMFREQ = 14; static const int NUMMONSTERTYPES = 9; struct monstertype // see docs for how these values modify behaviour { short gun, speed, health, freq, lag, rate, pain, loyalty, bscale, weight; short painsound, diesound; const char *name, *mdlname, *vwepname; }; static const monstertype monstertypes[NUMMONSTERTYPES] = { { GUN_FIREBALL, 15, 100, 3, 0, 100, 800, 1, 10, 90, S_PAINO, S_DIE1, "an ogro", "ogro", "ogro/vwep"}, { GUN_CG, 18, 70, 2, 70, 10, 400, 2, 10, 50, S_PAINR, S_DEATHR, "a rhino", "monster/rhino", NULL}, { GUN_SG, 13, 120, 1, 100, 300, 400, 4, 14, 115, S_PAINE, S_DEATHE, "ratamahatta", "monster/rat", "monster/rat/vwep"}, { GUN_RIFLE, 14, 200, 1, 80, 400, 300, 4, 18, 145, S_PAINS, S_DEATHS, "a slith", "monster/slith", "monster/slith/vwep"}, { GUN_RL, 12, 500, 1, 0, 200, 200, 6, 24, 210, S_PAINB, S_DEATHB, "bauul", "monster/bauul", "monster/bauul/vwep"}, { GUN_BITE, 24, 50, 3, 0, 100, 400, 1, 15, 75, S_PAINP, S_PIGGR2, "a hellpig", "monster/hellpig", NULL}, { GUN_ICEBALL, 11, 250, 1, 0, 10, 400, 6, 18, 160, S_PAINH, S_DEATHH, "a knight", "monster/knight", "monster/knight/vwep"}, { GUN_SLIMEBALL, 15, 100, 1, 0, 200, 400, 2, 10, 60, S_PAIND, S_DEATHD, "a goblin", "monster/goblin", "monster/goblin/vwep"}, { GUN_GL, 22, 50, 1, 0, 200, 400, 1, 10, 40, S_PAIND, S_DEATHD, "a spider", "monster/spider", NULL }, }; VAR(skill, 1, 3, 10); VAR(killsendsp, 0, 1, 1); bool monsterhurt; vec monsterhurtpos; struct monster : fpsent { int monsterstate; // one of M_*, M_NONE means human int mtype, tag; // see monstertypes table fpsent *enemy; // monster wants to kill this entity float targetyaw; // monster wants to look in this direction int trigger; // millis at which transition to another monsterstate takes place vec attacktarget; // delayed attacks int anger; // how many times already hit by fellow monster physent *stacked; vec stackpos; monster(int _type, int _yaw, int _tag, int _state, int _trigger, int _move) : monsterstate(_state), tag(_tag), stacked(NULL), stackpos(0, 0, 0) { type = ENT_AI; respawn(); if(_type>=NUMMONSTERTYPES || _type < 0) { conoutf(CON_WARN, "warning: unknown monster in spawn: %d", _type); _type = 0; } mtype = _type; const monstertype &t = monstertypes[mtype]; eyeheight = 8.0f; aboveeye = 7.0f; radius *= t.bscale/10.0f; xradius = yradius = radius; eyeheight *= t.bscale/10.0f; aboveeye *= t.bscale/10.0f; weight = t.weight; if(_state!=M_SLEEP) spawnplayer(this); trigger = lastmillis+_trigger; targetyaw = yaw = (float)_yaw; move = _move; enemy = player1; gunselect = t.gun; maxspeed = (float)t.speed*4; health = t.health; armour = 0; loopi(NUMGUNS) ammo[i] = 10000; pitch = 0; roll = 0; state = CS_ALIVE; anger = 0; copystring(name, t.name); } void normalize_yaw(float angle) { while(yawangle+180.0f) yaw -= 360.0f; } // monster AI is sequenced using transitions: they are in a particular state where // they execute a particular behaviour until the trigger time is hit, and then they // reevaluate their situation based on the current state, the environment etc., and // transition to the next state. Transition timeframes are parametrized by difficulty // level (skill), faster transitions means quicker decision making means tougher AI. void transition(int _state, int _moving, int n, int r) // n = at skill 0, n/2 = at skill 10, r = added random factor { monsterstate = _state; move = _moving; n = n*130/100; trigger = lastmillis+n-skill*(n/16)+rnd(r+1); } void monsteraction(int curtime) // main AI thinking routine, called every frame for every monster { if(enemy->state==CS_DEAD) { enemy = player1; anger = 0; } normalize_yaw(targetyaw); if(targetyaw>yaw) // slowly turn monster towards his target { yaw += curtime*0.5f; if(targetyawyaw) yaw = targetyaw; } float dist = enemy->o.dist(o); if(monsterstate!=M_SLEEP) pitch = asin((enemy->o.z - o.z) / dist) / RAD; if(blocked) // special case: if we run into scenery { blocked = false; if(!rnd(20000/monstertypes[mtype].speed)) // try to jump over obstackle (rare) { jumping = true; } else if(triggero.x - o.x, enemy->o.y - o.y)/RAD; switch(monsterstate) { case M_PAIN: case M_ATTACKING: case M_SEARCH: if(triggero, target)) { transition(M_HOME, 1, 500, 200); playsound(S_GRUNT1+rnd(2), &o); } } break; } case M_AIMING: // this state is the delay between wanting to shoot and actually firing if(triggero, target)) // no visual contact anymore, let monster get as close as possible then search for player { transition(M_HOME, 1, 800, 500); } else { bool melee = false, longrange = false; switch(monstertypes[mtype].gun) { case GUN_BITE: case GUN_FIST: melee = true; break; case GUN_RIFLE: longrange = true; break; } // the closer the monster is the more likely he wants to shoot, if((!melee || dist<20) && !rnd(longrange ? (int)dist/12+1 : min((int)dist/12+1,6)) && enemy->state==CS_ALIVE) // get ready to fire { attacktarget = target; transition(M_AIMING, 0, monstertypes[mtype].lag, 10); } else // track player some more { transition(M_HOME, 1, monstertypes[mtype].rate, 0); } } } break; } if(move || maymove() || (stacked && (stacked->state!=CS_ALIVE || stackpos != stacked->o))) { vec pos = feetpos(); loopv(teleports) // equivalent of player entity touch, but only teleports are used { entity &e = *entities::ents[teleports[i]]; float dist = e.o.dist(pos); if(dist<16) entities::teleport(teleports[i], this); } if(physsteps > 0) stacked = NULL; moveplayer(this, 1, true); // use physics to move monster } } void monsterpain(int damage, fpsent *d) { if(d->type==ENT_AI) // a monster hit us { if(this!=d) // guard for RL guys shooting themselves :) { anger++; // don't attack straight away, first get angry int _anger = d->type==ENT_AI && mtype==((monster *)d)->mtype ? anger/2 : anger; if(_anger>=monstertypes[mtype].loyalty) enemy = d; // monster infight if very angry } } else if(d->type==ENT_PLAYER) // player hit us { anger = 0; enemy = d; monsterhurt = true; monsterhurtpos = o; } damageeffect(damage, this); if((health -= damage)<=0) { state = CS_DEAD; lastpain = lastmillis; playsound(monstertypes[mtype].diesound, &o); monsterkilled(); gibeffect(max(-health, 0), vel, this); defformatstring(id)("monster_dead_%d", tag); if(identexists(id)) execute(id); } else { transition(M_PAIN, 0, monstertypes[mtype].pain, 200); // in this state monster won't attack playsound(monstertypes[mtype].painsound, &o); } } }; void stackmonster(monster *d, physent *o) { d->stacked = o; d->stackpos = o->o; } int nummonsters(int tag, int state) { int n = 0; loopv(monsters) if(monsters[i]->tag==tag && (monsters[i]->state==CS_ALIVE ? state!=1 : state>=1)) n++; return n; } ICOMMAND(nummonsters, "ii", (int *tag, int *state), intret(nummonsters(*tag, *state))); void preloadmonsters() { loopi(NUMMONSTERTYPES) preloadmodel(monstertypes[i].mdlname); for(int i = S_GRUNT1; i <= S_SLIMEBALL; i++) preloadsound(i); if(m_dmsp) preloadsound(S_V_FIGHT); if(m_classicsp) preloadsound(S_V_RESPAWNPOINT); } vector monsters; int nextmonster, spawnremain, numkilled, monstertotal, mtimestart, remain; void spawnmonster() // spawn a random monster according to freq distribution in DMSP { int n = rnd(TOTMFREQ), type; for(int i = 0; ; i++) if((n -= monstertypes[i].freq)<0) { type = i; break; } monsters.add(new monster(type, rnd(360), 0, M_SEARCH, 1000, 1)); } void clearmonsters() // called after map start or when toggling edit mode to reset/spawn all monsters to initial state { removetrackedparticles(); removetrackeddynlights(); loopv(monsters) delete monsters[i]; cleardynentcache(); monsters.shrink(0); numkilled = 0; monstertotal = 0; spawnremain = 0; remain = 0; monsterhurt = false; if(m_dmsp) { nextmonster = mtimestart = lastmillis+10000; monstertotal = spawnremain = skill*10; } else if(m_classicsp) { mtimestart = lastmillis; loopv(entities::ents) { extentity &e = *entities::ents[i]; if(e.type!=MONSTER) continue; monster *m = new monster(e.attr2, e.attr1, e.attr3, M_SLEEP, 100, 0); monsters.add(m); m->o = e.o; entinmap(m); updatedynentcache(m); monstertotal++; } } teleports.setsize(0); if(m_dmsp || m_classicsp) { loopv(entities::ents) if(entities::ents[i]->type==TELEPORT) teleports.add(i); } } void endsp(bool allkilled) { conoutf(CON_GAMEINFO, allkilled ? "\f2you have cleared the map!" : "\f2you reached the exit!"); monstertotal = 0; game::addmsg(N_FORCEINTERMISSION, "r"); } ICOMMAND(endsp, "", (), endsp(false)); void monsterkilled() { numkilled++; player1->frags = numkilled; remain = monstertotal-numkilled; if(remain>0 && remain<=5) conoutf(CON_GAMEINFO, "\f2only %d monster(s) remaining", remain); } void updatemonsters(int curtime) { if(m_dmsp && spawnremain && lastmillis>nextmonster) { if(spawnremain--==monstertotal) { conoutf(CON_GAMEINFO, "\f2The invasion has begun!"); playsound(S_V_FIGHT); } nextmonster = lastmillis+1000; spawnmonster(); } if(killsendsp && monstertotal && !spawnremain && numkilled==monstertotal) endsp(true); bool monsterwashurt = monsterhurt; loopv(monsters) { if(monsters[i]->state==CS_ALIVE) monsters[i]->monsteraction(curtime); else if(monsters[i]->state==CS_DEAD) { if(lastmillis-monsters[i]->lastpain<2000) { //monsters[i]->move = 0; monsters[i]->move = monsters[i]->strafe = 0; moveplayer(monsters[i], 1, true); } } } if(monsterwashurt) monsterhurt = false; } void rendermonsters() { loopv(monsters) { monster &m = *monsters[i]; if(m.state!=CS_DEAD || lastmillis-m.lastpain<10000) { modelattach vwep[2]; vwep[0] = modelattach("tag_weapon", monstertypes[m.mtype].vwepname, ANIM_VWEP_IDLE|ANIM_LOOP, 0); float fade = 1; if(m.state==CS_DEAD) fade -= clamp(float(lastmillis - (m.lastpain + 9000))/1000, 0.0f, 1.0f); renderclient(&m, monstertypes[m.mtype].mdlname, vwep, 0, m.monsterstate==M_ATTACKING ? -ANIM_ATTACK1 : 0, 300, m.lastaction, m.lastpain, fade); } } } void suicidemonster(monster *m) { m->monsterpain(400, player1); } void hitmonster(int damage, monster *m, fpsent *at, const vec &vel, int gun) { m->monsterpain(damage, at); } void spsummary(int accuracy) { conoutf(CON_GAMEINFO, "\f2--- single player time score: ---"); int pen, score = 0; pen = ((lastmillis-maptime)*100)/game::scaletime(1000); score += pen; if(pen) conoutf(CON_GAMEINFO, "\f2time taken: %d seconds (%d simulated seconds)", pen, (lastmillis-maptime)/1000); pen = player1->deaths*60; score += pen; if(pen) conoutf(CON_GAMEINFO, "\f2time penalty for %d deaths (1 minute each): %d seconds", player1->deaths, pen); pen = remain*10; score += pen; if(pen) conoutf(CON_GAMEINFO, "\f2time penalty for %d monsters remaining (10 seconds each): %d seconds", remain, pen); pen = (10-skill)*20; score += pen; if(pen) conoutf(CON_GAMEINFO, "\f2time penalty for lower skill level (20 seconds each): %d seconds", pen); pen = 100-accuracy; score += pen; if(pen) conoutf(CON_GAMEINFO, "\f2time penalty for missed shots (1 second each %%): %d seconds", pen); defformatstring(aname)("bestscore_%s", getclientmap()); const char *bestsc = getalias(aname); int bestscore = *bestsc ? parseint(bestsc) : score; if(scorestate != CS_DEAD && !intermission; } float weapmindist(int weap) { return max(int(guns[weap].exprad), 2); } float weapmaxdist(int weap) { return guns[weap].range + 4; } bool weaprange(fpsent *d, int weap, float dist) { float mindist = weapmindist(weap), maxdist = weapmaxdist(weap); return dist >= mindist*mindist && dist <= maxdist*maxdist; } bool targetable(fpsent *d, fpsent *e) { if(d == e || !canmove(d)) return false; return e->state == CS_ALIVE && !isteam(d->team, e->team); } bool getsight(vec &o, float yaw, float pitch, vec &q, vec &v, float mdist, float fovx, float fovy) { float dist = o.dist(q); if(dist <= mdist) { float x = fmod(fabs(asin((q.z-o.z)/dist)/RAD-pitch), 360); float y = fmod(fabs(-atan2(q.x-o.x, q.y-o.y)/RAD-yaw), 360); if(min(x, 360-x) <= fovx && min(y, 360-y) <= fovy) return raycubelos(o, q, v); } return false; } bool cansee(fpsent *d, vec &x, vec &y, vec &targ) { aistate &b = d->ai->getstate(); if(canmove(d) && b.type != AI_S_WAIT) return getsight(x, d->yaw, d->pitch, y, targ, d->ai->views[2], d->ai->views[0], d->ai->views[1]); return false; } bool canshoot(fpsent *d, fpsent *e) { if(weaprange(d, d->gunselect, e->o.squaredist(d->o)) && targetable(d, e)) return d->ammo[d->gunselect] > 0 && lastmillis - d->lastaction >= d->gunwait; return false; } bool canshoot(fpsent *d) { return !d->ai->becareful && d->ammo[d->gunselect] > 0 && lastmillis - d->lastaction >= d->gunwait; } bool hastarget(fpsent *d, aistate &b, fpsent *e, float yaw, float pitch, float dist) { // add margins of error if(weaprange(d, d->gunselect, dist) || (d->skill <= 100 && !rnd(d->skill))) { if(d->gunselect == GUN_FIST) return true; float skew = clamp(float(lastmillis-d->ai->enemymillis)/float((d->skill*guns[d->gunselect].attackdelay/200.f)), 0.f, guns[d->gunselect].projspeed ? 0.25f : 1e16f), offy = yaw-d->yaw, offp = pitch-d->pitch; if(offy > 180) offy -= 360; else if(offy < -180) offy += 360; if(fabs(offy) <= d->ai->views[0]*skew && fabs(offp) <= d->ai->views[1]*skew) return true; } return false; } vec getaimpos(fpsent *d, fpsent *e) { vec o = e->o; if(d->gunselect == GUN_RL) o.z += (e->aboveeye*0.2f)-(0.8f*d->eyeheight); else if(d->gunselect != GUN_GL) o.z += (e->aboveeye-e->eyeheight)*0.5f; if(d->skill <= 100) { if(lastmillis >= d->ai->lastaimrnd) { const int aiskew[NUMGUNS] = { 1, 10, 50, 5, 20, 1, 100, 10, 10, 10, 1, 1 }; #define rndaioffset(r) ((rnd(int(r*aiskew[d->gunselect]*2)+1)-(r*aiskew[d->gunselect]))*(1.f/float(max(d->skill, 1)))) loopk(3) d->ai->aimrnd[k] = rndaioffset(e->radius); int dur = (d->skill+10)*10; d->ai->lastaimrnd = lastmillis+dur+rnd(dur); } loopk(3) o[k] += d->ai->aimrnd[k]; } return o; } void create(fpsent *d) { if(!d->ai) d->ai = new aiinfo; } void destroy(fpsent *d) { if(d->ai) DELETEP(d->ai); } void init(fpsent *d, int at, int ocn, int sk, int bn, int pm, const char *name, const char *team) { loadwaypoints(); fpsent *o = newclient(ocn); d->aitype = at; bool resetthisguy = false; if(!d->name[0]) { if(aidebug) conoutf("%s assigned to %s at skill %d", colorname(d, name), o ? colorname(o) : "?", sk); else conoutf("\f0join:\f7 %s", colorname(d, name)); resetthisguy = true; } else { if(d->ownernum != ocn) { if(aidebug) conoutf("%s reassigned to %s", colorname(d, name), o ? colorname(o) : "?"); resetthisguy = true; } if(d->skill != sk && aidebug) conoutf("%s changed skill to %d", colorname(d, name), sk); } copystring(d->name, name, MAXNAMELEN+1); copystring(d->team, team, MAXTEAMLEN+1); d->ownernum = ocn; d->skill = sk; d->playermodel = chooserandomplayermodel(pm); if(resetthisguy) removeweapons(d); if(d->ownernum >= 0 && player1->clientnum == d->ownernum) { create(d); if(d->ai) { d->ai->views[0] = viewfieldx(d->skill); d->ai->views[1] = viewfieldy(d->skill); d->ai->views[2] = viewdist(d->skill); } } else if(d->ai) destroy(d); } void update() { if(intermission) { loopv(players) if(players[i]->ai) players[i]->stopmoving(); } else // fixed rate logic done out-of-sequence at 1 frame per second for each ai { if(totalmillis-updatemillis > 1000) { avoid(); forcegun = multiplayer(false) ? -1 : aiforcegun; updatemillis = totalmillis; } if(!iteration && totalmillis-itermillis > 1000) { iteration = 1; itermillis = totalmillis; } int count = 0; loopv(players) if(players[i]->ai) think(players[i], ++count == iteration ? true : false); if(++iteration > count) iteration = 0; } } bool checkothers(vector &targets, fpsent *d, int state, int targtype, int target, bool teams, int *members) { // checks the states of other ai for a match targets.setsize(0); loopv(players) { fpsent *e = players[i]; if(targets.find(e->clientnum) >= 0) continue; if(teams && d && !isteam(d->team, e->team)) continue; if(members) (*members)++; if(e == d || !e->ai || e->state != CS_ALIVE) continue; aistate &b = e->ai->getstate(); if(state >= 0 && b.type != state) continue; if(target >= 0 && b.target != target) continue; if(targtype >=0 && b.targtype != targtype) continue; targets.add(e->clientnum); } return !targets.empty(); } bool makeroute(fpsent *d, aistate &b, int node, bool changed, int retries) { if(!iswaypoint(d->lastnode)) return false; if(changed && d->ai->route.length() > 1 && d->ai->route[0] == node) return true; if(route(d, d->lastnode, node, d->ai->route, obstacles, retries)) { b.override = false; return true; } // retry fails: 0 = first attempt, 1 = try ignoring obstacles, 2 = try ignoring prevnodes too if(retries <= 1) return makeroute(d, b, node, false, retries+1); return false; } bool makeroute(fpsent *d, aistate &b, const vec &pos, bool changed, int retries) { int node = closestwaypoint(pos, SIGHTMIN, true); return makeroute(d, b, node, changed, retries); } bool randomnode(fpsent *d, aistate &b, const vec &pos, float guard, float wander) { static vector candidates; candidates.setsize(0); findwaypointswithin(pos, guard, wander, candidates); while(!candidates.empty()) { int w = rnd(candidates.length()), n = candidates.removeunordered(w); if(n != d->lastnode && !d->ai->hasprevnode(n) && !obstacles.find(n, d) && makeroute(d, b, n)) return true; } return false; } bool randomnode(fpsent *d, aistate &b, float guard, float wander) { return randomnode(d, b, d->feetpos(), guard, wander); } bool badhealth(fpsent *d) { if(d->skill <= 100) return d->health <= (111-d->skill)/4; return false; } bool enemy(fpsent *d, aistate &b, const vec &pos, float guard = SIGHTMIN, int pursue = 0) { fpsent *t = NULL; vec dp = d->headpos(); float mindist = guard*guard, bestdist = 1e16f; loopv(players) { fpsent *e = players[i]; if(e == d || !targetable(d, e)) continue; vec ep = getaimpos(d, e); float dist = ep.squaredist(dp); if(dist < bestdist && (cansee(d, dp, ep) || dist <= mindist)) { t = e; bestdist = dist; } } if(t && violence(d, b, t, pursue)) return true; return false; } bool patrol(fpsent *d, aistate &b, const vec &pos, float guard, float wander, int walk, bool retry) { vec feet = d->feetpos(); if(walk == 2 || b.override || (walk && feet.squaredist(pos) <= guard*guard) || !makeroute(d, b, pos)) { // run away and back to keep ourselves busy if(!b.override && randomnode(d, b, pos, guard, wander)) { b.override = true; return true; } else if(d->ai->route.empty()) { if(!retry) { b.override = false; return patrol(d, b, pos, guard, wander, walk, true); } b.override = false; return false; } } b.override = false; return true; } bool defend(fpsent *d, aistate &b, const vec &pos, float guard, float wander, int walk) { bool hasenemy = enemy(d, b, pos, wander, d->gunselect == GUN_FIST ? 1 : 0); if(!walk) { if(d->feetpos().squaredist(pos) <= guard*guard) { b.idle = hasenemy ? 2 : 1; return true; } walk++; } return patrol(d, b, pos, guard, wander, walk); } bool violence(fpsent *d, aistate &b, fpsent *e, int pursue) { if(e && targetable(d, e)) { if(pursue) { if((b.targtype != AI_T_AFFINITY || !(pursue%2)) && makeroute(d, b, e->lastnode)) d->ai->switchstate(b, AI_S_PURSUE, AI_T_PLAYER, e->clientnum); else if(pursue >= 3) return false; // can't pursue } if(d->ai->enemy != e->clientnum) { d->ai->enemyseen = d->ai->enemymillis = lastmillis; d->ai->enemy = e->clientnum; } return true; } return false; } bool target(fpsent *d, aistate &b, int pursue = 0, bool force = false, float mindist = 0.f) { static vector hastried; hastried.setsize(0); vec dp = d->headpos(); while(true) { float dist = 1e16f; fpsent *t = NULL; loopv(players) { fpsent *e = players[i]; if(e == d || hastried.find(e) >= 0 || !targetable(d, e)) continue; vec ep = getaimpos(d, e); float v = ep.squaredist(dp); if((!t || v < dist) && (mindist <= 0 || v <= mindist) && (force || cansee(d, dp, ep))) { t = e; dist = v; } } if(t) { if(violence(d, b, t, pursue)) return true; hastried.add(t); } else break; } return false; } int isgoodammo(int gun) { return gun >= GUN_SG && gun <= GUN_GL; } bool hasgoodammo(fpsent *d) { static const int goodguns[] = { GUN_CG, GUN_RL, GUN_SG, GUN_RIFLE }; loopi(sizeof(goodguns)/sizeof(goodguns[0])) if(d->hasammo(goodguns[0])) return true; if(d->ammo[GUN_GL] > 5) return true; return false; } void assist(fpsent *d, aistate &b, vector &interests, bool all, bool force) { loopv(players) { fpsent *e = players[i]; if(e == d || (!all && e->aitype != AI_NONE) || !isteam(d->team, e->team)) continue; interest &n = interests.add(); n.state = AI_S_DEFEND; n.node = e->lastnode; n.target = e->clientnum; n.targtype = AI_T_PLAYER; n.score = e->o.squaredist(d->o)/(hasgoodammo(d) ? 1e8f : (force ? 1e4f : 1e2f)); } } static void tryitem(fpsent *d, extentity &e, int id, aistate &b, vector &interests, bool force = false) { float score = 0; switch(e.type) { case I_HEALTH: if(d->health < min(d->skill, 75)) score = 1e3f; break; case I_QUAD: score = 1e3f; break; case I_BOOST: score = 1e2f; break; case I_GREENARMOUR: case I_YELLOWARMOUR: { int atype = A_GREEN + e.type - I_GREENARMOUR; if(atype > d->armourtype) score = atype == A_YELLOW ? 1e2f : 1e1f; else if(d->armour < 50) score = 1e1f; break; } default: { if(e.type >= I_SHELLS && e.type <= I_CARTRIDGES && !d->hasmaxammo(e.type)) { int gun = e.type - I_SHELLS + GUN_SG; // go get a weapon upgrade if(gun == d->ai->weappref) score = 1e8f; else if(isgoodammo(gun)) score = hasgoodammo(d) ? 1e2f : 1e4f; } break; } } if(score != 0) { interest &n = interests.add(); n.state = AI_S_INTEREST; n.node = closestwaypoint(e.o, SIGHTMIN, true); n.target = id; n.targtype = AI_T_ENTITY; n.score = d->feetpos().squaredist(e.o)/(force ? -1 : score); } } void items(fpsent *d, aistate &b, vector &interests, bool force = false) { loopv(entities::ents) { extentity &e = *(extentity *)entities::ents[i]; if(!e.spawned || !d->canpickup(e.type)) continue; tryitem(d, e, i, b, interests, force); } } static vector targets; bool parseinterests(fpsent *d, aistate &b, vector &interests, bool override, bool ignore) { while(!interests.empty()) { int q = interests.length()-1; loopi(interests.length()-1) if(interests[i].score < interests[q].score) q = i; interest n = interests.removeunordered(q); bool proceed = true; if(!ignore) switch(n.state) { case AI_S_DEFEND: // don't get into herds { int members = 0; proceed = !checkothers(targets, d, n.state, n.targtype, n.target, true, &members) && members > 1; break; } default: break; } if(proceed && makeroute(d, b, n.node)) { d->ai->switchstate(b, n.state, n.targtype, n.target); return true; } } return false; } bool find(fpsent *d, aistate &b, bool override = false) { static vector interests; interests.setsize(0); if(!m_noitems) { if((!m_noammo && !hasgoodammo(d)) || d->health < min(d->skill - 15, 75)) items(d, b, interests); else { static vector nearby; nearby.setsize(0); findents(I_SHELLS, I_QUAD, false, d->feetpos(), vec(32, 32, 24), nearby); loopv(nearby) { int id = nearby[i]; extentity &e = *(extentity *)entities::ents[id]; if(d->canpickup(e.type)) tryitem(d, e, id, b, interests); } } } if(cmode) cmode->aifind(d, b, interests); if(m_teammode) assist(d, b, interests); return parseinterests(d, b, interests, override); } bool findassist(fpsent *d, aistate &b, bool override = false) { static vector interests; interests.setsize(0); assist(d, b, interests); while(!interests.empty()) { int q = interests.length()-1; loopi(interests.length()-1) if(interests[i].score < interests[q].score) q = i; interest n = interests.removeunordered(q); bool proceed = true; switch(n.state) { case AI_S_DEFEND: // don't get into herds { int members = 0; proceed = !checkothers(targets, d, n.state, n.targtype, n.target, true, &members) && members > 1; break; } default: break; } if(proceed && makeroute(d, b, n.node)) { d->ai->switchstate(b, n.state, n.targtype, n.target); return true; } } return false; } void damaged(fpsent *d, fpsent *e) { if(d->ai && canmove(d) && targetable(d, e)) // see if this ai is interested in a grudge { aistate &b = d->ai->getstate(); if(violence(d, b, e, d->gunselect == GUN_FIST ? 1 : 0)) return; } if(checkothers(targets, d, AI_S_DEFEND, AI_T_PLAYER, d->clientnum, true)) { loopv(targets) { fpsent *t = getclient(targets[i]); if(!t->ai || !canmove(t) || !targetable(t, e)) continue; aistate &c = t->ai->getstate(); if(violence(t, c, e, d->gunselect == GUN_FIST ? 1 : 0)) return; } } } void findorientation(vec &o, float yaw, float pitch, vec &pos) { vec dir; vecfromyawpitch(yaw, pitch, 1, 0, dir); if(raycubepos(o, dir, pos, 0, RAY_CLIPMAT|RAY_SKIPFIRST) == -1) pos = dir.mul(2*getworldsize()).add(o); //otherwise 3dgui won't work when outside of map } void setup(fpsent *d) { d->ai->clearsetup(); d->ai->reset(true); d->ai->lastrun = lastmillis; if(m_insta) d->ai->weappref = GUN_RIFLE; else { if(forcegun >= 0 && forcegun < NUMGUNS) d->ai->weappref = forcegun; else if(m_noammo) d->ai->weappref = -1; else d->ai->weappref = rnd(GUN_GL-GUN_SG+1)+GUN_SG; } vec dp = d->headpos(); findorientation(dp, d->yaw, d->pitch, d->ai->target); } void spawned(fpsent *d) { if(d->ai) setup(d); } void killed(fpsent *d, fpsent *e) { if(d->ai) d->ai->reset(); } void itemspawned(int ent) { if(entities::ents.inrange(ent) && entities::ents[ent]->type >= I_SHELLS && entities::ents[ent]->type <= I_QUAD) { loopv(players) if(players[i] && players[i]->ai && players[i]->aitype == AI_BOT && players[i]->canpickup(entities::ents[ent]->type)) { fpsent *d = players[i]; bool wantsitem = false; switch(entities::ents[ent]->type) { case I_BOOST: case I_HEALTH: wantsitem = badhealth(d); break; case I_GREENARMOUR: case I_YELLOWARMOUR: case I_QUAD: break; default: { itemstat &is = itemstats[entities::ents[ent]->type-I_SHELLS]; wantsitem = isgoodammo(is.info) && d->ammo[is.info] <= (d->ai->weappref == is.info ? is.add : is.add/2); break; } } if(wantsitem) { aistate &b = d->ai->getstate(); if(b.targtype == AI_T_AFFINITY) continue; if(b.type == AI_S_INTEREST && b.targtype == AI_T_ENTITY) { if(entities::ents.inrange(b.target)) { if(d->o.squaredist(entities::ents[ent]->o) < d->o.squaredist(entities::ents[b.target]->o)) d->ai->switchstate(b, AI_S_INTEREST, AI_T_ENTITY, ent); } continue; } d->ai->switchstate(b, AI_S_INTEREST, AI_T_ENTITY, ent); } } } } bool check(fpsent *d, aistate &b) { if(cmode && cmode->aicheck(d, b)) return true; return false; } int dowait(fpsent *d, aistate &b) { d->ai->clear(true); // ensure they're clean if(check(d, b) || find(d, b)) return 1; if(target(d, b, 4, false)) return 1; if(target(d, b, 4, true)) return 1; if(randomnode(d, b, SIGHTMIN, 1e16f)) { d->ai->switchstate(b, AI_S_INTEREST, AI_T_NODE, d->ai->route[0]); return 1; } return 0; // but don't pop the state } int dodefend(fpsent *d, aistate &b) { if(d->state == CS_ALIVE) { switch(b.targtype) { case AI_T_NODE: if(check(d, b)) return 1; if(iswaypoint(b.target)) return defend(d, b, waypoints[b.target].o) ? 1 : 0; break; case AI_T_ENTITY: if(check(d, b)) return 1; if(entities::ents.inrange(b.target)) return defend(d, b, entities::ents[b.target]->o) ? 1 : 0; break; case AI_T_AFFINITY: if(cmode) return cmode->aidefend(d, b) ? 1 : 0; break; case AI_T_PLAYER: { if(check(d, b)) return 1; fpsent *e = getclient(b.target); if(e && e->state == CS_ALIVE) return defend(d, b, e->feetpos()) ? 1 : 0; break; } default: break; } } return 0; } int dointerest(fpsent *d, aistate &b) { if(d->state != CS_ALIVE) return 0; switch(b.targtype) { case AI_T_NODE: // this is like a wait state without sitting still.. if(check(d, b) || find(d, b)) return 1; if(target(d, b, 4, true)) return 1; if(iswaypoint(b.target) && vec(waypoints[b.target].o).sub(d->feetpos()).magnitude() > CLOSEDIST) return makeroute(d, b, waypoints[b.target].o) ? 1 : 0; break; case AI_T_ENTITY: if(entities::ents.inrange(b.target)) { extentity &e = *(extentity *)entities::ents[b.target]; if(!e.spawned || e.type < I_SHELLS || e.type > I_CARTRIDGES || d->hasmaxammo(e.type)) return 0; //if(d->feetpos().squaredist(e.o) <= CLOSEDIST*CLOSEDIST) //{ // b.idle = 1; // return true; //} return makeroute(d, b, e.o) ? 1 : 0; } break; } return 0; } int dopursue(fpsent *d, aistate &b) { if(d->state == CS_ALIVE) { switch(b.targtype) { case AI_T_NODE: { if(check(d, b)) return 1; if(iswaypoint(b.target)) return defend(d, b, waypoints[b.target].o) ? 1 : 0; break; } case AI_T_AFFINITY: { if(cmode) return cmode->aipursue(d, b) ? 1 : 0; break; } case AI_T_PLAYER: { //if(check(d, b)) return 1; fpsent *e = getclient(b.target); if(e && e->state == CS_ALIVE) { float guard = SIGHTMIN, wander = guns[d->gunselect].range; if(d->gunselect == GUN_FIST) guard = 0.f; return patrol(d, b, e->feetpos(), guard, wander) ? 1 : 0; } break; } default: break; } } return 0; } int closenode(fpsent *d) { vec pos = d->feetpos(); int node1 = -1, node2 = -1; float mindist1 = CLOSEDIST*CLOSEDIST, mindist2 = CLOSEDIST*CLOSEDIST; loopv(d->ai->route) if(iswaypoint(d->ai->route[i])) { vec epos = waypoints[d->ai->route[i]].o; float dist = epos.squaredist(pos); if(dist > FARDIST*FARDIST) continue; int entid = obstacles.remap(d, d->ai->route[i], epos); if(entid >= 0) { if(entid != i) dist = epos.squaredist(pos); if(dist < mindist1) { node1 = i; mindist1 = dist; } } else if(dist < mindist2) { node2 = i; mindist2 = dist; } } return node1 >= 0 ? node1 : node2; } int wpspot(fpsent *d, int n, bool check = false) { if(iswaypoint(n)) loopk(2) { vec epos = waypoints[n].o; int entid = obstacles.remap(d, n, epos, k!=0); if(iswaypoint(entid)) { d->ai->spot = epos; d->ai->targnode = entid; return !check || d->feetpos().squaredist(epos) > MINWPDIST*MINWPDIST ? 1 : 2; } } return 0; } int randomlink(fpsent *d, int n) { if(iswaypoint(n) && waypoints[n].haslinks()) { waypoint &w = waypoints[n]; static vector linkmap; linkmap.setsize(0); loopi(MAXWAYPOINTLINKS) { if(!w.links[i]) break; if(iswaypoint(w.links[i]) && !d->ai->hasprevnode(w.links[i]) && d->ai->route.find(w.links[i]) < 0) linkmap.add(w.links[i]); } if(!linkmap.empty()) return linkmap[rnd(linkmap.length())]; } return -1; } bool anynode(fpsent *d, aistate &b, int len = NUMPREVNODES) { if(iswaypoint(d->lastnode)) loopk(2) { d->ai->clear(k ? true : false); int n = randomlink(d, d->lastnode); if(wpspot(d, n)) { d->ai->route.add(n); d->ai->route.add(d->lastnode); loopi(len) { n = randomlink(d, n); if(iswaypoint(n)) d->ai->route.insert(0, n); else break; } return true; } } return false; } bool checkroute(fpsent *d, int n) { if(d->ai->route.empty() || !d->ai->route.inrange(n)) return false; int last = d->ai->lastcheck ? lastmillis-d->ai->lastcheck : 0; if(last < 500 || n < 3) return false; // route length is too short d->ai->lastcheck = lastmillis; int w = iswaypoint(d->lastnode) ? d->lastnode : d->ai->route[n], c = min(n-1, NUMPREVNODES); loopj(c) // check ahead to see if we need to go around something { int p = n-j-1, v = d->ai->route[p]; if(d->ai->hasprevnode(v) || obstacles.find(v, d)) // something is in the way, try to remap around it { int m = p-1; if(m < 3) return false; // route length is too short from this point loopirev(m) { int t = d->ai->route[i]; if(!d->ai->hasprevnode(t) && !obstacles.find(t, d)) { static vector remap; remap.setsize(0); if(route(d, w, t, remap, obstacles)) { // kill what we don't want and put the remap in while(d->ai->route.length() > i) d->ai->route.pop(); loopvk(remap) d->ai->route.add(remap[k]); return true; } return false; // we failed } } return false; } } return false; } bool hunt(fpsent *d, aistate &b) { if(!d->ai->route.empty()) { int n = closenode(d); if(d->ai->route.inrange(n) && checkroute(d, n)) n = closenode(d); if(d->ai->route.inrange(n)) { if(!n) { switch(wpspot(d, d->ai->route[n], true)) { case 2: d->ai->clear(false); case 1: return true; // not close enough to pop it yet case 0: default: break; } } else { while(d->ai->route.length() > n+1) d->ai->route.pop(); // waka-waka-waka-waka int m = n-1; // next, please! if(d->ai->route.inrange(m) && wpspot(d, d->ai->route[m])) return true; } } } b.override = false; return anynode(d, b); } void jumpto(fpsent *d, aistate &b, const vec &pos) { vec off = vec(pos).sub(d->feetpos()), dir(off.x, off.y, 0); bool sequenced = d->ai->blockseq || d->ai->targseq, offground = d->timeinair && !d->inwater, jump = !offground && lastmillis >= d->ai->jumpseed && (sequenced || off.z >= JUMPMIN || lastmillis >= d->ai->jumprand); if(jump) { vec old = d->o; d->o = vec(pos).add(vec(0, 0, d->eyeheight)); if(!collide(d, vec(0, 0, 1))) jump = false; d->o = old; if(jump) { float radius = 18*18; loopv(entities::ents) if(entities::ents[i]->type == JUMPPAD) { fpsentity &e = *(fpsentity *)entities::ents[i]; if(e.o.squaredist(pos) <= radius) { jump = false; break; } } } } if(jump) { d->jumping = true; int seed = (111-d->skill)*(d->inwater ? 3 : 5); d->ai->jumpseed = lastmillis+seed+rnd(seed); seed *= b.idle ? 50 : 25; d->ai->jumprand = lastmillis+seed+rnd(seed); } } void fixfullrange(float &yaw, float &pitch, float &roll, bool full) { if(full) { while(pitch < -180.0f) pitch += 360.0f; while(pitch >= 180.0f) pitch -= 360.0f; while(roll < -180.0f) roll += 360.0f; while(roll >= 180.0f) roll -= 360.0f; } else { if(pitch > 89.9f) pitch = 89.9f; if(pitch < -89.9f) pitch = -89.9f; if(roll > 89.9f) roll = 89.9f; if(roll < -89.9f) roll = -89.9f; } while(yaw < 0.0f) yaw += 360.0f; while(yaw >= 360.0f) yaw -= 360.0f; } void fixrange(float &yaw, float &pitch) { float r = 0.f; fixfullrange(yaw, pitch, r, false); } void getyawpitch(const vec &from, const vec &pos, float &yaw, float &pitch) { float dist = from.dist(pos); yaw = -atan2(pos.x-from.x, pos.y-from.y)/RAD; pitch = asin((pos.z-from.z)/dist)/RAD; } void scaleyawpitch(float &yaw, float &pitch, float targyaw, float targpitch, float frame, float scale) { if(yaw < targyaw-180.0f) yaw += 360.0f; if(yaw > targyaw+180.0f) yaw -= 360.0f; float offyaw = fabs(targyaw-yaw)*frame, offpitch = fabs(targpitch-pitch)*frame*scale; if(targyaw > yaw) { yaw += offyaw; if(targyaw < yaw) yaw = targyaw; } else if(targyaw < yaw) { yaw -= offyaw; if(targyaw > yaw) yaw = targyaw; } if(targpitch > pitch) { pitch += offpitch; if(targpitch < pitch) pitch = targpitch; } else if(targpitch < pitch) { pitch -= offpitch; if(targpitch > pitch) pitch = targpitch; } fixrange(yaw, pitch); } bool lockon(fpsent *d, fpsent *e, float maxdist) { if(d->gunselect == GUN_FIST && !d->blocked && !d->timeinair) { vec dir = vec(e->o).sub(d->o); float xydist = dir.x*dir.x+dir.y*dir.y, zdist = dir.z*dir.z, mdist = maxdist*maxdist, ddist = d->radius*d->radius+e->radius*e->radius; if(zdist <= ddist && xydist >= ddist+4 && xydist <= mdist+ddist) return true; } return false; } int process(fpsent *d, aistate &b) { int result = 0, stupify = d->skill <= 10+rnd(15) ? rnd(d->skill*1000) : 0, skmod = 101-d->skill; float frame = d->skill <= 100 ? float(lastmillis-d->ai->lastrun)/float(max(skmod,1)*10) : 1; vec dp = d->headpos(); bool idle = b.idle == 1 || (stupify && stupify <= skmod); d->ai->dontmove = false; if(idle) { d->ai->lastaction = d->ai->lasthunt = lastmillis; d->ai->dontmove = true; d->ai->spot = vec(0, 0, 0); } else if(hunt(d, b)) { getyawpitch(dp, vec(d->ai->spot).add(vec(0, 0, d->eyeheight)), d->ai->targyaw, d->ai->targpitch); d->ai->lasthunt = lastmillis; } else { idle = d->ai->dontmove = true; d->ai->spot = vec(0, 0, 0); } if(!d->ai->dontmove) jumpto(d, b, d->ai->spot); fpsent *e = getclient(d->ai->enemy); bool enemyok = e && targetable(d, e); if(!enemyok || d->skill >= 50) { fpsent *f = (fpsent *)intersectclosest(dp, d->ai->target, d); if(f) { if(targetable(d, f)) { if(!enemyok) violence(d, b, f, d->gunselect == GUN_FIST ? 1 : 0); enemyok = true; e = f; } else enemyok = false; } else if(!enemyok && target(d, b, d->gunselect == GUN_FIST ? 1 : 0, false, SIGHTMIN)) enemyok = (e = getclient(d->ai->enemy)) != NULL; } if(enemyok) { vec ep = getaimpos(d, e); float yaw, pitch; getyawpitch(dp, ep, yaw, pitch); fixrange(yaw, pitch); bool insight = cansee(d, dp, ep), hasseen = d->ai->enemyseen && lastmillis-d->ai->enemyseen <= (d->skill*10)+3000, quick = d->ai->enemyseen && lastmillis-d->ai->enemyseen <= (d->gunselect == GUN_CG ? 300 : skmod)+30; if(insight) d->ai->enemyseen = lastmillis; if(idle || insight || hasseen || quick) { float sskew = insight || d->skill > 100 ? 1.5f : (hasseen ? 1.f : 0.5f); if(insight && lockon(d, e, 16)) { d->ai->targyaw = yaw; d->ai->targpitch = pitch; if(!idle) frame *= 2; d->ai->becareful = false; } scaleyawpitch(d->yaw, d->pitch, yaw, pitch, frame, sskew); if(insight || quick) { if(canshoot(d, e) && hastarget(d, b, e, yaw, pitch, dp.squaredist(ep))) { d->attacking = true; d->ai->lastaction = lastmillis; result = 3; } else result = 2; } else result = 1; } else { if(!d->ai->enemyseen || lastmillis-d->ai->enemyseen > (d->skill*50)+3000) { d->ai->enemy = -1; d->ai->enemyseen = d->ai->enemymillis = 0; } enemyok = false; result = 0; } } else { if(!enemyok) { d->ai->enemy = -1; d->ai->enemyseen = d->ai->enemymillis = 0; } enemyok = false; result = 0; } fixrange(d->ai->targyaw, d->ai->targpitch); if(!result) scaleyawpitch(d->yaw, d->pitch, d->ai->targyaw, d->ai->targpitch, frame*0.25f, 1.f); if(d->ai->becareful && d->physstate == PHYS_FALL) { float offyaw, offpitch; vec v = vec(d->vel).normalize(); vectoyawpitch(v, offyaw, offpitch); offyaw -= d->yaw; offpitch -= d->pitch; if(fabs(offyaw)+fabs(offpitch) >= 135) d->ai->becareful = false; else if(d->ai->becareful) d->ai->dontmove = true; } else d->ai->becareful = false; if(d->ai->dontmove) d->move = d->strafe = 0; else { // our guys move one way.. but turn another?! :) const struct aimdir { int move, strafe, offset; } aimdirs[8] = { { 1, 0, 0 }, { 1, -1, 45 }, { 0, -1, 90 }, { -1, -1, 135 }, { -1, 0, 180 }, { -1, 1, 225 }, { 0, 1, 270 }, { 1, 1, 315 } }; float yaw = d->ai->targyaw-d->yaw; while(yaw < 0.0f) yaw += 360.0f; while(yaw >= 360.0f) yaw -= 360.0f; int r = clamp(((int)floor((yaw+22.5f)/45.0f))&7, 0, 7); const aimdir &ad = aimdirs[r]; d->move = ad.move; d->strafe = ad.strafe; } findorientation(dp, d->yaw, d->pitch, d->ai->target); return result; } bool hasrange(fpsent *d, fpsent *e, int weap) { if(!e) return true; if(targetable(d, e)) { vec ep = getaimpos(d, e); float dist = ep.squaredist(d->headpos()); if(weaprange(d, weap, dist)) return true; } return false; } bool request(fpsent *d, aistate &b) { fpsent *e = getclient(d->ai->enemy); if(!d->hasammo(d->gunselect) || !hasrange(d, e, d->gunselect) || (d->gunselect != d->ai->weappref && (!isgoodammo(d->gunselect) || d->hasammo(d->ai->weappref)))) { static const int gunprefs[] = { GUN_CG, GUN_RL, GUN_SG, GUN_RIFLE, GUN_GL, GUN_PISTOL, GUN_FIST }; int gun = -1; if(d->hasammo(d->ai->weappref) && hasrange(d, e, d->ai->weappref)) gun = d->ai->weappref; else { loopi(sizeof(gunprefs)/sizeof(gunprefs[0])) if(d->hasammo(gunprefs[i]) && hasrange(d, e, gunprefs[i])) { gun = gunprefs[i]; break; } } if(gun >= 0 && gun != d->gunselect) gunselect(gun, d); } return process(d, b) >= 2; } void timeouts(fpsent *d, aistate &b) { if(d->blocked) { d->ai->blocktime += lastmillis-d->ai->lastrun; if(d->ai->blocktime > (d->ai->blockseq+1)*1000) { d->ai->blockseq++; switch(d->ai->blockseq) { case 1: case 2: case 3: if(entities::ents.inrange(d->ai->targnode)) d->ai->addprevnode(d->ai->targnode); d->ai->clear(false); break; case 4: d->ai->reset(true); break; case 5: d->ai->reset(false); break; case 6: default: suicide(d); return; break; // this is our last resort.. } } } else d->ai->blocktime = d->ai->blockseq = 0; if(d->ai->targnode == d->ai->targlast) { d->ai->targtime += lastmillis-d->ai->lastrun; if(d->ai->targtime > (d->ai->targseq+1)*1000) { d->ai->targseq++; switch(d->ai->targseq) { case 1: case 2: case 3: if(entities::ents.inrange(d->ai->targnode)) d->ai->addprevnode(d->ai->targnode); d->ai->clear(false); break; case 4: d->ai->reset(true); break; case 5: d->ai->reset(false); break; case 6: default: suicide(d); return; break; // this is our last resort.. } } } else { d->ai->targtime = d->ai->targseq = 0; d->ai->targlast = d->ai->targnode; } if(d->ai->lasthunt) { int millis = lastmillis-d->ai->lasthunt; if(millis <= 1000) { d->ai->tryreset = false; d->ai->huntseq = 0; } else if(millis > (d->ai->huntseq+1)*1000) { d->ai->huntseq++; switch(d->ai->huntseq) { case 1: d->ai->reset(true); break; case 2: d->ai->reset(false); break; case 3: default: suicide(d); return; break; // this is our last resort.. } } } } void logic(fpsent *d, aistate &b, bool run) { bool allowmove = canmove(d) && b.type != AI_S_WAIT; if(d->state != CS_ALIVE || !allowmove) d->stopmoving(); if(d->state == CS_ALIVE) { if(allowmove) { if(!request(d, b)) target(d, b, d->gunselect == GUN_FIST ? 1 : 0, b.idle ? true : false); shoot(d, d->ai->target); } if(!intermission) { if(d->ragdoll) cleanragdoll(d); moveplayer(d, 10, true); if(allowmove && !b.idle) timeouts(d, b); if(d->quadmillis) entities::checkquad(curtime, d); entities::checkitems(d); if(cmode) cmode->checkitems(d); } } else if(d->state == CS_DEAD) { if(d->ragdoll) moveragdoll(d); else if(lastmillis-d->lastpain<2000) { d->move = d->strafe = 0; moveplayer(d, 10, false); } } d->attacking = d->jumping = false; } void avoid() { // guess as to the radius of ai and other critters relying on the avoid set for now float guessradius = player1->radius; obstacles.clear(); loopv(players) { dynent *d = players[i]; if(d->state != CS_ALIVE) continue; obstacles.avoidnear(d, d->o.z + d->aboveeye + 1, d->feetpos(), guessradius + d->radius); } extern avoidset wpavoid; obstacles.add(wpavoid); avoidweapons(obstacles, guessradius); } void think(fpsent *d, bool run) { // the state stack works like a chain of commands, certain commands simply replace each other // others spawn new commands to the stack the ai reads the top command from the stack and executes // it or pops the stack and goes back along the history until it finds a suitable command to execute bool cleannext = false; if(d->ai->state.empty()) d->ai->addstate(AI_S_WAIT); loopvrev(d->ai->state) { aistate &c = d->ai->state[i]; if(cleannext) { c.millis = lastmillis; c.override = false; cleannext = false; } if(d->state == CS_DEAD && d->respawned!=d->lifesequence && (!cmode || cmode->respawnwait(d) <= 0) && lastmillis - d->lastpain >= 500) { addmsg(N_TRYSPAWN, "rc", d); d->respawned = d->lifesequence; } else if(d->state == CS_ALIVE && run) { int result = 0; c.idle = 0; switch(c.type) { case AI_S_WAIT: result = dowait(d, c); break; case AI_S_DEFEND: result = dodefend(d, c); break; case AI_S_PURSUE: result = dopursue(d, c); break; case AI_S_INTEREST: result = dointerest(d, c); break; default: result = 0; break; } if(result <= 0) { if(c.type != AI_S_WAIT) { switch(result) { case 0: default: d->ai->removestate(i); cleannext = true; break; case -1: i = d->ai->state.length()-1; break; } continue; // shouldn't interfere } } } logic(d, c, run); break; } if(d->ai->trywipe) d->ai->wipe(); d->ai->lastrun = lastmillis; } void drawroute(fpsent *d, float amt = 1.f) { int last = -1; loopvrev(d->ai->route) { if(d->ai->route.inrange(last)) { int index = d->ai->route[i], prev = d->ai->route[last]; if(iswaypoint(index) && iswaypoint(prev)) { waypoint &e = waypoints[index], &f = waypoints[prev]; vec fr = f.o, dr = e.o; fr.z += amt; dr.z += amt; particle_flare(fr, dr, 1, PART_STREAK, 0xFFFFFF); } } last = i; } if(aidebug >= 5) { vec pos = d->feetpos(); if(d->ai->spot != vec(0, 0, 0)) particle_flare(pos, d->ai->spot, 1, PART_LIGHTNING, 0x00FFFF); if(iswaypoint(d->ai->targnode)) particle_flare(pos, waypoints[d->ai->targnode].o, 1, PART_LIGHTNING, 0xFF00FF); if(iswaypoint(d->lastnode)) particle_flare(pos, waypoints[d->lastnode].o, 1, PART_LIGHTNING, 0xFFFF00); loopi(NUMPREVNODES) if(iswaypoint(d->ai->prevnodes[i])) { particle_flare(pos, waypoints[d->ai->prevnodes[i]].o, 1, PART_LIGHTNING, 0x884400); pos = waypoints[d->ai->prevnodes[i]].o; } } } VAR(showwaypoints, 0, 0, 1); VAR(showwaypointsradius, 0, 200, 10000); const char *stnames[AI_S_MAX] = { "wait", "defend", "pursue", "interest" }, *sttypes[AI_T_MAX+1] = { "none", "node", "player", "affinity", "entity" }; void render() { if(aidebug > 1) { int total = 0, alive = 0; loopv(players) if(players[i]->ai) total++; loopv(players) if(players[i]->state == CS_ALIVE && players[i]->ai) { fpsent *d = players[i]; vec pos = d->abovehead(); pos.z += 3; alive++; if(aidebug >= 4) drawroute(d, 4.f*(float(alive)/float(total))); if(aidebug >= 3) { defformatstring(q)("node: %d route: %d (%d)", d->lastnode, !d->ai->route.empty() ? d->ai->route[0] : -1, d->ai->route.length() ); particle_textcopy(pos, q, PART_TEXT, 1); pos.z += 2; } bool top = true; loopvrev(d->ai->state) { aistate &b = d->ai->state[i]; defformatstring(s)("%s%s (%d ms) %s:%d", top ? "\fg" : "\fy", stnames[b.type], lastmillis-b.millis, sttypes[b.targtype+1], b.target ); particle_textcopy(pos, s, PART_TEXT, 1); pos.z += 2; if(top) { if(aidebug >= 3) top = false; else break; } } if(aidebug >= 3) { if(d->ai->weappref >= 0 && d->ai->weappref < NUMGUNS) { particle_textcopy(pos, guns[d->ai->weappref].name, PART_TEXT, 1); pos.z += 2; } fpsent *e = getclient(d->ai->enemy); if(e) { particle_textcopy(pos, colorname(e), PART_TEXT, 1); pos.z += 2; } } } if(aidebug >= 4) { int cur = 0; loopv(obstacles.obstacles) { const avoidset::obstacle &ob = obstacles.obstacles[i]; int next = cur + ob.numwaypoints; for(; cur < next; cur++) { int ent = obstacles.waypoints[cur]; if(iswaypoint(ent)) regular_particle_splash(PART_EDIT, 2, 40, waypoints[ent].o, 0xFF6600, 1.5f); } cur = next; } } } if(showwaypoints || aidebug >= 6) { vector close; int len = waypoints.length(); if(showwaypointsradius) { findwaypointswithin(camera1->o, 0, showwaypointsradius, close); len = close.length(); } loopi(len) { waypoint &w = waypoints[showwaypointsradius ? close[i] : i]; loopj(MAXWAYPOINTLINKS) { int link = w.links[j]; if(!link) break; particle_flare(w.o, waypoints[link].o, 1, PART_STREAK, 0x0000FF); } } } } } sauerbraten-0.0.20130203.dfsg/fpsgame/render.cpp0000644000175000017500000003772012067675530021026 0ustar vincentvincent#include "game.h" namespace game { vector bestplayers; vector bestteams; VARP(ragdoll, 0, 1, 1); VARP(ragdollmillis, 0, 10000, 300000); VARP(ragdollfade, 0, 1000, 300000); VARFP(playermodel, 0, 0, 4, changedplayermodel()); VARP(forceplayermodels, 0, 0, 1); VARP(hidedead, 0, 0, 1); vector ragdolls; void saveragdoll(fpsent *d) { if(!d->ragdoll || !ragdollmillis || (!ragdollfade && lastmillis > d->lastpain + ragdollmillis)) return; fpsent *r = new fpsent(*d); r->lastupdate = ragdollfade && lastmillis > d->lastpain + max(ragdollmillis - ragdollfade, 0) ? lastmillis - max(ragdollmillis - ragdollfade, 0) : d->lastpain; r->edit = NULL; r->ai = NULL; r->attackchan = r->idlechan = -1; if(d==player1) r->playermodel = playermodel; ragdolls.add(r); d->ragdoll = NULL; } void clearragdolls() { ragdolls.deletecontents(); } void moveragdolls() { loopv(ragdolls) { fpsent *d = ragdolls[i]; if(lastmillis > d->lastupdate + ragdollmillis) { delete ragdolls.remove(i--); continue; } moveragdoll(d); } } static const playermodelinfo playermodels[5] = { { "mrfixit", "mrfixit/blue", "mrfixit/red", "mrfixit/hudguns", NULL, "mrfixit/horns", { "mrfixit/armor/blue", "mrfixit/armor/green", "mrfixit/armor/yellow" }, "mrfixit", "mrfixit_blue", "mrfixit_red", true }, { "snoutx10k", "snoutx10k/blue", "snoutx10k/red", "snoutx10k/hudguns", NULL, "snoutx10k/wings", { "snoutx10k/armor/blue", "snoutx10k/armor/green", "snoutx10k/armor/yellow" }, "snoutx10k", "snoutx10k_blue", "snoutx10k_red", true }, //{ "ogro/green", "ogro/blue", "ogro/red", "mrfixit/hudguns", "ogro/vwep", NULL, { NULL, NULL, NULL }, "ogro", "ogro_blue", "ogro_red", false }, { "ogro2", "ogro2/blue", "ogro2/red", "mrfixit/hudguns", NULL, "ogro2/quad", { "ogro2/armor/blue", "ogro2/armor/green", "ogro2/armor/yellow" }, "ogro", "ogro_blue", "ogro_red", true }, { "inky", "inky/blue", "inky/red", "inky/hudguns", NULL, "inky/quad", { "inky/armor/blue", "inky/armor/green", "inky/armor/yellow" }, "inky", "inky_blue", "inky_red", true }, { "captaincannon", "captaincannon/blue", "captaincannon/red", "captaincannon/hudguns", NULL, "captaincannon/quad", { "captaincannon/armor/blue", "captaincannon/armor/green", "captaincannon/armor/yellow" }, "captaincannon", "captaincannon_blue", "captaincannon_red", true } }; int chooserandomplayermodel(int seed) { return (seed&0xFFFF)%(sizeof(playermodels)/sizeof(playermodels[0])); } const playermodelinfo *getplayermodelinfo(int n) { if(size_t(n) >= sizeof(playermodels)/sizeof(playermodels[0])) return NULL; return &playermodels[n]; } const playermodelinfo &getplayermodelinfo(fpsent *d) { const playermodelinfo *mdl = getplayermodelinfo(d==player1 || forceplayermodels ? playermodel : d->playermodel); if(!mdl) mdl = getplayermodelinfo(playermodel); return *mdl; } void changedplayermodel() { if(player1->clientnum < 0) player1->playermodel = playermodel; if(player1->ragdoll) cleanragdoll(player1); loopv(ragdolls) { fpsent *d = ragdolls[i]; if(!d->ragdoll) continue; if(!forceplayermodels) { const playermodelinfo *mdl = getplayermodelinfo(d->playermodel); if(mdl) continue; } cleanragdoll(d); } loopv(players) { fpsent *d = players[i]; if(d == player1 || !d->ragdoll) continue; if(!forceplayermodels) { const playermodelinfo *mdl = getplayermodelinfo(d->playermodel); if(mdl) continue; } cleanragdoll(d); } } void preloadplayermodel() { loopi(3) { const playermodelinfo *mdl = getplayermodelinfo(i); if(!mdl) break; if(i != playermodel && (!multiplayer(false) || forceplayermodels)) continue; if(m_teammode) { preloadmodel(mdl->blueteam); preloadmodel(mdl->redteam); } else preloadmodel(mdl->ffa); if(mdl->vwep) preloadmodel(mdl->vwep); if(mdl->quad) preloadmodel(mdl->quad); loopj(3) if(mdl->armour[j]) preloadmodel(mdl->armour[j]); } } VAR(testquad, 0, 0, 1); VAR(testarmour, 0, 0, 1); VAR(testteam, 0, 0, 3); void renderplayer(fpsent *d, const playermodelinfo &mdl, int team, float fade, bool mainpass) { int lastaction = d->lastaction, hold = mdl.vwep || d->gunselect==GUN_PISTOL ? 0 : (ANIM_HOLD1+d->gunselect)|ANIM_LOOP, attack = ANIM_ATTACK1+d->gunselect, delay = mdl.vwep ? 300 : guns[d->gunselect].attackdelay+50; if(intermission && d->state!=CS_DEAD) { lastaction = 0; hold = attack = ANIM_LOSE|ANIM_LOOP; delay = 0; if(m_teammode ? bestteams.htfind(d->team)>=0 : bestplayers.find(d)>=0) hold = attack = ANIM_WIN|ANIM_LOOP; } else if(d->state==CS_ALIVE && d->lasttaunt && lastmillis-d->lasttaunt<1000 && lastmillis-d->lastaction>delay) { lastaction = d->lasttaunt; hold = attack = ANIM_TAUNT; delay = 1000; } modelattach a[5]; static const char *vweps[] = {"vwep/fist", "vwep/shotg", "vwep/chaing", "vwep/rocket", "vwep/rifle", "vwep/gl", "vwep/pistol"}; int ai = 0; if((!mdl.vwep || d->gunselect!=GUN_FIST) && d->gunselect<=GUN_PISTOL) { int vanim = ANIM_VWEP_IDLE|ANIM_LOOP, vtime = 0; if(lastaction && d->lastattackgun==d->gunselect && lastmillis < lastaction + delay) { vanim = ANIM_VWEP_SHOOT; vtime = lastaction; } a[ai++] = modelattach("tag_weapon", mdl.vwep ? mdl.vwep : vweps[d->gunselect], vanim, vtime); } if(d->state==CS_ALIVE) { if((testquad || d->quadmillis) && mdl.quad) a[ai++] = modelattach("tag_powerup", mdl.quad, ANIM_POWERUP|ANIM_LOOP, 0); if(testarmour || d->armour) { int type = clamp(d->armourtype, (int)A_BLUE, (int)A_YELLOW); if(mdl.armour[type]) a[ai++] = modelattach("tag_shield", mdl.armour[type], ANIM_SHIELD|ANIM_LOOP, 0); } } if(mainpass) { d->muzzle = vec(-1, -1, -1); a[ai++] = modelattach("tag_muzzle", &d->muzzle); } const char *mdlname = mdl.ffa; switch(testteam ? testteam-1 : team) { case 1: mdlname = mdl.blueteam; break; case 2: mdlname = mdl.redteam; break; } renderclient(d, mdlname, a[0].tag ? a : NULL, hold, attack, delay, lastaction, intermission && d->state!=CS_DEAD ? 0 : d->lastpain, fade, ragdoll && mdl.ragdoll); #if 0 if(d->state!=CS_DEAD && d->quadmillis) { entitylight light; rendermodel(&light, "quadrings", ANIM_MAPMODEL|ANIM_LOOP, vec(d->o).sub(vec(0, 0, d->eyeheight/2)), 360*lastmillis/1000.0f, 0, MDL_DYNSHADOW | MDL_CULL_VFC | MDL_CULL_DIST); } #endif } VARP(teamskins, 0, 0, 1); void rendergame(bool mainpass) { if(mainpass) ai::render(); if(intermission) { bestteams.shrink(0); bestplayers.shrink(0); if(m_teammode) getbestteams(bestteams); else getbestplayers(bestplayers); } startmodelbatches(); fpsent *exclude = isthirdperson() ? NULL : followingplayer(); loopv(players) { fpsent *d = players[i]; if(d == player1 || d->state==CS_SPECTATOR || d->state==CS_SPAWNING || d->lifesequence < 0 || d == exclude || (d->state==CS_DEAD && hidedead)) continue; int team = 0; if(teamskins || m_teammode) team = isteam(player1->team, d->team) ? 1 : 2; renderplayer(d, getplayermodelinfo(d), team, 1, mainpass); copystring(d->info, colorname(d)); if(d->maxhealth>100) { defformatstring(sn)(" +%d", d->maxhealth-100); concatstring(d->info, sn); } if(d->state!=CS_DEAD) particle_text(d->abovehead(), d->info, PART_TEXT, 1, team ? (team==1 ? 0x6496FF : 0xFF4B19) : 0x1EC850, 2.0f); } loopv(ragdolls) { fpsent *d = ragdolls[i]; int team = 0; if(teamskins || m_teammode) team = isteam(player1->team, d->team) ? 1 : 2; float fade = 1.0f; if(ragdollmillis && ragdollfade) fade -= clamp(float(lastmillis - (d->lastupdate + max(ragdollmillis - ragdollfade, 0)))/min(ragdollmillis, ragdollfade), 0.0f, 1.0f); renderplayer(d, getplayermodelinfo(d), team, fade, mainpass); } if(isthirdperson() && !followingplayer() && (player1->state!=CS_DEAD || !hidedead)) renderplayer(player1, getplayermodelinfo(player1), teamskins || m_teammode ? 1 : 0, 1, mainpass); rendermonsters(); rendermovables(); entities::renderentities(); renderbouncers(); renderprojectiles(); if(cmode) cmode->rendergame(); endmodelbatches(); } VARP(hudgun, 0, 1, 1); VARP(hudgunsway, 0, 1, 1); VARP(teamhudguns, 0, 1, 1); VARP(chainsawhudgun, 0, 1, 1); VAR(testhudgun, 0, 0, 1); FVAR(swaystep, 1, 35.0f, 100); FVAR(swayside, 0, 0.04f, 1); FVAR(swayup, -1, 0.05f, 1); float swayfade = 0, swayspeed = 0, swaydist = 0; vec swaydir(0, 0, 0); void swayhudgun(int curtime) { fpsent *d = hudplayer(); if(d->state != CS_SPECTATOR) { if(d->physstate >= PHYS_SLOPE) { swayspeed = min(sqrtf(d->vel.x*d->vel.x + d->vel.y*d->vel.y), d->maxspeed); swaydist += swayspeed*curtime/1000.0f; swaydist = fmod(swaydist, 2*swaystep); swayfade = 1; } else if(swayfade > 0) { swaydist += swayspeed*swayfade*curtime/1000.0f; swaydist = fmod(swaydist, 2*swaystep); swayfade -= 0.5f*(curtime*d->maxspeed)/(swaystep*1000.0f); } float k = pow(0.7f, curtime/10.0f); swaydir.mul(k); vec vel(d->vel); vel.add(d->falling); swaydir.add(vec(vel).mul((1-k)/(15*max(vel.magnitude(), d->maxspeed)))); } } struct hudent : dynent { hudent() { type = ENT_CAMERA; } } guninterp; SVARP(hudgunsdir, ""); void drawhudmodel(fpsent *d, int anim, float speed = 0, int base = 0) { if(d->gunselect>GUN_PISTOL) return; vec sway; vecfromyawpitch(d->yaw, 0, 0, 1, sway); float steps = swaydist/swaystep*M_PI; sway.mul(swayside*cosf(steps)); sway.z = swayup*(fabs(sinf(steps)) - 1); sway.add(swaydir).add(d->o); if(!hudgunsway) sway = d->o; #if 0 if(player1->state!=CS_DEAD && player1->quadmillis) { float t = 0.5f + 0.5f*sinf(2*M_PI*lastmillis/1000.0f); color.y = color.y*(1-t) + t; } #endif const playermodelinfo &mdl = getplayermodelinfo(d); defformatstring(gunname)("%s/%s", hudgunsdir[0] ? hudgunsdir : mdl.hudguns, guns[d->gunselect].file); if((m_teammode || teamskins) && teamhudguns) concatstring(gunname, d==player1 || isteam(d->team, player1->team) ? "/blue" : "/red"); else if(testteam > 1) concatstring(gunname, testteam==2 ? "/blue" : "/red"); modelattach a[2]; d->muzzle = vec(-1, -1, -1); a[0] = modelattach("tag_muzzle", &d->muzzle); dynent *interp = NULL; if(d->gunselect==GUN_FIST && chainsawhudgun) { anim |= ANIM_LOOP; base = 0; interp = &guninterp; } rendermodel(NULL, gunname, anim, sway, testhudgun ? 0 : d->yaw+90, testhudgun ? 0 : d->pitch, MDL_LIGHT|MDL_HUD, interp, a, base, (int)ceil(speed)); if(d->muzzle.x >= 0) d->muzzle = calcavatarpos(d->muzzle, 12); } void drawhudgun() { fpsent *d = hudplayer(); if(d->state==CS_SPECTATOR || d->state==CS_EDITING || !hudgun || editmode) { d->muzzle = player1->muzzle = vec(-1, -1, -1); return; } int rtime = guns[d->gunselect].attackdelay; if(d->lastaction && d->lastattackgun==d->gunselect && lastmillis-d->lastactionlastaction); } else { drawhudmodel(d, ANIM_GUN_IDLE|ANIM_LOOP); } } void renderavatar() { drawhudgun(); } void renderplayerpreview(int model, int team, int weap) { static fpsent *previewent = NULL; if(!previewent) { previewent = new fpsent; previewent->o = vec(0, 0.9f*(previewent->eyeheight + previewent->aboveeye), previewent->eyeheight - (previewent->eyeheight + previewent->aboveeye)/2); previewent->light.color = vec(1, 1, 1); previewent->light.dir = vec(0, -1, 2).normalize(); loopi(GUN_PISTOL-GUN_FIST) previewent->ammo[GUN_FIST+1+i] = 1; } previewent->gunselect = clamp(weap, int(GUN_FIST), int(GUN_PISTOL)); previewent->yaw = fmod(lastmillis/10000.0f*360.0f, 360.0f); previewent->light.millis = -1; const playermodelinfo *mdlinfo = getplayermodelinfo(model); if(!mdlinfo) return; renderplayer(previewent, *mdlinfo, team >= 0 && team <= 2 ? team : 0, 1, false); } vec hudgunorigin(int gun, const vec &from, const vec &to, fpsent *d) { if(d->muzzle.x >= 0) return d->muzzle; vec offset(from); if(d!=hudplayer() || isthirdperson()) { vec front, right; vecfromyawpitch(d->yaw, d->pitch, 1, 0, front); offset.add(front.mul(d->radius)); if(d->type!=ENT_AI) { offset.z += (d->aboveeye + d->eyeheight)*0.75f - d->eyeheight; vecfromyawpitch(d->yaw, 0, 0, -1, right); offset.add(right.mul(0.5f*d->radius)); offset.add(front); } return offset; } offset.add(vec(to).sub(from).normalize().mul(2)); if(hudgun) { offset.sub(vec(camup).mul(1.0f)); offset.add(vec(camright).mul(0.8f)); } else offset.sub(vec(camup).mul(0.8f)); return offset; } void preloadweapons() { const playermodelinfo &mdl = getplayermodelinfo(player1); loopi(NUMGUNS) { const char *file = guns[i].file; if(!file) continue; string fname; if((m_teammode || teamskins) && teamhudguns) { formatstring(fname)("%s/%s/blue", hudgunsdir[0] ? hudgunsdir : mdl.hudguns, file); preloadmodel(fname); } else { formatstring(fname)("%s/%s", hudgunsdir[0] ? hudgunsdir : mdl.hudguns, file); preloadmodel(fname); } formatstring(fname)("vwep/%s", file); preloadmodel(fname); } } void preloadsounds() { for(int i = S_JUMP; i <= S_SPLASH2; i++) preloadsound(i); for(int i = S_JUMPPAD; i <= S_PISTOL; i++) preloadsound(i); for(int i = S_V_BOOST; i <= S_V_QUAD10; i++) preloadsound(i); for(int i = S_BURN; i <= S_HIT; i++) preloadsound(i); } void preload() { if(hudgun) preloadweapons(); preloadbouncers(); preloadplayermodel(); preloadsounds(); entities::preloadentities(); if(m_sp) preloadmonsters(); } } sauerbraten-0.0.20130203.dfsg/engine/0000755000175000017500000000000012100771035016636 5ustar vincentvincentsauerbraten-0.0.20130203.dfsg/engine/blob.cpp0000644000175000017500000004740612072404330020272 0ustar vincentvincent#include "engine.h" VARNP(blobs, showblobs, 0, 1, 1); VARFP(blobintensity, 0, 60, 100, resetblobs()); VARFP(blobheight, 1, 32, 128, resetblobs()); VARFP(blobfadelow, 1, 8, 32, resetblobs()); VARFP(blobfadehigh, 1, 8, 32, resetblobs()); VARFP(blobmargin, 0, 1, 16, resetblobs()); VAR(dbgblob, 0, 0, 1); struct blobinfo { vec o; float radius; int millis; uint startindex, endindex; ushort startvert, endvert; }; struct blobvert { vec pos; float u, v; bvec color; uchar alpha; }; struct blobrenderer { const char *texname; Texture *tex; blobinfo **cache; int cachesize; blobinfo *blobs; int maxblobs, startblob, endblob; blobvert *verts; int maxverts, startvert, endvert, availverts; ushort *indexes; int maxindexes, startindex, endindex, availindexes; blobinfo *lastblob, *flushblob; vec blobmin, blobmax; ivec bborigin, bbsize; float blobalphalow, blobalphahigh; uchar blobalpha; blobrenderer(const char *texname) : texname(texname), tex(NULL), cache(NULL), cachesize(0), blobs(NULL), maxblobs(0), startblob(0), endblob(0), verts(NULL), maxverts(0), startvert(0), endvert(0), availverts(0), indexes(NULL), maxindexes(0), startindex(0), endindex(0), availindexes(0), lastblob(NULL) {} void init(int tris) { if(cache) { DELETEA(cache); cachesize = 0; } if(blobs) { DELETEA(blobs); maxblobs = startblob = endblob = 0; } if(verts) { DELETEA(verts); maxverts = startvert = endvert = availverts = 0; } if(indexes) { DELETEA(indexes); maxindexes = startindex = endindex = availindexes = 0; } if(!tris) return; tex = textureload(texname, 3); cachesize = tris/2; cache = new blobinfo *[cachesize]; memset(cache, 0, cachesize * sizeof(blobinfo *)); maxblobs = tris/2; blobs = new blobinfo[maxblobs]; memset(blobs, 0, maxblobs * sizeof(blobinfo)); maxindexes = tris*3 + 3; availindexes = maxindexes - 3; indexes = new ushort[maxindexes]; maxverts = min(tris*3/2 + 1, (1<<16)-1); availverts = maxverts - 1; verts = new blobvert[maxverts]; } bool freeblob() { blobinfo &b = blobs[startblob]; if(&b == lastblob) return false; startblob++; if(startblob >= maxblobs) startblob = 0; startvert = b.endvert; if(startvert>=maxverts) startvert = 0; availverts += b.endvert - b.startvert; startindex = b.endindex; if(startindex>=maxindexes) startindex = 0; availindexes += b.endindex - b.startindex; b.millis = 0; return true; } blobinfo &newblob(const vec &o, float radius) { blobinfo &b = blobs[endblob]; int next = endblob + 1; if(next>=maxblobs) next = 0; if(next==startblob) { lastblob = &b; freeblob(); } endblob = next; b.o = o; b.radius = radius; b.millis = totalmillis; b.startindex = b.endindex = endindex; b.startvert = b.endvert = endvert; lastblob = &b; return b; } void clearblobs() { startblob = endblob = 0; startvert = endvert = 0; availverts = maxverts - 1; startindex = endindex = 0; availindexes = maxindexes - 3; } template static int split(const vec *in, int numin, float below, float above, vec *out) { int numout = 0; const vec *p = &in[numin-1]; float pc = (*p)[C]; loopi(numin) { const vec &v = in[i]; float c = v[C]; if(c < below) { if(pc > above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); if(pc > below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); } else if(c > above) { if(pc < below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); if(pc < above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); } else if(pc < below) { if(c > below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); } else if(pc > above && c < above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); out[numout++] = v; p = &v; pc = c; } return numout; } template static int clip(const vec *in, int numin, float below, float above, vec *out) { int numout = 0; const vec *p = &in[numin-1]; float pc = (*p)[C]; loopi(numin) { const vec &v = in[i]; float c = v[C]; if(c < below) { if(pc > above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); if(pc > below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); } else if(c > above) { if(pc < below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); if(pc < above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); } else { if(pc < below) { if(c > below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); } else if(pc > above && c < above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); out[numout++] = v; } p = &v; pc = c; } return numout; } void dupblob() { if(lastblob->startvert >= lastblob->endvert) { lastblob->startindex = lastblob->endindex = endindex; lastblob->startvert = lastblob->endvert = endvert; return; } blobinfo &b = newblob(lastblob->o, lastblob->radius); b.millis = -1; } inline int addvert(const vec &pos) { blobvert &v = verts[endvert]; v.pos = pos; v.u = (pos.x - blobmin.x) / (blobmax.x - blobmin.x); v.v = (pos.y - blobmin.y) / (blobmax.y - blobmin.y); v.color = bvec(255, 255, 255); if(pos.z < blobmin.z + blobfadelow) v.alpha = uchar(blobalphalow * (pos.z - blobmin.z)); else if(pos.z > blobmax.z - blobfadehigh) v.alpha = uchar(blobalphahigh * (blobmax.z - pos.z)); else v.alpha = blobalpha; return endvert++; } void addtris(const vec *v, int numv) { if(endvert != int(lastblob->endvert) || endindex != int(lastblob->endindex)) dupblob(); for(const vec *cur = &v[2], *end = &v[numv];;) { int limit = maxverts - endvert - 2; if(limit <= 0) { while(availverts < limit+2) if(!freeblob()) return; availverts -= limit+2; lastblob->endvert = maxverts; endvert = 0; dupblob(); limit = maxverts - 2; } limit = min(int(end - cur), min(limit, (maxindexes - endindex)/3)); while(availverts < limit+2) if(!freeblob()) return; while(availindexes < limit*3) if(!freeblob()) return; int i1 = addvert(v[0]), i2 = addvert(cur[-1]); loopk(limit) { indexes[endindex++] = i1; indexes[endindex++] = i2; i2 = addvert(*cur++); indexes[endindex++] = i2; } availverts -= endvert - lastblob->endvert; availindexes -= endindex - lastblob->endindex; lastblob->endvert = endvert; lastblob->endindex = endindex; if(endvert >= maxverts) endvert = 0; if(endindex >= maxindexes) endindex = 0; if(cur >= end) break; dupblob(); } } void gentris(cube &cu, int orient, const ivec &o, int size, materialsurface *mat = NULL, int vismask = 0) { vec pos[MAXFACEVERTS+8]; int dim = dimension(orient), numverts = 0, numplanes = 1, flat = -1; if(mat) { switch(orient) { #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: v0 v1 v2 v3 break; #define GENFACEVERT(orient, vert, x,y,z, xv,yv,zv) \ pos[numverts++] = vec(x xv, y yv, z zv); GENFACEVERTS(o.x, o.x, o.y, o.y, o.z, o.z, , + mat->csize, , + mat->rsize, + 0.1f, - 0.1f); #undef GENFACEORIENT #undef GENFACEVERT } flat = dim; } else if(cu.texture[orient] == DEFAULT_SKY) return; else if(cu.ext && (numverts = cu.ext->surfaces[orient].numverts&MAXFACEVERTS)) { vertinfo *verts = cu.ext->verts() + cu.ext->surfaces[orient].verts; ivec vo = ivec(o).mask(~0xFFF).shl(3); loopj(numverts) pos[j] = verts[j].getxyz().add(vo).tovec().mul(1/8.0f); if(numverts >= 4 && !(cu.merged&(1<= 0) { float offset = pos[0][dim]; if(offset < blobmin[dim] || offset > blobmax[dim]) return; flat = dim; } vec vmin = pos[0], vmax = pos[0]; for(int i = 1; i < numverts; i++) { vmin.min(pos[i]); vmax.max(pos[i]); } if(vmax.x < blobmin.x || vmin.x > blobmax.x || vmax.y < blobmin.y || vmin.y > blobmax.y || vmax.z < blobmin.z || vmin.z > blobmax.z) return; vec v1[MAXFACEVERTS+6+4], v2[MAXFACEVERTS+6+4]; loopl(numplanes) { vec *v = pos; int numv = numverts; if(numplanes >= 2) { if(l) { pos[1] = pos[2]; pos[2] = pos[3]; } numv = 3; } if(vec().cross(v[0], v[1], v[2]).z <= 0) continue; #define CLIPSIDE(clip, below, above) \ { \ vec *in = v; \ v = in==v1 ? v2 : v1; \ numv = clip(in, numv, below, above, v); \ if(numv < 3) continue; \ } if(flat!=0) CLIPSIDE(clip<0>, blobmin.x, blobmax.x); if(flat!=1) CLIPSIDE(clip<1>, blobmin.y, blobmax.y); if(flat!=2) { CLIPSIDE(clip<2>, blobmin.z, blobmax.z); CLIPSIDE(split<2>, blobmin.z + blobfadelow, blobmax.z - blobfadehigh); } addtris(v, numv); } } void findmaterials(vtxarray *va) { materialsurface *matbuf = va->matbuf; int matsurfs = va->matsurfs; loopi(matsurfs) { materialsurface &m = matbuf[i]; if(!isclipped(m.material&MATF_VOLUME) || m.orient == O_BOTTOM) { i += m.skip; continue; } int dim = dimension(m.orient), c = C[dim], r = R[dim]; for(;;) { materialsurface &m = matbuf[i]; if(m.o[dim] >= blobmin[dim] && m.o[dim] <= blobmax[dim] && m.o[c] + m.csize >= blobmin[c] && m.o[c] <= blobmax[c] && m.o[r] + m.rsize >= blobmin[r] && m.o[r] <= blobmax[r]) { static cube dummy; gentris(dummy, m.orient, m.o, max(m.csize, m.rsize), &m); } if(i+1 >= matsurfs) break; materialsurface &n = matbuf[i+1]; if(n.material != m.material || n.orient != m.orient) break; i++; } } } void findescaped(cube *cu, const ivec &o, int size, int escaped) { loopi(8) { if(escaped&(1<>1, cu[i].escaped); else { int vismask = cu[i].merged; if(vismask) loopj(6) if(vismask&(1<va && cu[i].ext->va->matsurfs) findmaterials(cu[i].ext->va); if(cu[i].children) gentris(cu[i].children, co, size>>1, cu[i].escaped); else { int vismask = cu[i].visible; if(vismask&0xC0) { if(vismask&0x80) loopj(6) gentris(cu[i], j, co, size, NULL, vismask); else loopj(6) if(vismask&(1<>1, cu[i].escaped); else { int vismask = cu[i].merged; if(vismask) loopj(6) if(vismask&(1<>1); return b.millis >= 0 ? &b : NULL; } static void setuprenderstate() { foggedshader->set(); enablepolygonoffset(GL_POLYGON_OFFSET_FILL); glDepthMask(GL_FALSE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if(!dbgblob) glEnable(GL_BLEND); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); } static void cleanuprenderstate() { glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDepthMask(GL_TRUE); glDisable(GL_BLEND); disablepolygonoffset(GL_POLYGON_OFFSET_FILL); } static int lastreset; static void reset() { lastreset = totalmillis; } static blobrenderer *lastrender; void fadeblob(blobinfo *b, float fade) { float minz = b->o.z - (blobheight + blobfadelow), maxz = b->o.z + blobfadehigh, scale = fade*blobintensity*255/100.0f, scalelow = scale / blobfadelow, scalehigh = scale / blobfadehigh; uchar alpha = uchar(scale); b->millis = totalmillis; do { if(b->endvert - b->startvert >= 3) for(blobvert *v = &verts[b->startvert], *end = &verts[b->endvert]; v < end; v++) { float z = v->pos.z; if(z < minz + blobfadelow) v->alpha = uchar(scalelow * (z - minz)); else if(z > maxz - blobfadehigh) v->alpha = uchar(scalehigh * (maxz - z)); else v->alpha = alpha; } int offset = b - &blobs[0] + 1; if(offset >= maxblobs) offset = 0; if(offset < endblob ? offset > startblob || startblob > endblob : offset > startblob) b = &blobs[offset]; else break; } while(b->millis < 0); } void renderblob(const vec &o, float radius, float fade) { if(lastrender != this) { if(!lastrender) { if(!blobs) initblobs(); setuprenderstate(); } glVertexPointer(3, GL_FLOAT, sizeof(blobvert), &verts->pos); glTexCoordPointer(2, GL_FLOAT, sizeof(blobvert), &verts->u); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(blobvert), &verts->color); if(!lastrender || lastrender->tex != tex) glBindTexture(GL_TEXTURE_2D, tex->id); lastrender = this; } union { int i; float f; } ox, oy; ox.f = o.x; oy.f = o.y; uint hash = uint(ox.i^~oy.i^(INT_MAX-oy.i)^uint(radius)); hash %= cachesize; blobinfo *b = cache[hash]; if(!b || b->millis <= lastreset || b->o!=o || b->radius!=radius) { b = addblob(o, radius, fade); cache[hash] = b; if(!b) return; } else if(fade < 1 && b->millis < totalmillis) fadeblob(b, fade); do { if(b->endvert - b->startvert >= 3) { if(hasDRE) glDrawRangeElements_(GL_TRIANGLES, b->startvert, b->endvert-1, b->endindex - b->startindex, GL_UNSIGNED_SHORT, &indexes[b->startindex]); else glDrawElements(GL_TRIANGLES, b->endindex - b->startindex, GL_UNSIGNED_SHORT, &indexes[b->startindex]); xtravertsva += b->endvert - b->startvert; } int offset = b - &blobs[0] + 1; if(offset >= maxblobs) offset = 0; if(offset < endblob ? offset > startblob || startblob > endblob : offset > startblob) b = &blobs[offset]; else break; } while(b->millis < 0); } }; int blobrenderer::lastreset = 0; blobrenderer *blobrenderer::lastrender = NULL; VARFP(blobstattris, 128, 4096, 1<<16, initblobs(BLOB_STATIC)); VARFP(blobdyntris, 128, 4096, 1<<16, initblobs(BLOB_DYNAMIC)); static blobrenderer blobs[] = { blobrenderer("packages/particles/blob.png"), blobrenderer("packages/particles/blob.png") }; void initblobs(int type) { if(type < 0 || (type==BLOB_STATIC && blobs[BLOB_STATIC].blobs)) blobs[BLOB_STATIC].init(showblobs ? blobstattris : 0); if(type < 0 || (type==BLOB_DYNAMIC && blobs[BLOB_DYNAMIC].blobs)) blobs[BLOB_DYNAMIC].init(showblobs ? blobdyntris : 0); } void resetblobs() { blobrenderer::lastreset = totalmillis; } void renderblob(int type, const vec &o, float radius, float fade) { if(!showblobs) return; if(refracting < 0 && o.z - blobheight - blobfadelow >= reflectz) return; blobs[type].renderblob(o, radius + blobmargin, fade); } void flushblobs() { if(blobrenderer::lastrender) blobrenderer::cleanuprenderstate(); blobrenderer::lastrender = NULL; } sauerbraten-0.0.20130203.dfsg/engine/material.cpp0000644000175000017500000011036412060612257021152 0ustar vincentvincent#include "engine.h" struct QuadNode { int x, y, size; uint filled; QuadNode *child[4]; QuadNode(int x, int y, int size) : x(x), y(y), size(size), filled(0) { loopi(4) child[i] = 0; } void clear() { loopi(4) DELETEP(child[i]); } ~QuadNode() { clear(); } void insert(int mx, int my, int msize) { if(size == msize) { filled = 0xF; return; } int csize = size>>1, i = 0; if(mx >= x+csize) i |= 1; if(my >= y+csize) i |= 2; if(csize == msize) { filled |= (1 << i); return; } if(!child[i]) child[i] = new QuadNode(i&1 ? x+csize : x, i&2 ? y+csize : y, csize); child[i]->insert(mx, my, msize); loopj(4) if(child[j]) { if(child[j]->filled == 0xF) { DELETEP(child[j]); filled |= (1 << j); } } } void genmatsurf(ushort mat, uchar orient, uchar flags, int x, int y, int z, int size, materialsurface *&matbuf) { materialsurface &m = *matbuf++; m.material = mat; m.orient = orient; m.flags = flags; m.csize = size; m.rsize = size; int dim = dimension(orient); m.o[C[dim]] = x; m.o[R[dim]] = y; m.o[dim] = z; } void genmatsurfs(ushort mat, uchar orient, uchar flags, int z, materialsurface *&matbuf) { if(filled == 0xF) genmatsurf(mat, orient, flags, x, y, z, size, matbuf); else if(filled) { int csize = size>>1; loopi(4) if(filled & (1 << i)) genmatsurf(mat, orient, flags, i&1 ? x+csize : x, i&2 ? y+csize : y, z, csize, matbuf); } loopi(4) if(child[i]) child[i]->genmatsurfs(mat, orient, flags, z, matbuf); } }; static float wfwave, wfscroll, wfxscale, wfyscale; static void renderwaterfall(const materialsurface &m, float offset, const vec *normal = NULL) { if(varray::data.empty()) { varray::defattrib(varray::ATTRIB_VERTEX, 3, GL_FLOAT); if(normal) varray::defattrib(varray::ATTRIB_NORMAL, 3, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD0, 2, GL_FLOAT); varray::begin(GL_QUADS); } float x = m.o.x, y = m.o.y, zmin = m.o.z, zmax = zmin; if(m.ends&1) zmin += -WATER_OFFSET-WATER_AMPLITUDE; if(m.ends&2) zmax += wfwave; int csize = m.csize, rsize = m.rsize; #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: v0 v1 v2 v3 break; #undef GENFACEVERTX #define GENFACEVERTX(orient, vert, mx,my,mz, sx,sy,sz) \ { \ vec v(mx sx, my sy, mz sz); \ varray::attrib(v.x, v.y, v.z); \ GENFACENORMAL \ varray::attrib(wfxscale*v.y, wfyscale*(v.z+wfscroll)); \ } #undef GENFACEVERTY #define GENFACEVERTY(orient, vert, mx,my,mz, sx,sy,sz) \ { \ vec v(mx sx, my sy, mz sz); \ varray::attrib(v.x, v.y, v.z); \ GENFACENORMAL \ varray::attrib(wfxscale*v.x, wfyscale*(v.z+wfscroll)); \ } #define GENFACENORMAL varray::attrib(n.x, n.y, n.z); if(normal) { vec n = *normal; switch(m.orient) { GENFACEVERTSXY(x, x, y, y, zmin, zmax, /**/, + csize, /**/, + rsize, + offset, - offset) } } #undef GENFACENORMAL #define GENFACENORMAL else switch(m.orient) { GENFACEVERTSXY(x, x, y, y, zmin, zmax, /**/, + csize, /**/, + rsize, + offset, - offset) } #undef GENFACENORMAL #undef GENFACEORIENT #undef GENFACEVERTX #define GENFACEVERTX(o,n, x,y,z, xv,yv,zv) GENFACEVERT(o,n, x,y,z, xv,yv,zv) #undef GENFACEVERTY #define GENFACEVERTY(o,n, x,y,z, xv,yv,zv) GENFACEVERT(o,n, x,y,z, xv,yv,zv) } static void drawmaterial(const materialsurface &m, float offset) { if(varray::data.empty()) { varray::defattrib(varray::ATTRIB_VERTEX, 3, GL_FLOAT); varray::begin(GL_QUADS); } float x = m.o.x, y = m.o.y, z = m.o.z, csize = m.csize, rsize = m.rsize; switch(m.orient) { #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: v0 v1 v2 v3 break; #define GENFACEVERT(orient, vert, mx,my,mz, sx,sy,sz) \ varray::attrib(mx sx, my sy, mz sz); GENFACEVERTS(x, x, y, y, z, z, /**/, + csize, /**/, + rsize, + offset, - offset) #undef GENFACEORIENT #undef GENFACEVERT } } const struct material { const char *name; ushort id; } materials[] = { {"air", MAT_AIR}, {"water", MAT_WATER}, {"water1", MAT_WATER}, {"water2", MAT_WATER+1}, {"water3", MAT_WATER+2}, {"water4", MAT_WATER+3}, {"glass", MAT_GLASS}, {"glass1", MAT_GLASS}, {"glass2", MAT_GLASS+1}, {"glass3", MAT_GLASS+2}, {"glass4", MAT_GLASS+3}, {"lava", MAT_LAVA}, {"lava1", MAT_LAVA}, {"lava2", MAT_LAVA+1}, {"lava3", MAT_LAVA+2}, {"lava4", MAT_LAVA+3}, {"clip", MAT_CLIP}, {"noclip", MAT_NOCLIP}, {"gameclip", MAT_GAMECLIP}, {"death", MAT_DEATH}, {"alpha", MAT_ALPHA} }; int findmaterial(const char *name) { loopi(sizeof(materials)/sizeof(material)) { if(!strcmp(materials[i].name, name)) return materials[i].id; } return -1; } const char *findmaterialname(int mat) { loopi(sizeof(materials)/sizeof(materials[0])) if(materials[i].id == mat) return materials[i].name; return NULL; } const char *getmaterialdesc(int mat, const char *prefix) { static const ushort matmasks[] = { MATF_VOLUME|MATF_INDEX, MATF_CLIP, MAT_DEATH, MAT_ALPHA }; static string desc; desc[0] = '\0'; loopi(sizeof(matmasks)/sizeof(matmasks[0])) if(mat&matmasks[i]) { const char *matname = findmaterialname(mat&matmasks[i]); if(matname) { concatstring(desc, desc[0] ? ", " : prefix); concatstring(desc, matname); } } return desc; } int visiblematerial(const cube &c, int orient, int x, int y, int z, int size, ushort matmask) { ushort mat = c.material&matmask; switch(mat) { case MAT_AIR: break; case MAT_LAVA: case MAT_WATER: if(visibleface(c, orient, x, y, z, size, mat, MAT_AIR, matmask)) return (orient != O_BOTTOM ? MATSURF_VISIBLE : MATSURF_EDIT_ONLY); break; case MAT_GLASS: if(visibleface(c, orient, x, y, z, size, MAT_GLASS, MAT_AIR, matmask)) return MATSURF_VISIBLE; break; default: if(visibleface(c, orient, x, y, z, size, mat, MAT_AIR, matmask)) return MATSURF_EDIT_ONLY; break; } return MATSURF_NOT_VISIBLE; } void genmatsurfs(const cube &c, int cx, int cy, int cz, int size, vector &matsurfs) { loopi(6) { static const ushort matmasks[] = { MATF_VOLUME|MATF_INDEX, MATF_CLIP, MAT_DEATH, MAT_ALPHA }; loopj(sizeof(matmasks)/sizeof(matmasks[0])) { int matmask = matmasks[j]; int vis = visiblematerial(c, i, cx, cy, cz, size, matmask&~MATF_INDEX); if(vis != MATSURF_NOT_VISIBLE) { materialsurface m; m.material = c.material&matmask; m.orient = i; m.flags = vis == MATSURF_EDIT_ONLY ? materialsurface::F_EDIT : 0; m.o = ivec(cx, cy, cz); m.csize = m.rsize = size; if(dimcoord(i)) m.o[dimension(i)] += size; matsurfs.add(m); break; } } } } static inline bool mergematcmp(const materialsurface &x, const materialsurface &y) { int dim = dimension(x.orient), c = C[dim], r = R[dim]; if(x.o[r] + x.rsize < y.o[r] + y.rsize) return true; if(x.o[r] + x.rsize > y.o[r] + y.rsize) return false; return x.o[c] < y.o[c]; } static int mergematr(materialsurface *m, int sz, materialsurface &n) { int dim = dimension(n.orient), c = C[dim], r = R[dim]; for(int i = sz-1; i >= 0; --i) { if(m[i].o[r] + m[i].rsize < n.o[r]) break; if(m[i].o[r] + m[i].rsize == n.o[r] && m[i].o[c] == n.o[c] && m[i].csize == n.csize) { n.o[r] = m[i].o[r]; n.rsize += m[i].rsize; memmove(&m[i], &m[i+1], (sz - (i+1)) * sizeof(materialsurface)); return 1; } } return 0; } static int mergematc(materialsurface &m, materialsurface &n) { int dim = dimension(n.orient), c = C[dim], r = R[dim]; if(m.o[r] == n.o[r] && m.rsize == n.rsize && m.o[c] + m.csize == n.o[c]) { n.o[c] = m.o[c]; n.csize += m.csize; return 1; } return 0; } static int mergemat(materialsurface *m, int sz, materialsurface &n) { for(bool merged = false; sz; merged = true) { int rmerged = mergematr(m, sz, n); sz -= rmerged; if(!rmerged && merged) break; if(!sz) break; int cmerged = mergematc(m[sz-1], n); sz -= cmerged; if(!cmerged) break; } m[sz++] = n; return sz; } static int mergemats(materialsurface *m, int sz) { quicksort(m, sz, mergematcmp); int nsz = 0; loopi(sz) nsz = mergemat(m, nsz, m[i]); return nsz; } static inline bool optmatcmp(const materialsurface &x, const materialsurface &y) { if(x.material < y.material) return true; if(x.material > y.material) return false; if(x.orient > y.orient) return true; if(x.orient < y.orient) return false; int dim = dimension(x.orient); return x.o[dim] < y.o[dim]; } VARF(optmats, 0, 1, 1, allchanged()); int optimizematsurfs(materialsurface *matbuf, int matsurfs) { quicksort(matbuf, matsurfs, optmatcmp); if(!optmats) return matsurfs; materialsurface *cur = matbuf, *end = matbuf+matsurfs; while(cur < end) { materialsurface *start = cur++; int dim = dimension(start->orient); while(cur < end && cur->material == start->material && cur->orient == start->orient && cur->flags == start->flags && cur->o[dim] == start->o[dim]) ++cur; if(!isliquid(start->material&MATF_VOLUME) || start->orient != O_TOP || !vertwater) { if(start!=matbuf) memmove(matbuf, start, (cur-start)*sizeof(materialsurface)); matbuf += mergemats(matbuf, cur-start); } else if(cur-start>=4) { QuadNode vmats(0, 0, worldsize); loopi(cur-start) vmats.insert(start[i].o[C[dim]], start[i].o[R[dim]], start[i].csize); vmats.genmatsurfs(start->material, start->orient, start->flags, start->o[dim], matbuf); } else { if(start!=matbuf) memmove(matbuf, start, (cur-start)*sizeof(materialsurface)); matbuf += cur-start; } } return matsurfs - (end-matbuf); } extern vector valist; struct waterinfo { materialsurface *m; double depth, area; }; void setupmaterials(int start, int len) { int hasmat = 0; vector water; unionfind uf; if(!len) len = valist.length(); for(int i = start; i < len; i++) { vtxarray *va = valist[i]; materialsurface *skip = NULL; loopj(va->matsurfs) { materialsurface &m = va->matbuf[j]; int matvol = m.material&MATF_VOLUME; if(matvol==MAT_WATER && m.orient==O_TOP) { m.index = water.length(); loopvk(water) { materialsurface &n = *water[k].m; if(m.material!=n.material || m.o.z!=n.o.z) continue; if(n.o.x+n.rsize==m.o.x || m.o.x+m.rsize==n.o.x) { if(n.o.y+n.csize>m.o.y && n.o.ym.o.x && n.o.xmaterial && m.orient == skip->orient && skip->skip < 0xFFFF) skip->skip++; else skip = &m; } } loopv(water) { int root = uf.find(i); if(i==root) continue; materialsurface &m = *water[i].m, &n = *water[root].m; if(m.light && (!m.light->attr1 || !n.light || (n.light->attr1 && m.light->attr1 > n.light->attr1))) n.light = m.light; water[root].depth += water[i].depth; water[root].area += water[i].area; } loopv(water) { int root = uf.find(i); water[i].m->light = water[root].m->light; water[i].m->depth = (short)(water[root].depth/water[root].area); } if(hasmat&(0xF< ymin && ymax > xmin) continue; int c = sortorigin[dim]; if(c > xmin && c < xmax) return sortedit; if(c > ymin && c < ymax) return !sortedit; xmin = abs(xmin - c); xmax = abs(xmax - c); ymin = abs(ymin - c); ymax = abs(ymax - c); if(max(xmin, xmax) <= min(ymin, ymax)) return sortedit; else if(max(ymin, ymax) <= min(xmin, xmax)) return !sortedit; } if(x.material < y.material) return sortedit; if(x.material > y.material) return !sortedit; return false; } extern vtxarray *visibleva, *reflectedva; void sortmaterials(vector &vismats) { sortorigin = ivec(camera1->o); if(reflecting) sortorigin.z = int(reflectz - (camera1->o.z - reflectz)); vec dir; vecfromyawpitch(camera1->yaw, reflecting ? -camera1->pitch : camera1->pitch, 1, 0, dir); loopi(3) { dir[i] = fabs(dir[i]); sortdim[i] = i; } if(dir[sortdim[2]] > dir[sortdim[1]]) swap(sortdim[2], sortdim[1]); if(dir[sortdim[1]] > dir[sortdim[0]]) swap(sortdim[1], sortdim[0]); if(dir[sortdim[2]] > dir[sortdim[1]]) swap(sortdim[2], sortdim[1]); for(vtxarray *va = reflecting ? reflectedva : visibleva; va; va = reflecting ? va->rnext : va->next) { if(!va->matsurfs || va->occluded >= OCCLUDE_BB) continue; if(reflecting || refracting>0 ? va->o.z+va->size <= reflectz : va->o.z >= reflectz) continue; loopi(va->matsurfs) { materialsurface &m = va->matbuf[i]; if(!editmode || !showmat || envmapping) { int matvol = m.material&MATF_VOLUME; if(matvol==MAT_WATER && (m.orient==O_TOP || (refracting<0 && reflectz>worldsize))) { i += m.skip; continue; } if(m.flags&materialsurface::F_EDIT) { i += m.skip; continue; } if(glaring && matvol!=MAT_LAVA) { i += m.skip; continue; } } else if(glaring) continue; vismats.add(&m); } } sortedit = editmode && showmat && !envmapping; vismats.sort(vismatcmp); } void rendermatgrid(vector &vismats) { enablepolygonoffset(GL_POLYGON_OFFSET_LINE); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); int lastmat = -1; loopvrev(vismats) { materialsurface &m = *vismats[i]; if(m.material != lastmat) { xtraverts += varray::end(); lastmat = m.material; switch(m.material&~MATF_INDEX) { case MAT_WATER: glColor3ub( 0, 0, 85); break; // blue case MAT_CLIP: glColor3ub(85, 0, 0); break; // red case MAT_GLASS: glColor3ub( 0, 85, 85); break; // cyan case MAT_NOCLIP: glColor3ub( 0, 85, 0); break; // green case MAT_LAVA: glColor3ub(85, 40, 0); break; // orange case MAT_GAMECLIP: glColor3ub(85, 85, 0); break; // yellow case MAT_DEATH: glColor3ub(40, 40, 40); break; // black case MAT_ALPHA: glColor3ub(85, 0, 85); break; // pink } } drawmaterial(m, -0.1f); } xtraverts += varray::end(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); disablepolygonoffset(GL_POLYGON_OFFSET_LINE); } #define GLASSVARS(name) \ bvec name##color(0x20, 0x80, 0xC0); \ HVARFR(name##colour, 0, 0x2080C0, 0xFFFFFF, \ { \ if(!name##colour) name##colour = 0x2080FF; \ name##color = bvec((name##colour>>16)&0xFF, (name##colour>>8)&0xFF, name##colour&0xFF); \ }); GLASSVARS(glass) GLASSVARS(glass2) GLASSVARS(glass3) GLASSVARS(glass4) GETMATIDXVAR(glass, colour, int) GETMATIDXVAR(glass, color, const bvec &) VARP(glassenv, 0, 1, 1); static void drawglass(const materialsurface &m, float offset, const vec *normal = NULL) { if(varray::data.empty()) { varray::defattrib(varray::ATTRIB_VERTEX, 3, GL_FLOAT); if(normal) varray::defattrib(varray::ATTRIB_NORMAL, 3, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); varray::begin(GL_QUADS); } #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: v0 v1 v2 v3 break; #define GENFACEVERT(orient, vert, mx,my,mz, sx,sy,sz) \ { \ vec v(mx sx, my sy, mz sz); \ vec reflect = vec(v).sub(camera1->o); \ reflect[dimension(orient)] = -reflect[dimension(orient)]; \ varray::attrib(v.x, v.y, v.z); \ GENFACENORMAL \ varray::attrib(reflect.x, reflect.y, reflect.z); \ } #define GENFACENORMAL varray::attrib(n.x, n.y, n.z); float x = m.o.x, y = m.o.y, z = m.o.z, csize = m.csize, rsize = m.rsize; if(normal) { vec n = *normal; switch(m.orient) { GENFACEVERTS(x, x, y, y, z, z, /**/, + csize, /**/, + rsize, + offset, - offset) } } #undef GENFACENORMAL #define GENFACENORMAL else switch(m.orient) { GENFACEVERTS(x, x, y, y, z, z, /**/, + csize, /**/, + rsize, + offset, - offset) } #undef GENFACENORMAL #undef GENFACEORIENT #undef GENFACEVERT } VARFP(waterfallenv, 0, 1, 1, preloadwatershaders()); void rendermaterials() { vector vismats; sortmaterials(vismats); if(vismats.empty()) return; glDisable(GL_CULL_FACE); varray::enable(); MSlot *mslot = NULL; uchar wcol[4] = { 255, 255, 255, 192 }, wfcol[4] = { 255, 255, 255, 192 }; int lastorient = -1, lastmat = -1, usedwaterfall = -1; GLenum textured = GL_TEXTURE_2D; bool depth = true, blended = false, tint = false, overbright = false, usedcamera = false; ushort envmapped = EMID_NONE; static const vec normals[6] = { vec(-1, 0, 0), vec( 1, 0, 0), vec(0, -1, 0), vec(0, 1, 0), vec(0, 0, -1), vec(0, 0, 1) }; static const float zerofog[4] = { 0, 0, 0, 1 }; float oldfogc[4]; glGetFloatv(GL_FOG_COLOR, oldfogc); int lastfogtype = 1; if(editmode && showmat && !envmapping) { glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR); glEnable(GL_BLEND); blended = true; glDisable(GL_TEXTURE_2D); textured = 0; foggednotextureshader->set(); glFogfv(GL_FOG_COLOR, zerofog); lastfogtype = 0; loopv(vismats) { const materialsurface &m = *vismats[i]; if(lastmat!=m.material) { xtraverts += varray::end(); switch(m.material&~MATF_INDEX) { case MAT_WATER: glColor3ub(255, 128, 0); break; // blue case MAT_CLIP: glColor3ub( 0, 255, 255); break; // red case MAT_GLASS: glColor3ub(255, 0, 0); break; // cyan case MAT_NOCLIP: glColor3ub(255, 0, 255); break; // green case MAT_LAVA: glColor3ub( 0, 128, 255); break; // orange case MAT_GAMECLIP: glColor3ub( 0, 0, 255); break; // yellow case MAT_DEATH: glColor3ub(192, 192, 192); break; // black case MAT_ALPHA: glColor3ub( 0, 255, 0); break; // pink default: continue; } lastmat = m.material; } drawmaterial(m, -0.1f); } } else loopv(vismats) { const materialsurface &m = *vismats[i]; int matvol = m.material&~MATF_INDEX; if(lastmat!=m.material || lastorient!=m.orient || (matvol==MAT_GLASS && envmapped && m.envmap != envmapped)) { int fogtype = lastfogtype; switch(matvol) { case MAT_WATER: if(m.orient == O_TOP) continue; if(lastmat == m.material) break; mslot = &lookupmaterialslot(m.material, false); if(!mslot->loaded || !mslot->sts.inrange(1)) continue; else { xtraverts += varray::end(); glBindTexture(GL_TEXTURE_2D, mslot->sts[1].t->id); float angle = fmod(float(lastmillis/(renderpath!=R_FIXEDFUNCTION ? 600.0f : 300.0f)/(2*M_PI)), 1.0f), s = angle - int(angle) - 0.5f; s *= 8 - fabs(s)*16; wfwave = vertwater ? WATER_AMPLITUDE*s-WATER_OFFSET : -WATER_OFFSET; wfscroll = 16.0f*lastmillis/1000.0f; wfxscale = TEX_SCALE/(mslot->sts[1].t->xs*mslot->scale); wfyscale = TEX_SCALE/(mslot->sts[1].t->ys*mslot->scale); memcpy(wcol, getwatercolor(m.material).v, 3); memcpy(wfcol, getwaterfallcolor(m.material).v, 3); if(!wfcol[0] && !wfcol[1] && !wfcol[2]) memcpy(wfcol, wcol, 3); int wfog = getwaterfog(m.material); if(overbright || tint) { resettmu(0); overbright = tint = false; } if(!wfog && (renderpath==R_FIXEDFUNCTION || !hasCM || !waterfallenv)) { glColor3ubv(wfcol); foggednotextureshader->set(); fogtype = 1; if(blended) { glDisable(GL_BLEND); blended = false; } if(!depth) { glDepthMask(GL_TRUE); depth = true; } if(textured) { glDisable(textured); textured = 0; } break; } else if(renderpath==R_FIXEDFUNCTION || ((!waterfallrefract || reflecting || refracting) && (!hasCM || !waterfallenv))) { glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR); glColor3ubv(wfcol); foggedshader->set(); fogtype = 0; if(!blended) { glEnable(GL_BLEND); blended = true; } if(depth) { glDepthMask(GL_FALSE); depth = false; } } else { glColor3ubv(wfcol); fogtype = 1; if(!usedcamera) { setenvparamf("camera", SHPARAM_VERTEX, 0, camera1->o.x, camera1->o.y, camera1->o.z); usedcamera = true; } if(waterfallrefract && wfog && !reflecting && !refracting) { if(hasCM && waterfallenv) SETSHADER(waterfallenvrefract); else SETSHADER(waterfallrefract); if(blended) { glDisable(GL_BLEND); blended = false; } if(!depth) { glDepthMask(GL_TRUE); depth = true; } } else { SETSHADER(waterfallenv); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if(wfog) { if(!blended) { glEnable(GL_BLEND); blended = true; } if(depth) { glDepthMask(GL_FALSE); depth = false; } } else { if(blended) { glDisable(GL_BLEND); blended = false; } if(!depth) { glDepthMask(GL_TRUE); depth = true; } } } if(usedwaterfall != m.material) { Texture *dudv = mslot->sts.inrange(5) ? mslot->sts[5].t : notexture; float scale = 8.0f/(dudv->ys*mslot->scale); setlocalparamf("dudvoffset", SHPARAM_PIXEL, 1, 0, scale*16*lastmillis/1000.0f); glActiveTexture_(GL_TEXTURE1_ARB); glBindTexture(GL_TEXTURE_2D, mslot->sts.inrange(4) ? mslot->sts[4].t->id : notexture->id); glActiveTexture_(GL_TEXTURE2_ARB); glBindTexture(GL_TEXTURE_2D, mslot->sts.inrange(5) ? mslot->sts[5].t->id : notexture->id); if(hasCM && waterfallenv) { glActiveTexture_(GL_TEXTURE3_ARB); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, lookupenvmap(*mslot)); } if(waterfallrefract && (!reflecting || !refracting) && usedwaterfall < 0) { extern void setupwaterfallrefract(GLenum tmu1, GLenum tmu2); setupwaterfallrefract(GL_TEXTURE4_ARB, GL_TEXTURE0_ARB); } else glActiveTexture_(GL_TEXTURE0_ARB); usedwaterfall = m.material; } } } if(textured!=GL_TEXTURE_2D) { if(textured) glDisable(textured); glEnable(GL_TEXTURE_2D); textured = GL_TEXTURE_2D; } break; case MAT_LAVA: if(lastmat==m.material && lastorient!=O_TOP && m.orient!=O_TOP) break; mslot = &lookupmaterialslot(m.material, false); if(!mslot->loaded) continue; else { int subslot = m.orient==O_TOP ? 0 : 1; if(!mslot->sts.inrange(subslot)) continue; xtraverts += varray::end(); glBindTexture(GL_TEXTURE_2D, mslot->sts[subslot].t->id); } if(m.orient!=O_TOP) { float angle = fmod(float(lastmillis/2000.0f/(2*M_PI)), 1.0f), s = angle - int(angle) - 0.5f; s *= 8 - fabs(s)*16; wfwave = vertwater ? WATER_AMPLITUDE*s-WATER_OFFSET : -WATER_OFFSET; wfscroll = 16.0f*lastmillis/3000.0f; wfxscale = TEX_SCALE/(mslot->sts[1].t->xs*mslot->scale); wfyscale = TEX_SCALE/(mslot->sts[1].t->ys*mslot->scale); } if(lastmat!=m.material) { if(!depth) { glDepthMask(GL_TRUE); depth = true; } if(blended) { glDisable(GL_BLEND); blended = false; } if(renderpath==R_FIXEDFUNCTION && !overbright) { setuptmu(0, "C * T x 2"); overbright = true; tint = false; } float t = lastmillis/2000.0f; t -= floor(t); t = 1.0f - 2*fabs(t-0.5f); extern int glare; if(renderpath!=R_FIXEDFUNCTION && glare) t = 0.625f + 0.075f*t; else t = 0.5f + 0.5f*t; glColor3f(t, t, t); if(glaring) SETSHADER(lavaglare); else SETSHADER(lava); fogtype = 1; } if(textured!=GL_TEXTURE_2D) { if(textured) glDisable(textured); glEnable(GL_TEXTURE_2D); textured = GL_TEXTURE_2D; } break; case MAT_GLASS: if((m.envmap==EMID_NONE || !glassenv || (envmapped==m.envmap && textured==GL_TEXTURE_CUBE_MAP_ARB)) && lastmat==m.material) break; xtraverts += varray::end(); if(m.envmap!=EMID_NONE && glassenv) { if(textured!=GL_TEXTURE_CUBE_MAP_ARB) { if(textured) glDisable(textured); glEnable(GL_TEXTURE_CUBE_MAP_ARB); textured = GL_TEXTURE_CUBE_MAP_ARB; } if(envmapped!=m.envmap) { glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, lookupenvmap(m.envmap)); if(renderpath!=R_FIXEDFUNCTION && !usedcamera) { setenvparamf("camera", SHPARAM_VERTEX, 0, camera1->o.x, camera1->o.y, camera1->o.z); usedcamera = true; } envmapped = m.envmap; } } if(lastmat!=m.material) { if(!blended) { glEnable(GL_BLEND); blended = true; } if(depth) { glDepthMask(GL_FALSE); depth = false; } const bvec &gcol = getglasscolor(m.material); if(m.envmap!=EMID_NONE && glassenv) { if(renderpath==R_FIXEDFUNCTION) { if(!tint) { colortmu(0, 0.8f, 0.8f, 0.8f, 0.8f); setuptmu(0, "T , C @ Ka", "= Ca"); tint = true; overbright = false; } glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(gcol.x/255.0f, gcol.y/255.0f, gcol.z/255.0f, 0.25f); fogtype = 1; } else { if(overbright || tint) { resettmu(0); overbright = tint = false; } glBlendFunc(GL_ONE, GL_SRC_ALPHA); glColor3ubv(gcol.v); } SETSHADER(glass); } else { if(overbright || tint) { resettmu(0); overbright = tint = false; } if(textured) { glDisable(textured); textured = 0; } glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(gcol.x/255.0f, gcol.y/255.0f, gcol.z/255.0f, 0.15f); foggednotextureshader->set(); fogtype = 1; } } break; default: continue; } lastmat = m.material; lastorient = m.orient; if(fogtype!=lastfogtype) { glFogfv(GL_FOG_COLOR, fogtype ? oldfogc : zerofog); lastfogtype = fogtype; } } switch(matvol) { case MAT_WATER: renderwaterfall(m, 0.1f, renderpath!=R_FIXEDFUNCTION && hasCM && waterfallenv ? &normals[m.orient] : NULL); break; case MAT_LAVA: if(m.orient==O_TOP) renderlava(m, mslot->sts[0].t, mslot->scale); else renderwaterfall(m, 0.1f); break; case MAT_GLASS: if(m.envmap!=EMID_NONE && glassenv) drawglass(m, 0.1f, renderpath!=R_FIXEDFUNCTION ? &normals[m.orient] : NULL); else drawmaterial(m, 0.1f); break; } } xtraverts += varray::end(); if(!depth) glDepthMask(GL_TRUE); if(blended) glDisable(GL_BLEND); if(overbright || tint) resettmu(0); if(!lastfogtype) glFogfv(GL_FOG_COLOR, oldfogc); if(editmode && showmat && !envmapping) { foggedlineshader->set(); rendermatgrid(vismats); } varray::disable(); glEnable(GL_CULL_FACE); if(textured!=GL_TEXTURE_2D) { if(textured) glDisable(textured); glEnable(GL_TEXTURE_2D); } } sauerbraten-0.0.20130203.dfsg/engine/rendertarget.h0000644000175000017500000004577411733166445021534 0ustar vincentvincentextern int rtsharefb, rtscissor, blurtile; struct rendertarget { int texw, texh, vieww, viewh; GLenum colorfmt, depthfmt, target; GLuint rendertex, renderfb, renderdb, blurtex, blurfb, blurdb; int blursize; float blursigma; float blurweights[MAXBLURRADIUS+1], bluroffsets[MAXBLURRADIUS+1]; float scissorx1, scissory1, scissorx2, scissory2; #define BLURTILES 32 #define BLURTILEMASK (0xFFFFFFFFU>>(32-BLURTILES)) uint blurtiles[BLURTILES+1]; bool initialized; rendertarget() : texw(0), texh(0), vieww(0), viewh(0), colorfmt(GL_FALSE), depthfmt(GL_FALSE), target(GL_TEXTURE_2D), rendertex(0), renderfb(0), renderdb(0), blurtex(0), blurfb(0), blurdb(0), blursize(0), blursigma(0), initialized(false) { } virtual ~rendertarget() {} virtual GLenum attachment() const { return GL_COLOR_ATTACHMENT0_EXT; } virtual const GLenum *colorformats() const { static const GLenum colorfmts[] = { GL_RGB, GL_RGB8, GL_FALSE }; return colorfmts; } virtual const GLenum *depthformats() const { static const GLenum depthfmts[] = { GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT32, GL_FALSE }; return depthfmts; } virtual bool depthtest() const { return true; } void cleanup(bool fullclean = false) { if(renderfb) { glDeleteFramebuffers_(1, &renderfb); renderfb = 0; } if(renderdb) { glDeleteRenderbuffers_(1, &renderdb); renderdb = 0; } if(rendertex) { glDeleteTextures(1, &rendertex); rendertex = 0; } texw = texh = 0; cleanupblur(); if(fullclean) colorfmt = depthfmt = GL_FALSE; } void cleanupblur() { if(blurfb) { glDeleteFramebuffers_(1, &blurfb); blurfb = 0; } if(blurtex) { glDeleteTextures(1, &blurtex); blurtex = 0; } if(blurdb) { glDeleteRenderbuffers_(1, &blurdb); blurdb = 0; } blursize = 0; blursigma = 0.0f; } void setupblur() { if(!hasFBO) return; if(!blurtex) glGenTextures(1, &blurtex); createtexture(blurtex, texw, texh, NULL, 3, 1, colorfmt, target); if(!swaptexs() || rtsharefb) return; if(!blurfb) glGenFramebuffers_(1, &blurfb); glBindFramebuffer_(GL_FRAMEBUFFER_EXT, blurfb); glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, target, blurtex, 0); if(depthtest()) { if(!blurdb) glGenRenderbuffers_(1, &blurdb); glGenRenderbuffers_(1, &blurdb); glBindRenderbuffer_(GL_RENDERBUFFER_EXT, blurdb); glRenderbufferStorage_(GL_RENDERBUFFER_EXT, depthfmt, texw, texh); glFramebufferRenderbuffer_(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, blurdb); } glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); } virtual bool shadowcompare() const { return false; } void setup(int w, int h) { if(hasFBO) { if(!renderfb) glGenFramebuffers_(1, &renderfb); glBindFramebuffer_(GL_FRAMEBUFFER_EXT, renderfb); } if(!rendertex) glGenTextures(1, &rendertex); target = texrect() ? GL_TEXTURE_RECTANGLE_ARB : GL_TEXTURE_2D; GLenum attach = attachment(); if(hasFBO && attach == GL_DEPTH_ATTACHMENT_EXT) { glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); } const GLenum *colorfmts = colorformats(); int find = 0; do { createtexture(rendertex, w, h, NULL, 3, filter() ? 1 : 0, colorfmt ? colorfmt : colorfmts[find], target); if(!hasFBO) break; else { glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, attach, target, rendertex, 0); if(glCheckFramebufferStatus_(GL_FRAMEBUFFER_EXT)==GL_FRAMEBUFFER_COMPLETE_EXT) break; } } while(!colorfmt && colorfmts[++find]); if(!colorfmt) colorfmt = colorfmts[find]; if(attach == GL_DEPTH_ATTACHMENT_EXT && shadowcompare()) { if(hasDT && hasSH) { glTexParameteri(target, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE_ARB); glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC_ARB, GL_GEQUAL); glTexParameteri(target, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE); } else { glTexParameteri(target, GL_TEXTURE_COMPARE_SGIX, GL_TRUE); glTexParameteri(target, GL_TEXTURE_COMPARE_OPERATOR_SGIX, GL_TEXTURE_GEQUAL_R_SGIX); } } if(hasFBO && attach != GL_DEPTH_ATTACHMENT_EXT && depthtest()) { if(!renderdb) { glGenRenderbuffers_(1, &renderdb); depthfmt = GL_FALSE; } if(!depthfmt) glBindRenderbuffer_(GL_RENDERBUFFER_EXT, renderdb); const GLenum *depthfmts = depthformats(); find = 0; do { if(!depthfmt) glRenderbufferStorage_(GL_RENDERBUFFER_EXT, depthfmts[find], w, h); glFramebufferRenderbuffer_(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderdb); if(glCheckFramebufferStatus_(GL_FRAMEBUFFER_EXT)==GL_FRAMEBUFFER_COMPLETE_EXT) break; } while(!depthfmt && depthfmts[++find]); if(!depthfmt) depthfmt = depthfmts[find]; } if(hasFBO) glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); texw = w; texh = h; initialized = false; } bool addblurtiles(float x1, float y1, float x2, float y2, float blurmargin = 0) { if(x1 >= 1 || y1 >= 1 || x2 <= -1 || y2 <= -1) return false; scissorx1 = min(scissorx1, max(x1, -1.0f)); scissory1 = min(scissory1, max(y1, -1.0f)); scissorx2 = max(scissorx2, min(x2, 1.0f)); scissory2 = max(scissory2, min(y2, 1.0f)); float blurerror = 2.0f*float(2*blursize + blurmargin); int tx1 = max(0, min(BLURTILES - 1, int((x1-blurerror/vieww + 1)/2 * BLURTILES))), ty1 = max(0, min(BLURTILES - 1, int((y1-blurerror/viewh + 1)/2 * BLURTILES))), tx2 = max(0, min(BLURTILES - 1, int((x2+blurerror/vieww + 1)/2 * BLURTILES))), ty2 = max(0, min(BLURTILES - 1, int((y2+blurerror/viewh + 1)/2 * BLURTILES))); uint mask = (BLURTILEMASK>>(BLURTILES - (tx2+1))) & (BLURTILEMASK< scissorx2 || y1-blurerror/viewh > scissory2) return false; if(!blurtile) return true; int tx1 = max(0, min(BLURTILES - 1, int((x1 + 1)/2 * BLURTILES))), ty1 = max(0, min(BLURTILES - 1, int((y1 + 1)/2 * BLURTILES))), tx2 = max(0, min(BLURTILES - 1, int((x2 + 1)/2 * BLURTILES))), ty2 = max(0, min(BLURTILES - 1, int((y2 + 1)/2 * BLURTILES))); uint mask = (BLURTILEMASK>>(BLURTILES - (tx2+1))) & (BLURTILEMASK<>= 8; x += 8; } while(!(mask&1)) { mask >>= 1; x++; } int xstart = x; do { mask >>= 1; x++; } while(mask&1); uint strip = (BLURTILEMASK>>(BLURTILES - x)) & (BLURTILEMASK<w-vieww; y += screen->h-viewh; } else if(!blurtex) setupblur(); if(blursize!=wantsblursize || (wantsblursize && blursigma!=wantsblursigma)) { setupblurkernel(wantsblursize, wantsblursigma, blurweights, bluroffsets); blursize = wantsblursize; blursigma = wantsblursigma; } glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); if(scissor) { glScissor(x, y, w, h); glEnable(GL_SCISSOR_TEST); } loopi(2) { setblurshader(i, target == GL_TEXTURE_RECTANGLE_ARB ? 1 : (i ? texh : texw), blursize, blurweights, bluroffsets, target); if(hasFBO) { if(!swaptexs() || rtsharefb) glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, target, i ? rendertex : blurtex, 0); else glBindFramebuffer_(GL_FRAMEBUFFER_EXT, i ? renderfb : blurfb); glBindTexture(target, i ? blurtex : rendertex); } rendertiles(); if(!hasFBO) glCopyTexSubImage2D(target, 0, x-(screen->w-vieww), y-(screen->h-viewh), x, y, w, h); } if(scissor) glDisable(GL_SCISSOR_TEST); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); } virtual bool swaptexs() const { return false; } virtual bool dorender() { return true; } virtual bool shouldrender() { return true; } virtual void doblur(int blursize, float blursigma) { int sx, sy, sw, sh; bool scissoring = rtscissor && scissorblur(sx, sy, sw, sh) && sw > 0 && sh > 0; if(!scissoring) { sx = sy = 0; sw = vieww; sh = viewh; } blur(blursize, blursigma, sx, sy, sw, sh, scissoring); } virtual bool scissorrender(int &x, int &y, int &w, int &h) { if(scissorx1 >= scissorx2 || scissory1 >= scissory2) { if(vieww < texw || viewh < texh) { x = y = 0; w = vieww; h = viewh; return true; } return false; } x = max(int(floor((scissorx1+1)/2*vieww)) - 2*blursize, 0); y = max(int(floor((scissory1+1)/2*viewh)) - 2*blursize, 0); w = min(int(ceil((scissorx2+1)/2*vieww)) + 2*blursize, vieww) - x; h = min(int(ceil((scissory2+1)/2*viewh)) + 2*blursize, viewh) - y; return true; } virtual bool scissorblur(int &x, int &y, int &w, int &h) { if(scissorx1 >= scissorx2 || scissory1 >= scissory2) { if(vieww < texw || viewh < texh) { x = y = 0; w = vieww; h = viewh; return true; } return false; } x = max(int(floor((scissorx1+1)/2*vieww)), 0); y = max(int(floor((scissory1+1)/2*viewh)), 0); w = min(int(ceil((scissorx2+1)/2*vieww)), vieww) - x; h = min(int(ceil((scissory2+1)/2*viewh)), viewh) - y; return true; } virtual void doclear() {} virtual bool screenview() const { return false; } virtual bool texrect() const { return false; } virtual bool filter() const { return true; } void render(int w, int h, int blursize = 0, float blursigma = 0) { w = min(w, hwtexsize); h = min(h, hwtexsize); if(texrect()) { if(w > screen->w) w = screen->w; if(h > screen->h) h = screen->h; vieww = w; viewh = h; } else if(screenview()) { while(screen->w < (w*3)/4) w /= 2; while(screen->h < (h*3)/4) h /= 2; vieww = min(w, screen->w); viewh = min(h, screen->h); } else { if(!hasFBO) { while(w > screen->w) w /= 2; while(h > screen->h) h /= 2; } vieww = w; viewh = h; } if(w!=texw || h!=texh || (texrect() ? target!=GL_TEXTURE_RECTANGLE_ARB : target!=GL_TEXTURE_2D) || (hasFBO && (swaptexs() && !rtsharefb ? !blurfb : blurfb))) cleanup(); if(!filter()) { if(blurtex) cleanupblur(); blursize = 0; } if(!rendertex) setup(w, h); scissorx2 = scissory2 = -1; scissorx1 = scissory1 = 1; memset(blurtiles, 0, sizeof(blurtiles)); if(!shouldrender()) return; if(hasFBO) { if(blursize && !blurtex) setupblur(); if(swaptexs() && blursize) { swap(rendertex, blurtex); if(!rtsharefb) { swap(renderfb, blurfb); swap(renderdb, blurdb); } } glBindFramebuffer_(GL_FRAMEBUFFER_EXT, renderfb); if(swaptexs() && blursize && rtsharefb) glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, attachment(), target, rendertex, 0); glViewport(0, 0, vieww, viewh); } else glViewport(screen->w-vieww, screen->h-viewh, vieww, viewh); doclear(); int sx, sy, sw, sh; bool scissoring = rtscissor && scissorrender(sx, sy, sw, sh) && sw > 0 && sh > 0; if(scissoring) { if(!hasFBO) { sx += screen->w-vieww; sy += screen->h-viewh; } glScissor(sx, sy, sw, sh); glEnable(GL_SCISSOR_TEST); } else { sx = hasFBO ? 0 : screen->w-vieww; sy = hasFBO ? 0 : screen->h-viewh; sw = vieww; sh = viewh; } if(!depthtest()) glDisable(GL_DEPTH_TEST); bool succeeded = dorender(); if(!depthtest()) glEnable(GL_DEPTH_TEST); if(scissoring) glDisable(GL_SCISSOR_TEST); if(succeeded) { if(!hasFBO) { glBindTexture(target, rendertex); if(!initialized) { sx = screen->w-vieww; sy = screen->h-viewh; sw = vieww; sh = viewh; } glCopyTexSubImage2D(target, 0, sx-(screen->w-vieww), sy-(screen->h-viewh), sx, sy, sw, sh); } initialized = true; if(blursize) doblur(blursize, blursigma); } if(hasFBO) glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); glViewport(0, 0, screen->w, screen->h); } virtual void dodebug(int w, int h) {} virtual bool flipdebug() const { return true; } void debugscissor(int w, int h, bool lines = false) { if(!rtscissor || scissorx1 >= scissorx2 || scissory1 >= scissory2) return; int sx = int(0.5f*(scissorx1 + 1)*w), sy = int(0.5f*(scissory1 + 1)*h), sw = int(0.5f*(scissorx2 - scissorx1)*w), sh = int(0.5f*(scissory2 - scissory1)*h); if(flipdebug()) { sy = h - sy; sh = -sh; } glBegin(lines ? GL_LINE_LOOP : GL_TRIANGLE_STRIP); glVertex2i(sx, sy); glVertex2i(sx + sw, sy); if(lines) glVertex2i(sx + sw, sy + sh); glVertex2i(sx, sy + sh); if(!lines) glVertex2i(sx + sw, sy + sh); glEnd(); } void debugblurtiles(int w, int h, bool lines = false) { if(!blurtile) return; float vxsz = float(w)/BLURTILES, vysz = float(h)/BLURTILES; loop(y, BLURTILES+1) { uint mask = blurtiles[y]; int x = 0; while(mask) { while(!(mask&0xFF)) { mask >>= 8; x += 8; } while(!(mask&1)) { mask >>= 1; x++; } int xstart = x; do { mask >>= 1; x++; } while(mask&1); uint strip = (BLURTILEMASK>>(BLURTILES - x)) & (BLURTILEMASK<w, screen->h)/2, h = (w*screen->h)/screen->w; (target==GL_TEXTURE_RECTANGLE_ARB ? rectshader : defaultshader)->set(); glColor3f(1, 1, 1); glEnable(target); glBindTexture(target, rendertex); float tx1 = 0, tx2 = vieww, ty1 = 0, ty2 = viewh; if(target!=GL_TEXTURE_RECTANGLE_ARB) { tx2 /= vieww; ty2 /= viewh; } if(flipdebug()) swap(ty1, ty2); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(tx1, ty1); glVertex2i(0, 0); glTexCoord2f(tx2, ty1); glVertex2i(w, 0); glTexCoord2f(tx1, ty2); glVertex2i(0, h); glTexCoord2f(tx2, ty2); glVertex2i(w, h); glEnd(); notextureshader->set(); glDisable(target); dodebug(w, h); } }; sauerbraten-0.0.20130203.dfsg/engine/skelmodel.h0000644000175000017500000023346412077017136021012 0ustar vincentvincentVARP(gpuskel, 0, 1, 1); VARP(matskel, 0, 1, 1); VAR(maxskelanimdata, 1, 192, 0); #define BONEMASK_NOT 0x8000 #define BONEMASK_END 0xFFFF #define BONEMASK_BONE 0x7FFF struct skelmodel : animmodel { struct vert { vec pos, norm; float u, v; int blend, interpindex; }; struct vvert { vec pos; float u, v; }; struct vvertn : vvert { vec norm; }; struct vvertw : vvertn { uchar weights[4]; uchar bones[4]; }; struct vvertbump : vvertn { vec tangent; float bitangent; }; struct vvertbumpw : vvertw { vec tangent; float bitangent; }; struct bumpvert { vec tangent; float bitangent; }; struct tri { ushort vert[3]; }; struct blendcombo { int uses, interpindex; float weights[4]; uchar bones[4], interpbones[4]; blendcombo() : uses(1) { } bool operator==(const blendcombo &c) const { loopk(4) if(bones[k] != c.bones[k]) return false; loopk(4) if(weights[k] != c.weights[k]) return false; return true; } int size() const { int i = 1; while(i < 4 && weights[i]) i++; return i; } static bool sortcmp(const blendcombo &x, const blendcombo &y) { loopi(4) { if(x.weights[i]) { if(!y.weights[i]) return true; } else if(y.weights[i]) return false; else break; } return false; } int addweight(int sorted, float weight, int bone) { if(weight <= 1e-3f) return sorted; loopk(sorted) if(weight > weights[k]) { for(int l = min(sorted-1, 2); l >= k; l--) { weights[l+1] = weights[l]; bones[l+1] = bones[l]; } weights[k] = weight; bones[k] = bone; return sorted<4 ? sorted+1 : sorted; } if(sorted>=4) return sorted; weights[sorted] = weight; bones[sorted] = bone; return sorted+1; } void finalize(int sorted) { loopj(4-sorted) { weights[sorted+j] = 0; bones[sorted+j] = 0; } if(sorted <= 0) return; float total = 0; loopj(sorted) total += weights[j]; total = 1.0f/total; loopj(sorted) weights[j] *= total; } void serialize(vvertw &v) { if(interpindex >= 0) { v.weights[0] = 255; loopk(3) v.weights[k+1] = 0; v.bones[0] = (matskel ? 3 : 2)*interpindex; loopk(3) v.bones[k+1] = v.bones[0]; } else { int total = 0; loopk(4) total += (v.weights[k] = uchar(weights[k]*255)); while(total > 255) { loopk(4) if(v.weights[k] > 0 && total > 255) { v.weights[k]--; total--; } } while(total < 255) { loopk(4) if(v.weights[k] < 255 && total < 255) { v.weights[k]++; total++; } } loopk(4) v.bones[k] = (matskel ? 3 : 2)*interpbones[k]; } } }; struct animcacheentry { animstate as[MAXANIMPARTS]; float pitch; int millis; uchar *partmask; ragdolldata *ragdoll; animcacheentry() : ragdoll(NULL) { loopk(MAXANIMPARTS) as[k].cur.fr1 = as[k].prev.fr1 = -1; } bool operator==(const animcacheentry &c) const { loopi(MAXANIMPARTS) if(as[i]!=c.as[i]) return false; return pitch==c.pitch && partmask==c.partmask && ragdoll==c.ragdoll && (!ragdoll || min(millis, c.millis) >= ragdoll->lastmove); } }; struct vbocacheentry : animcacheentry { uchar *vdata; GLuint vbuf; int owner; vbocacheentry() : vdata(NULL), vbuf(0), owner(-1) {} }; struct skelcacheentry : animcacheentry { dualquat *bdata; matrix3x4 *mdata; int version; bool dirty; skelcacheentry() : bdata(NULL), mdata(NULL), version(-1), dirty(false) {} void nextversion() { version = Shader::uniformlocversion(); dirty = true; } }; struct blendcacheentry : skelcacheentry { int owner; blendcacheentry() : owner(-1) {} }; struct skelmeshgroup; struct skelmesh : mesh { vert *verts; bumpvert *bumpverts; tri *tris; int numverts, numtris, maxweights; int voffset, eoffset, elen; ushort minvert, maxvert; skelmesh() : verts(NULL), bumpverts(NULL), tris(NULL), numverts(0), numtris(0), maxweights(0) { } virtual ~skelmesh() { DELETEA(verts); DELETEA(bumpverts); DELETEA(tris); } int addblendcombo(const blendcombo &c) { maxweights = max(maxweights, c.size()); return ((skelmeshgroup *)group)->addblendcombo(c); } void smoothnorms(float limit = 0, bool areaweight = true) { mesh::smoothnorms(verts, numverts, tris, numtris, limit, areaweight); } void buildnorms(bool areaweight = true) { mesh::buildnorms(verts, numverts, tris, numtris, areaweight); } void calctangents(bool areaweight = true) { if(bumpverts) return; bumpverts = new bumpvert[numverts]; mesh::calctangents(bumpverts, verts, verts, numverts, tris, numtris, areaweight); } void calcbb(int frame, vec &bbmin, vec &bbmax, const matrix3x4 &m) { loopj(numverts) { vec v = m.transform(verts[j].pos); loopi(3) { bbmin[i] = min(bbmin[i], v[i]); bbmax[i] = max(bbmax[i], v[i]); } } } void gentris(int frame, Texture *tex, vector *out, const matrix3x4 &m) { loopj(numtris) { BIH::tri &t = out[noclip ? 1 : 0].add(); t.tex = tex; vert &av = verts[tris[j].vert[0]], &bv = verts[tris[j].vert[1]], &cv = verts[tris[j].vert[2]]; t.a = m.transform(av.pos); t.b = m.transform(bv.pos); t.c = m.transform(cv.pos); t.tc[0] = av.u; t.tc[1] = av.v; t.tc[2] = bv.u; t.tc[3] = bv.v; t.tc[4] = cv.u; t.tc[5] = cv.v; } } static inline bool comparevert(vvert &w, int j, vert &v) { return v.u==w.u && v.v==w.v && v.pos==w.pos; } static inline bool comparevert(vvertn &w, int j, vert &v) { return v.u==w.u && v.v==w.v && v.pos==w.pos && v.norm==w.norm; } inline bool comparevert(vvertbump &w, int j, vert &v) { return v.u==w.u && v.v==w.v && v.pos==w.pos && v.norm==w.norm && (!bumpverts || (bumpverts[j].tangent==w.tangent && bumpverts[j].bitangent==w.bitangent)); } static inline void assignvert(vvert &vv, int j, vert &v, blendcombo &c) { vv.pos = v.pos; vv.u = v.u; vv.v = v.v; } static inline void assignvert(vvertn &vv, int j, vert &v, blendcombo &c) { vv.pos = v.pos; vv.norm = v.norm; vv.u = v.u; vv.v = v.v; } inline void assignvert(vvertbump &vv, int j, vert &v, blendcombo &c) { vv.pos = v.pos; vv.norm = v.norm; vv.u = v.u; vv.v = v.v; if(bumpverts) { vv.tangent = bumpverts[j].tangent; vv.bitangent = bumpverts[j].bitangent; } else { vv.tangent = vec(0, 0, 0); vv.bitangent = 0; } } static inline void assignvert(vvertw &vv, int j, vert &v, blendcombo &c) { vv.pos = v.pos; vv.norm = v.norm; vv.u = v.u; vv.v = v.v; c.serialize(vv); } inline void assignvert(vvertbumpw &vv, int j, vert &v, blendcombo &c) { vv.pos = v.pos; vv.norm = v.norm; vv.u = v.u; vv.v = v.v; if(bumpverts) { vv.tangent = bumpverts[j].tangent; vv.bitangent = bumpverts[j].bitangent; } else { vv.tangent = vec(0, 0, 0); vv.bitangent = 0; } c.serialize(vv); } template int genvbo(vector &idxs, int offset, vector &vverts) { voffset = offset; eoffset = idxs.length(); loopi(numverts) { vert &v = verts[i]; assignvert(vverts.add(), i, v, ((skelmeshgroup *)group)->blendcombos[v.blend]); } loopi(numtris) loopj(3) idxs.add(voffset + tris[i].vert[j]); elen = idxs.length()-eoffset; minvert = voffset; maxvert = voffset + numverts-1; return numverts; } template int genvbo(vector &idxs, int offset, vector &vverts, int *htdata, int htlen) { voffset = offset; eoffset = idxs.length(); minvert = 0xFFFF; loopi(numtris) { tri &t = tris[i]; loopj(3) { int index = t.vert[j]; vert &v = verts[index]; int htidx = hthash(v.pos)&(htlen-1); loopk(htlen) { int &vidx = htdata[(htidx+k)&(htlen-1)]; if(vidx < 0) { vidx = idxs.add(ushort(vverts.length())); assignvert(vverts.add(), index, v, ((skelmeshgroup *)group)->blendcombos[v.blend]); break; } else if(comparevert(vverts[vidx], index, v)) { minvert = min(minvert, idxs.add(ushort(vidx))); break; } } } } elen = idxs.length()-eoffset; minvert = min(minvert, ushort(voffset)); maxvert = max(minvert, ushort(vverts.length()-1)); return vverts.length()-voffset; } int genvbo(vector &idxs, int offset) { loopi(numverts) verts[i].interpindex = ((skelmeshgroup *)group)->remapblend(verts[i].blend); voffset = offset; eoffset = idxs.length(); loopi(numtris) { tri &t = tris[i]; loopj(3) idxs.add(voffset+t.vert[j]); } minvert = voffset; maxvert = voffset + numverts-1; elen = idxs.length()-eoffset; return numverts; } void filltc(uchar *vdata, size_t stride) { vdata = (uchar *)&((vvert *)&vdata[voffset*stride])->u; loopi(numverts) { ((float *)vdata)[0] = verts[i].u; ((float *)vdata)[1] = verts[i].v; vdata += stride; } } void fillbump(uchar *vdata, size_t stride) { if(stride==sizeof(vvertbumpw)) vdata = (uchar *)&((vvertbumpw *)&vdata[voffset*stride])->tangent; else vdata = (uchar *)&((vvertbump *)&vdata[voffset*stride])->tangent; if(bumpverts) loopi(numverts) { ((bumpvert *)vdata)->bitangent = bumpverts[i].bitangent; vdata += stride; } else loopi(numverts) { memset(vdata, 0, sizeof(bumpvert)); vdata += stride; } } template void interpverts(const M * RESTRICT mdata1, const M * RESTRICT mdata2, bool norms, bool tangents, void * RESTRICT vdata, skin &s) { const int blendoffset = ((skelmeshgroup *)group)->skel->numgpubones; mdata2 -= blendoffset; #define IPLOOP(type, dosetup, dotransform) \ loopi(numverts) \ { \ const vert &src = verts[i]; \ type &dst = ((type * RESTRICT)vdata)[i]; \ dosetup; \ const M &m = (src.interpindex < blendoffset ? mdata1 : mdata2)[src.interpindex]; \ dst.pos = m.transform(src.pos); \ dotransform; \ } if(tangents) { if(bumpverts) { IPLOOP(vvertbump, bumpvert &bsrc = bumpverts[i], { dst.norm = m.transformnormal(src.norm); dst.tangent = m.transformnormal(bsrc.tangent); }); } else { IPLOOP(vvertbump, , dst.norm = m.transformnormal(src.norm)); } } else if(norms) { IPLOOP(vvertn, , dst.norm = m.transformnormal(src.norm)); } else { IPLOOP(vvert, , ); } #undef IPLOOP } void setshader(Shader *s) { skelmeshgroup *g = (skelmeshgroup *)group; if(glaring) { if(!g->skel->usegpuskel) s->setvariant(0, 2); else if(g->skel->usematskel) s->setvariant(min(maxweights, g->vweights), 2); else s->setvariant(min(maxweights, g->vweights)-1, 3); } else if(!g->skel->usegpuskel) s->set(); else if(g->skel->usematskel) s->setvariant(min(maxweights, g->vweights)-1, 0); else s->setvariant(min(maxweights, g->vweights)-1, 1); } void render(const animstate *as, skin &s, vbocacheentry &vc) { if(!(as->cur.anim&ANIM_NOSKIN)) { if(s.multitextured()) { if(!enablemtc || lastmtcbuf!=lastvbuf) { glClientActiveTexture_(GL_TEXTURE1_ARB); if(!enablemtc) glEnableClientState(GL_TEXTURE_COORD_ARRAY); if(lastmtcbuf!=lastvbuf) { vvert *vverts = hasVBO ? 0 : (vvert *)vc.vdata; glTexCoordPointer(2, GL_FLOAT, ((skelmeshgroup *)group)->vertsize, &vverts->u); } glClientActiveTexture_(GL_TEXTURE0_ARB); lastmtcbuf = lastvbuf; enablemtc = true; } } else if(enablemtc) disablemtc(); if(s.tangents()) { if(!enabletangents || lastxbuf!=lastvbuf) { if(!enabletangents) glEnableVertexAttribArray_(1); if(lastxbuf!=lastvbuf) { if(((skelmeshgroup *)group)->vertsize==sizeof(vvertbumpw)) { vvertbumpw *vverts = hasVBO ? 0 : (vvertbumpw *)vc.vdata; glVertexAttribPointer_(1, 4, GL_FLOAT, GL_FALSE, ((skelmeshgroup *)group)->vertsize, &vverts->tangent.x); } else { vvertbump *vverts = hasVBO ? 0 : (vvertbump *)vc.vdata; glVertexAttribPointer_(1, 4, GL_FLOAT, GL_FALSE, ((skelmeshgroup *)group)->vertsize, &vverts->tangent.x); } } lastxbuf = lastvbuf; enabletangents = true; } } else if(enabletangents) disabletangents(); if(renderpath==R_FIXEDFUNCTION && (s.scrollu || s.scrollv)) { glMatrixMode(GL_TEXTURE); glPushMatrix(); glTranslatef(s.scrollu*lastmillis/1000.0f, s.scrollv*lastmillis/1000.0f, 0); if(s.multitextured()) { glActiveTexture_(GL_TEXTURE1_ARB); glPushMatrix(); glTranslatef(s.scrollu*lastmillis/1000.0f, s.scrollv*lastmillis/1000.0f, 0); } } } if(hasDRE) glDrawRangeElements_(GL_TRIANGLES, minvert, maxvert, elen, GL_UNSIGNED_SHORT, &((skelmeshgroup *)group)->edata[eoffset]); else glDrawElements(GL_TRIANGLES, elen, GL_UNSIGNED_SHORT, &((skelmeshgroup *)group)->edata[eoffset]); glde++; xtravertsva += numverts; if(renderpath==R_FIXEDFUNCTION && !(as->cur.anim&ANIM_NOSKIN) && (s.scrollu || s.scrollv)) { if(s.multitextured()) { glPopMatrix(); glActiveTexture_(GL_TEXTURE0_ARB); } glPopMatrix(); glMatrixMode(GL_MODELVIEW); } return; } }; struct tag { char *name; int bone; matrix3x4 matrix; tag() : name(NULL) {} ~tag() { DELETEA(name); } }; struct skelanimspec { char *name; int frame, range; skelanimspec() : name(NULL), frame(0), range(0) {} ~skelanimspec() { DELETEA(name); } }; struct boneinfo { const char *name; int parent, children, next, group, scheduled, interpindex, interpparent, ragdollindex, correctindex; float pitchscale, pitchoffset, pitchmin, pitchmax; dualquat base, invbase; boneinfo() : name(NULL), parent(-1), children(-1), next(-1), group(INT_MAX), scheduled(-1), interpindex(-1), interpparent(-1), ragdollindex(-1), correctindex(-1), pitchscale(0), pitchoffset(0), pitchmin(0), pitchmax(0) {} ~boneinfo() { DELETEA(name); } }; struct antipode { int parent, child; antipode(int parent, int child) : parent(parent), child(child) {} }; struct pitchdep { int bone, parent; dualquat pose; }; struct pitchtarget { int bone, frame, corrects, deps; float pitchmin, pitchmax, deviated; dualquat pose; }; struct pitchcorrect { int bone, target, parent; float pitchmin, pitchmax, pitchscale, pitchangle, pitchtotal; }; struct skeleton { char *name; int shared; vector users; boneinfo *bones; int numbones, numinterpbones, numgpubones, numframes; dualquat *framebones; vector skelanims; vector tags; vector antipodes; ragdollskel *ragdoll; vector pitchdeps; vector pitchtargets; vector pitchcorrects; bool usegpuskel, usematskel; vector skelcache; hashtable blendoffsets; skeleton() : name(NULL), shared(0), bones(NULL), numbones(0), numinterpbones(0), numgpubones(0), numframes(0), framebones(NULL), ragdoll(NULL), usegpuskel(false), usematskel(false), blendoffsets(32) { } ~skeleton() { DELETEA(name); DELETEA(bones); DELETEA(framebones); DELETEP(ragdoll); loopv(skelcache) { DELETEA(skelcache[i].bdata); DELETEA(skelcache[i].mdata); } } skelanimspec *findskelanim(const char *name, char sep = '\0') { int len = sep ? strlen(name) : 0; loopv(skelanims) { if(skelanims[i].name) { if(sep) { const char *end = strchr(skelanims[i].name, ':'); if(end && end - skelanims[i].name == len && !memcmp(name, skelanims[i].name, len)) return &skelanims[i]; } if(!strcmp(name, skelanims[i].name)) return &skelanims[i]; } } return NULL; } skelanimspec &addskelanim(const char *name) { skelanimspec &sa = skelanims.add(); sa.name = name ? newstring(name) : NULL; return sa; } int findbone(const char *name) { loopi(numbones) if(bones[i].name && !strcmp(bones[i].name, name)) return i; return -1; } int findtag(const char *name) { loopv(tags) if(!strcmp(tags[i].name, name)) return i; return -1; } bool addtag(const char *name, int bone, const matrix3x4 &matrix) { if(findtag(name) >= 0) return false; tag &t = tags.add(); t.name = newstring(name); t.bone = bone; t.matrix = matrix; return true; } void calcantipodes() { antipodes.shrink(0); vector schedule; loopi(numbones) { if(bones[i].group >= numbones) { bones[i].scheduled = schedule.length(); schedule.add(i); } else bones[i].scheduled = -1; } loopv(schedule) { int bone = schedule[i]; const boneinfo &info = bones[bone]; loopj(numbones) if(abs(bones[j].group) == bone && bones[j].scheduled < 0) { antipodes.add(antipode(info.interpindex, bones[j].interpindex)); bones[j].scheduled = schedule.length(); schedule.add(j); } if(i + 1 == schedule.length()) { int conflict = INT_MAX; loopj(numbones) if(bones[j].group < numbones && bones[j].scheduled < 0) conflict = min(conflict, abs(bones[j].group)); if(conflict < numbones) { bones[conflict].scheduled = schedule.length(); schedule.add(conflict); } } } } void remapbones() { loopi(numbones) { boneinfo &info = bones[i]; info.interpindex = -1; info.ragdollindex = -1; } numgpubones = 0; loopv(users) { skelmeshgroup *group = users[i]; loopvj(group->blendcombos) { blendcombo &c = group->blendcombos[j]; loopk(4) { if(!c.weights[k]) { c.interpbones[k] = k > 0 ? c.interpbones[k-1] : 0; continue; } boneinfo &info = bones[c.bones[k]]; if(info.interpindex < 0) info.interpindex = numgpubones++; c.interpbones[k] = info.interpindex; if(info.group < 0) continue; loopl(4) { if(!c.weights[l]) break; if(l == k) continue; int parent = c.bones[l]; if(info.parent == parent || (info.parent >= 0 && info.parent == bones[parent].parent)) { info.group = -info.parent; break; } if(info.group <= parent) continue; int child = c.bones[k]; while(parent > child) parent = bones[parent].parent; if(parent != child) info.group = c.bones[l]; } } } } numinterpbones = numgpubones; loopv(tags) { boneinfo &info = bones[tags[i].bone]; if(info.interpindex < 0) info.interpindex = numinterpbones++; } if(ragdoll) { loopv(ragdoll->joints) { boneinfo &info = bones[ragdoll->joints[i].bone]; if(info.interpindex < 0) info.interpindex = numinterpbones++; info.ragdollindex = i; } } loopi(numbones) { boneinfo &info = bones[i]; if(info.interpindex < 0) continue; for(int parent = info.parent; parent >= 0 && bones[parent].interpindex < 0; parent = bones[parent].parent) bones[parent].interpindex = numinterpbones++; } loopi(numbones) { boneinfo &info = bones[i]; if(info.interpindex < 0) continue; info.interpparent = info.parent >= 0 ? bones[info.parent].interpindex : -1; } if(ragdoll) { loopi(numbones) { boneinfo &info = bones[i]; if(info.interpindex < 0 || info.ragdollindex >= 0) continue; for(int parent = info.parent; parent >= 0; parent = bones[parent].parent) { if(bones[parent].ragdollindex >= 0) { ragdoll->addreljoint(i, bones[parent].ragdollindex); break; } } } } calcantipodes(); } void addpitchdep(int bone, int frame) { for(; bone >= 0; bone = bones[bone].parent) { int pos = pitchdeps.length(); loopvj(pitchdeps) if(bone <= pitchdeps[j].bone) { if(bone == pitchdeps[j].bone) goto nextbone; pos = j; break; } { pitchdep d; d.bone = bone; d.parent = -1; d.pose = framebones[frame*numbones + bone]; pitchdeps.insert(pos, d); } nextbone:; } } int findpitchdep(int bone) { loopv(pitchdeps) if(bone <= pitchdeps[i].bone) return bone == pitchdeps[i].bone ? i : -1; return -1; } int findpitchcorrect(int bone) { loopv(pitchcorrects) if(bone <= pitchcorrects[i].bone) return bone == pitchcorrects[i].bone ? i : -1; return -1; } void initpitchdeps() { pitchdeps.setsize(0); if(pitchtargets.empty()) return; loopv(pitchtargets) { pitchtarget &t = pitchtargets[i]; t.deps = -1; addpitchdep(t.bone, t.frame); } loopv(pitchdeps) { pitchdep &d = pitchdeps[i]; int parent = bones[d.bone].parent; if(parent >= 0) { int j = findpitchdep(parent); if(j >= 0) { d.parent = j; d.pose.mul(pitchdeps[j].pose, dualquat(d.pose)); } } } loopv(pitchtargets) { pitchtarget &t = pitchtargets[i]; int j = findpitchdep(t.bone); if(j >= 0) { t.deps = j; t.pose = pitchdeps[j].pose; } t.corrects = -1; for(int parent = t.bone; parent >= 0; parent = bones[parent].parent) { t.corrects = findpitchcorrect(parent); if(t.corrects >= 0) break; } } loopv(pitchcorrects) { pitchcorrect &c = pitchcorrects[i]; bones[c.bone].correctindex = i; c.parent = -1; for(int parent = c.bone;;) { parent = bones[parent].parent; if(parent < 0) break; c.parent = findpitchcorrect(parent); if(c.parent >= 0) break; } } } void optimize() { cleanup(); if(ragdoll) ragdoll->setup(); remapbones(); initpitchdeps(); } void expandbonemask(uchar *expansion, int bone, int val) { expansion[bone] = val; bone = bones[bone].children; while(bone>=0) { expandbonemask(expansion, bone, val); bone = bones[bone].next; } } void applybonemask(ushort *mask, uchar *partmask, int partindex) { if(!mask || *mask==BONEMASK_END) return; uchar *expansion = new uchar[numbones]; memset(expansion, *mask&BONEMASK_NOT ? 1 : 0, numbones); while(*mask!=BONEMASK_END) { expandbonemask(expansion, *mask&BONEMASK_BONE, *mask&BONEMASK_NOT ? 0 : 1); mask++; } loopi(numbones) if(expansion[i]) partmask[i] = partindex; delete[] expansion; } void linkchildren() { loopi(numbones) { boneinfo &b = bones[i]; b.children = -1; if(b.parent<0) b.next = -1; else { b.next = bones[b.parent].children; bones[b.parent].children = i; } } } int maxgpuparams() const { switch(renderpath) { case R_GLSLANG: return maxvsuniforms; case R_ASMGLSLANG: case R_ASMSHADER: return maxvpenvparams; default: return 0; } } int availgpubones() const { return min(maxgpuparams() - reservevpparams - 10, maxskelanimdata) / (matskel ? 3 : 2); } bool gpuaccelerate() const { return renderpath!=R_FIXEDFUNCTION && numframes && gpuskel && numgpubones<=availgpubones(); } float calcdeviation(const vec &axis, const vec &forward, const dualquat &pose1, const dualquat &pose2) { vec forward1 = pose1.transformnormal(forward).project(axis).normalize(), forward2 = pose2.transformnormal(forward).project(axis).normalize(), daxis = vec().cross(forward1, forward2); float dx = clamp(forward1.dot(forward2), -1.0f, 1.0f), dy = clamp(daxis.magnitude(), -1.0f, 1.0f); if(daxis.dot(axis) < 0) dy = -dy; return atan2f(dy, dx)/RAD; } void calcpitchcorrects(float pitch, const vec &axis, const vec &forward) { loopv(pitchtargets) { pitchtarget &t = pitchtargets[i]; t.deviated = calcdeviation(axis, forward, t.pose, pitchdeps[t.deps].pose); } loopv(pitchcorrects) { pitchcorrect &c = pitchcorrects[i]; c.pitchangle = c.pitchtotal = 0; } loopvj(pitchtargets) { pitchtarget &t = pitchtargets[j]; float tpitch = pitch - t.deviated; for(int parent = t.corrects; parent >= 0; parent = pitchcorrects[parent].parent) tpitch -= pitchcorrects[parent].pitchangle; if(t.pitchmin || t.pitchmax) tpitch = clamp(tpitch, t.pitchmin, t.pitchmax); loopv(pitchcorrects) { pitchcorrect &c = pitchcorrects[i]; if(c.target != j) continue; float total = c.parent >= 0 ? pitchcorrects[c.parent].pitchtotal : 0, avail = tpitch - total, used = tpitch*c.pitchscale; if(c.pitchmin || c.pitchmax) { if(used < 0) used = clamp(c.pitchmin, used, 0.0f); else used = clamp(c.pitchmax, 0.0f, used); } if(used < 0) used = clamp(avail, used, 0.0f); else used = clamp(avail, 0.0f, used); c.pitchangle = used; c.pitchtotal = used + total; } } } #define INTERPBONE(bone) \ const animstate &s = as[partmask[bone]]; \ const framedata &f = partframes[partmask[bone]]; \ dualquat d; \ (d = f.fr1[bone]).mul((1-s.cur.t)*s.interp); \ d.accumulate(f.fr2[bone], s.cur.t*s.interp); \ if(s.interp<1) \ { \ d.accumulate(f.pfr1[bone], (1-s.prev.t)*(1-s.interp)); \ d.accumulate(f.pfr2[bone], s.prev.t*(1-s.interp)); \ } #define INTERPBONES(outbody, rotbody) \ sc.nextversion(); \ struct framedata \ { \ const dualquat *fr1, *fr2, *pfr1, *pfr2; \ } partframes[MAXANIMPARTS]; \ loopi(numanimparts) \ { \ partframes[i].fr1 = &framebones[as[i].cur.fr1*numbones]; \ partframes[i].fr2 = &framebones[as[i].cur.fr2*numbones]; \ if(as[i].interp<1) \ { \ partframes[i].pfr1 = &framebones[as[i].prev.fr1*numbones]; \ partframes[i].pfr2 = &framebones[as[i].prev.fr2*numbones]; \ } \ } \ loopv(pitchdeps) \ { \ pitchdep &p = pitchdeps[i]; \ INTERPBONE(p.bone); \ d.normalize(); \ if(p.parent >= 0) p.pose.mul(pitchdeps[p.parent].pose, d); \ else p.pose = d; \ } \ calcpitchcorrects(pitch, axis, forward); \ loopi(numbones) if(bones[i].interpindex>=0) \ { \ INTERPBONE(i); \ const boneinfo &b = bones[i]; \ outbody; \ float angle; \ if(b.pitchscale) { angle = b.pitchscale*pitch + b.pitchoffset; if(b.pitchmin || b.pitchmax) angle = clamp(angle, b.pitchmin, b.pitchmax); } \ else if(b.correctindex >= 0) angle = pitchcorrects[b.correctindex].pitchangle; \ else continue; \ if(as->cur.anim&ANIM_NOPITCH || (as->interp < 1 && as->prev.anim&ANIM_NOPITCH)) \ angle *= (as->cur.anim&ANIM_NOPITCH ? 0 : as->interp) + (as->interp < 1 && as->prev.anim&ANIM_NOPITCH ? 0 : 1-as->interp); \ rotbody; \ } void interpmatbones(const animstate *as, float pitch, const vec &axis, const vec &forward, int numanimparts, const uchar *partmask, skelcacheentry &sc) { if(!sc.mdata) sc.mdata = new matrix3x4[numinterpbones]; if(lastsdata == sc.mdata) lastsdata = NULL; INTERPBONES( { matrix3x4 m(d); if(b.interpparent<0) sc.mdata[b.interpindex] = m; else sc.mdata[b.interpindex].mul(sc.mdata[b.interpparent], m); }, { sc.mdata[b.interpindex].mulorient(matrix3x3(angle*RAD, axis), b.base); }); } void interpbones(const animstate *as, float pitch, const vec &axis, const vec &forward, int numanimparts, const uchar *partmask, skelcacheentry &sc) { if(!sc.bdata) sc.bdata = new dualquat[numinterpbones]; if(lastsdata == sc.bdata) lastsdata = NULL; INTERPBONES( { d.normalize(); if(b.interpparent<0) sc.bdata[b.interpindex] = d; else sc.bdata[b.interpindex].mul(sc.bdata[b.interpparent], d); }, { sc.bdata[b.interpindex].mulorient(quat(axis, angle*RAD), b.base); }); loopv(antipodes) sc.bdata[antipodes[i].child].fixantipodal(sc.bdata[antipodes[i].parent]); } #define INITRAGDOLL(ptype, pdata, relbody) \ const ptype *pdata = sc.pdata; \ loopv(ragdoll->joints) \ { \ const ragdollskel::joint &j = ragdoll->joints[i]; \ const boneinfo &b = bones[j.bone]; \ const ptype &p = pdata[b.interpindex]; \ loopk(3) if(j.vert[k] >= 0) \ { \ ragdollskel::vert &v = ragdoll->verts[j.vert[k]]; \ ragdolldata::vert &dv = d.verts[j.vert[k]]; \ dv.pos.add(p.transform(v.pos).mul(v.weight)); \ } \ } \ if(ragdoll->animjoints) loopv(ragdoll->joints) \ { \ const ragdollskel::joint &j = ragdoll->joints[i]; \ const boneinfo &b = bones[j.bone]; \ const ptype &p = pdata[b.interpindex]; \ d.calcanimjoint(i, p); \ } \ loopv(ragdoll->verts) \ { \ ragdolldata::vert &dv = d.verts[i]; \ matrixstack[matrixpos].transform(vec(dv.pos).add(p->translate).mul(p->model->scale), dv.pos); \ } \ loopv(ragdoll->reljoints) \ { \ const ragdollskel::reljoint &r = ragdoll->reljoints[i]; \ const ragdollskel::joint &j = ragdoll->joints[r.parent]; \ const boneinfo &br = bones[r.bone], &bj = bones[j.bone]; \ relbody; \ } void initmatragdoll(ragdolldata &d, skelcacheentry &sc, part *p) { INITRAGDOLL(matrix3x4, mdata, { d.reljoints[i].transposemul(mdata[bj.interpindex], mdata[br.interpindex]); }); } void initragdoll(ragdolldata &d, skelcacheentry &sc, part *p) { INITRAGDOLL(dualquat, bdata, { dualquat q = bdata[bj.interpindex]; q.invert().mul(bdata[br.interpindex]); d.reljoints[i] = matrix3x4(q); }); } #define GENRAGDOLLBONES(outbody, relbody) \ sc.nextversion(); \ loopv(ragdoll->joints) \ { \ const ragdollskel::joint &j = ragdoll->joints[i]; \ const boneinfo &b = bones[j.bone]; \ vec pos(0, 0, 0); \ loopk(3) if(j.vert[k]>=0) pos.add(d.verts[j.vert[k]].pos); \ pos.mul(j.weight/p->model->scale).sub(p->translate); \ outbody; \ } \ loopv(ragdoll->reljoints) \ { \ const ragdollskel::reljoint &r = ragdoll->reljoints[i]; \ const ragdollskel::joint &j = ragdoll->joints[r.parent]; \ const boneinfo &br = bones[r.bone], &bj = bones[j.bone]; \ relbody; \ } void genmatragdollbones(ragdolldata &d, skelcacheentry &sc, part *p) { if(!sc.mdata) sc.mdata = new matrix3x4[numinterpbones]; if(lastsdata == sc.mdata) lastsdata = NULL; GENRAGDOLLBONES( { sc.mdata[b.interpindex].transposemul(d.tris[j.tri], pos, d.animjoints ? d.animjoints[i] : j.orient); }, { sc.mdata[br.interpindex].mul(sc.mdata[bj.interpindex], d.reljoints[i]); }); } void genragdollbones(ragdolldata &d, skelcacheentry &sc, part *p) { if(!sc.bdata) sc.bdata = new dualquat[numinterpbones]; if(lastsdata == sc.bdata) lastsdata = NULL; GENRAGDOLLBONES( { matrix3x4 m; m.transposemul(d.tris[j.tri], pos, d.animjoints ? d.animjoints[i] : j.orient); sc.bdata[b.interpindex] = dualquat(m); }, { sc.bdata[br.interpindex].mul(sc.bdata[bj.interpindex], dualquat(d.reljoints[i])); }); loopv(antipodes) sc.bdata[antipodes[i].child].fixantipodal(sc.bdata[antipodes[i].parent]); } void concattagtransform(part *p, int frame, int i, const matrix3x4 &m, matrix3x4 &n) { matrix3x4 t; t.mul(bones[tags[i].bone].base, tags[i].matrix); t.translate(vec(p->translate).mul(p->model->scale)); n.mul(m, t); } void calctags(part *p, skelcacheentry *sc = NULL) { loopv(p->links) { linkedpart &l = p->links[i]; tag &t = tags[l.tag]; matrix3x4 m; m.mul(bones[t.bone].base, t.matrix); if(sc) { int interpindex = bones[t.bone].interpindex; m.mul(usematskel ? sc->mdata[interpindex] : sc->bdata[interpindex], matrix3x4(m)); } l.matrix = m; l.matrix[12] = (l.matrix[12] + p->translate.x) * p->model->scale; l.matrix[13] = (l.matrix[13] + p->translate.y) * p->model->scale; l.matrix[14] = (l.matrix[14] + p->translate.z) * p->model->scale; } } void cleanup(bool full = true) { loopv(skelcache) { skelcacheentry &sc = skelcache[i]; loopj(MAXANIMPARTS) sc.as[j].cur.fr1 = -1; DELETEA(sc.bdata); DELETEA(sc.mdata); } skelcache.setsize(0); blendoffsets.clear(); lastsdata = lastbdata = NULL; if(full) loopv(users) users[i]->cleanup(); } bool canpreload() { return !numframes || gpuaccelerate(); } void preload() { if(!numframes) return; if(skelcache.empty()) { usegpuskel = gpuaccelerate(); usematskel = matskel!=0; } } skelcacheentry &checkskelcache(part *p, const animstate *as, float pitch, const vec &axis, const vec &forward, ragdolldata *rdata) { if(skelcache.empty()) { usegpuskel = gpuaccelerate(); usematskel = matskel!=0; } int numanimparts = ((skelpart *)as->owner)->numanimparts; uchar *partmask = ((skelpart *)as->owner)->partmask; skelcacheentry *sc = NULL; bool match = false; loopv(skelcache) { skelcacheentry &c = skelcache[i]; loopj(numanimparts) if(c.as[j]!=as[j]) goto mismatch; if(c.pitch != pitch || c.partmask != partmask || c.ragdoll != rdata || (rdata && c.millis < rdata->lastmove)) goto mismatch; match = true; sc = &c; break; mismatch: if(c.millis < lastmillis) { sc = &c; break; } } if(!sc) sc = &skelcache.add(); if(!match) { loopi(numanimparts) sc->as[i] = as[i]; sc->pitch = pitch; sc->partmask = partmask; sc->ragdoll = rdata; if(rdata) { if(matskel) genmatragdollbones(*rdata, *sc, p); else genragdollbones(*rdata, *sc, p); } else if(matskel) interpmatbones(as, pitch, axis, forward, numanimparts, partmask, *sc); else interpbones(as, pitch, axis, forward, numanimparts, partmask, *sc); } sc->millis = lastmillis; return *sc; } void setasmbones(skelcacheentry &sc, int count = 0) { if(sc.dirty) sc.dirty = false; else if((count ? lastbdata : lastsdata) == (usematskel ? (void *)sc.mdata : (void *)sc.bdata)) return; int offset = count ? numgpubones : 0; if(!offset) count = numgpubones; if(hasPP) { if(usematskel) glProgramEnvParameters4fv_(GL_VERTEX_PROGRAM_ARB, 10 + 3*offset, 3*count, sc.mdata[0].a.v); else glProgramEnvParameters4fv_(GL_VERTEX_PROGRAM_ARB, 10 + 2*offset, 2*count, sc.bdata[0].real.v); } else if(usematskel) loopi(count) { glProgramEnvParameter4fvARB_(GL_VERTEX_PROGRAM_ARB, 10 + 3*(offset+i), sc.mdata[i].a.v); glProgramEnvParameter4fvARB_(GL_VERTEX_PROGRAM_ARB, 11 + 3*(offset+i), sc.mdata[i].b.v); glProgramEnvParameter4fvARB_(GL_VERTEX_PROGRAM_ARB, 12 + 3*(offset+i), sc.mdata[i].c.v); } else loopi(count) { glProgramEnvParameter4fvARB_(GL_VERTEX_PROGRAM_ARB, 10 + 2*(offset+i), sc.bdata[i].real.v); glProgramEnvParameter4fvARB_(GL_VERTEX_PROGRAM_ARB, 11 + 2*(offset+i), sc.bdata[i].dual.v); } if(offset) lastbdata = usematskel ? (void *)sc.mdata : (void *)sc.bdata; else lastsdata = usematskel ? (void *)sc.mdata : (void *)sc.bdata; } int getblendoffset(UniformLoc &u) { int &offset = blendoffsets.access(Shader::lastshader->program, -1); if(offset < 0) { defformatstring(offsetname)("%s[%d]", u.name, (usematskel ? 3 : 2)*numgpubones); offset = glGetUniformLocation_(Shader::lastshader->program, offsetname); } return offset; } void setglslbones(UniformLoc &u, skelcacheentry &sc, skelcacheentry &bc, int count) { if(u.version == bc.version && u.data == (usematskel ? (void *)bc.mdata : (void *)bc.bdata)) return; if(usematskel) { glUniform4fv_(u.loc, 3*numgpubones, sc.mdata[0].a.v); if(count > 0) { int offset = getblendoffset(u); if(offset >= 0) glUniform4fv_(offset, 3*count, bc.mdata[0].a.v); } } else { glUniform4fv_(u.loc, 2*numgpubones, sc.bdata[0].real.v); if(count > 0) { int offset = getblendoffset(u); if(offset >= 0) glUniform4fv_(offset, 2*count, bc.bdata[0].real.v); } } u.version = bc.version; u.data = usematskel ? (void *)bc.mdata : (void *)bc.bdata; } void setgpubones(skelcacheentry &sc, blendcacheentry *bc, int count) { if(!Shader::lastshader) return; if(Shader::lastshader->type & SHADER_GLSLANG) { if(Shader::lastshader->uniformlocs.length() < 1) return; UniformLoc &u = Shader::lastshader->uniformlocs[0]; setglslbones(u, sc, bc ? *bc : sc, count); } else { setasmbones(sc); if(bc) setasmbones(*bc, count); } } bool shouldcleanup() const { return numframes && (skelcache.empty() || gpuaccelerate()!=usegpuskel || (matskel!=0)!=usematskel); } }; struct skelmeshgroup : meshgroup { skeleton *skel; vector blendcombos; int numblends[4]; static const int MAXBLENDCACHE = 16; blendcacheentry blendcache[MAXBLENDCACHE]; static const int MAXVBOCACHE = 16; vbocacheentry vbocache[MAXVBOCACHE]; ushort *edata; GLuint ebuf; bool vnorms, vtangents; int vlen, vertsize, vblends, vweights; uchar *vdata; skelmeshgroup() : skel(NULL), edata(NULL), ebuf(0), vnorms(false), vtangents(false), vlen(0), vertsize(0), vblends(0), vweights(0), vdata(NULL) { memset(numblends, 0, sizeof(numblends)); } virtual ~skelmeshgroup() { if(skel) { if(skel->shared) skel->users.removeobj(this); else DELETEP(skel); } if(ebuf) glDeleteBuffers_(1, &ebuf); loopi(MAXBLENDCACHE) { DELETEA(blendcache[i].bdata); DELETEA(blendcache[i].mdata); } loopi(MAXVBOCACHE) { DELETEA(vbocache[i].vdata); if(vbocache[i].vbuf) glDeleteBuffers_(1, &vbocache[i].vbuf); } DELETEA(vdata); } void shareskeleton(char *name) { if(!name) { skel = new skeleton; skel->users.add(this); return; } static hashtable skeletons; if(skeletons.access(name)) skel = skeletons[name]; else { skel = new skeleton; skel->name = newstring(name); skeletons[skel->name] = skel; } skel->users.add(this); skel->shared++; } int findtag(const char *name) { return skel->findtag(name); } int totalframes() const { return max(skel->numframes, 1); } virtual skelanimspec *loadanim(const char *filename) { return NULL; } void genvbo(bool norms, bool tangents, vbocacheentry &vc) { if(hasVBO) { if(!vc.vbuf) glGenBuffers_(1, &vc.vbuf); if(ebuf) return; } else if(edata) { #define ALLOCVDATA(vdata) \ do \ { \ DELETEA(vdata); \ vdata = new uchar[vlen*vertsize]; \ loopv(meshes) \ { \ skelmesh &m = *(skelmesh *)meshes[i]; \ m.filltc(vdata, vertsize); \ if(tangents) m.fillbump(vdata, vertsize); \ } \ } while(0) if(!vc.vdata) ALLOCVDATA(vc.vdata); return; } vector idxs; vnorms = norms; vtangents = tangents; vlen = 0; vblends = 0; if(skel->numframes && !skel->usegpuskel) { vweights = 1; loopv(blendcombos) { blendcombo &c = blendcombos[i]; c.interpindex = c.weights[1] ? skel->numgpubones + vblends++ : -1; } vertsize = tangents ? sizeof(vvertbump) : (norms ? sizeof(vvertn) : sizeof(vvert)); loopv(meshes) vlen += ((skelmesh *)meshes[i])->genvbo(idxs, vlen); DELETEA(vdata); if(hasVBO) ALLOCVDATA(vdata); else ALLOCVDATA(vc.vdata); } else { if(skel->numframes) { vweights = 4; int availbones = skel->availgpubones() - skel->numgpubones; while(vweights > 1 && availbones >= numblends[vweights-1]) availbones -= numblends[--vweights]; loopv(blendcombos) { blendcombo &c = blendcombos[i]; c.interpindex = c.size() > vweights ? skel->numgpubones + vblends++ : -1; } } else { vweights = 0; loopv(blendcombos) blendcombos[i].interpindex = -1; } if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, vc.vbuf); #define GENVBO(type, args) \ do \ { \ vertsize = sizeof(type); \ vector vverts; \ loopv(meshes) vlen += ((skelmesh *)meshes[i])->genvbo args; \ if(hasVBO) glBufferData_(GL_ARRAY_BUFFER_ARB, vverts.length()*sizeof(type), vverts.getbuf(), GL_STATIC_DRAW_ARB); \ else \ { \ DELETEA(vc.vdata); \ vc.vdata = new uchar[vverts.length()*sizeof(type)]; \ memcpy(vc.vdata, vverts.getbuf(), vverts.length()*sizeof(type)); \ } \ } while(0) #define GENVBOANIM(type) GENVBO(type, (idxs, vlen, vverts)) #define GENVBOSTAT(type) GENVBO(type, (idxs, vlen, vverts, htdata, htlen)) if(skel->numframes) { if(tangents) GENVBOANIM(vvertbumpw); else GENVBOANIM(vvertw); } else { int numverts = 0, htlen = 128; loopv(meshes) numverts += ((skelmesh *)meshes[i])->numverts; while(htlen < numverts) htlen *= 2; if(numverts*4 > htlen*3) htlen *= 2; int *htdata = new int[htlen]; memset(htdata, -1, htlen*sizeof(int)); if(tangents) GENVBOSTAT(vvertbump); else if(norms) GENVBOSTAT(vvertn); else GENVBOSTAT(vvert); delete[] htdata; } if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); } if(hasVBO) { glGenBuffers_(1, &ebuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, ebuf); glBufferData_(GL_ELEMENT_ARRAY_BUFFER_ARB, idxs.length()*sizeof(ushort), idxs.getbuf(), GL_STATIC_DRAW_ARB); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } else { edata = new ushort[idxs.length()]; memcpy(edata, idxs.getbuf(), idxs.length()*sizeof(ushort)); } #undef GENVBO #undef GENVBOANIM #undef GENVBOSTAT #undef ALLOCVDATA } void bindvbo(const animstate *as, vbocacheentry &vc, skelcacheentry *sc = NULL, blendcacheentry *bc = NULL) { vvertn *vverts = hasVBO ? 0 : (vvertn *)vc.vdata; if(hasVBO && lastebuf!=ebuf) { glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, ebuf); lastebuf = ebuf; } if(lastvbuf != (hasVBO ? (void *)(size_t)vc.vbuf : vc.vdata)) { if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, vc.vbuf); if(!lastvbuf) glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, vertsize, &vverts->pos); lastvbuf = hasVBO ? (void *)(size_t)vc.vbuf : vc.vdata; } if(as->cur.anim&ANIM_NOSKIN) { if(enabletc) disabletc(); if(enablenormals) disablenormals(); } else { if(vnorms || vtangents) { if(!enablenormals) { glEnableClientState(GL_NORMAL_ARRAY); enablenormals = true; } if(lastnbuf!=lastvbuf) { glNormalPointer(GL_FLOAT, vertsize, &vverts->norm); lastnbuf = lastvbuf; } } else if(enablenormals) disablenormals(); if(!enabletc) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); enabletc = true; } if(lasttcbuf!=lastvbuf) { glTexCoordPointer(2, GL_FLOAT, vertsize, &vverts->u); lasttcbuf = lastvbuf; } } if(!sc || !skel->usegpuskel) { if(enablebones) disablebones(); return; } if(!enablebones) { glEnableVertexAttribArray_(6); glEnableVertexAttribArray_(7); enablebones = true; } if(lastbbuf!=lastvbuf) { glVertexAttribPointer_(6, 4, GL_UNSIGNED_BYTE, GL_TRUE, vertsize, &((vvertw *)vverts)->weights); glVertexAttribPointer_(7, 4, GL_UNSIGNED_BYTE, GL_FALSE, vertsize, &((vvertw *)vverts)->bones); lastbbuf = lastvbuf; } } void concattagtransform(part *p, int frame, int i, const matrix3x4 &m, matrix3x4 &n) { skel->concattagtransform(p, frame, i, m, n); } int addblendcombo(const blendcombo &c) { loopv(blendcombos) if(blendcombos[i]==c) { blendcombos[i].uses += c.uses; return i; } numblends[c.size()-1]++; blendcombo &a = blendcombos.add(c); return a.interpindex = blendcombos.length()-1; } void sortblendcombos() { blendcombos.sort(blendcombo::sortcmp); int *remap = new int[blendcombos.length()]; loopv(blendcombos) remap[blendcombos[i].interpindex] = i; loopv(meshes) { skelmesh *m = (skelmesh *)meshes[i]; loopj(m->numverts) { vert &v = m->verts[j]; v.blend = remap[v.blend]; } } delete[] remap; } int remapblend(int blend) { const blendcombo &c = blendcombos[blend]; return c.weights[1] ? c.interpindex : c.interpbones[0]; } template static inline void blendbones(B &d, const B *bdata, const blendcombo &c) { d = bdata[c.interpbones[0]]; d.mul(c.weights[0]); d.accumulate(bdata[c.interpbones[1]], c.weights[1]); if(c.weights[2]) { d.accumulate(bdata[c.interpbones[2]], c.weights[2]); if(c.weights[3]) d.accumulate(bdata[c.interpbones[3]], c.weights[3]); } } void blendmatbones(const skelcacheentry &sc, blendcacheentry &bc) { bc.nextversion(); if(!bc.mdata) bc.mdata = new matrix3x4[vblends]; if(lastbdata == bc.mdata) lastbdata = NULL; matrix3x4 *dst = bc.mdata - skel->numgpubones; loopv(blendcombos) { const blendcombo &c = blendcombos[i]; if(c.interpindex<0) break; blendbones(dst[c.interpindex], sc.mdata, c); } } void blendbones(const skelcacheentry &sc, blendcacheentry &bc) { bc.nextversion(); if(!bc.bdata) bc.bdata = new dualquat[vblends]; if(lastbdata == bc.bdata) lastbdata = NULL; dualquat *dst = bc.bdata - skel->numgpubones; bool normalize = !skel->usegpuskel || vweights<=1; loopv(blendcombos) { const blendcombo &c = blendcombos[i]; if(c.interpindex<0) break; dualquat &d = dst[c.interpindex]; blendbones(d, sc.bdata, c); if(normalize) d.normalize(); } } void cleanup() { loopi(MAXBLENDCACHE) { blendcacheentry &c = blendcache[i]; DELETEA(c.bdata); DELETEA(c.mdata); c.owner = -1; } loopi(MAXVBOCACHE) { vbocacheentry &c = vbocache[i]; if(c.vbuf) { glDeleteBuffers_(1, &c.vbuf); c.vbuf = 0; } DELETEA(c.vdata); c.owner = -1; } if(hasVBO) { if(ebuf) { glDeleteBuffers_(1, &ebuf); ebuf = 0; } } else DELETEA(vdata); if(skel) skel->cleanup(false); } #define SEARCHCACHE(cachesize, cacheentry, cache, reusecheck) \ loopi(cachesize) \ { \ cacheentry &c = cache[i]; \ if(c.owner==owner) \ { \ if(c==sc) return c; \ else c.owner = -1; \ break; \ } \ } \ loopi(cachesize-1) \ { \ cacheentry &c = cache[i]; \ if(reusecheck c.owner < 0 || c.millis < lastmillis) \ return c; \ } \ return cache[cachesize-1]; vbocacheentry &checkvbocache(skelcacheentry &sc, int owner) { SEARCHCACHE(MAXVBOCACHE, vbocacheentry, vbocache, (hasVBO ? !c.vbuf : !c.vdata) || ); } blendcacheentry &checkblendcache(skelcacheentry &sc, int owner) { SEARCHCACHE(MAXBLENDCACHE, blendcacheentry, blendcache, ) } void preload(part *p) { if(!skel->canpreload()) return; bool norms = false, tangents = false; loopv(p->skins) { if(p->skins[i].normals()) norms = true; if(p->skins[i].tangents()) tangents = true; } if(skel->shouldcleanup()) skel->cleanup(); else if(norms!=vnorms || tangents!=vtangents) cleanup(); skel->preload(); if(hasVBO ? !vbocache->vbuf : !vbocache->vdata) genvbo(norms, tangents, *vbocache); } void render(const animstate *as, float pitch, const vec &axis, const vec &forward, dynent *d, part *p) { bool norms = false, tangents = false; loopv(p->skins) { if(p->skins[i].normals()) norms = true; if(p->skins[i].tangents()) tangents = true; } if(skel->shouldcleanup()) { skel->cleanup(); disablevbo(); } else if(norms!=vnorms || tangents!=vtangents) { cleanup(); disablevbo(); } if(!skel->numframes) { if(!(as->cur.anim&ANIM_NORENDER)) { if(hasVBO ? !vbocache->vbuf : !vbocache->vdata) genvbo(norms, tangents, *vbocache); bindvbo(as, *vbocache); loopv(meshes) { skelmesh *m = (skelmesh *)meshes[i]; p->skins[i].bind(m, as); m->render(as, p->skins[i], *vbocache); } } skel->calctags(p); return; } skelcacheentry &sc = skel->checkskelcache(p, as, pitch, axis, forward, as->cur.anim&ANIM_RAGDOLL || !d || !d->ragdoll || d->ragdoll->skel != skel->ragdoll ? NULL : d->ragdoll); if(!(as->cur.anim&ANIM_NORENDER)) { int owner = &sc-&skel->skelcache[0]; vbocacheentry &vc = skel->usegpuskel ? *vbocache : checkvbocache(sc, owner); vc.millis = lastmillis; if(hasVBO ? !vc.vbuf : !vc.vdata) genvbo(norms, tangents, vc); blendcacheentry *bc = NULL; if(vblends) { bc = &checkblendcache(sc, owner); bc->millis = lastmillis; if(bc->owner!=owner) { bc->owner = owner; *(animcacheentry *)bc = sc; if(skel->usematskel) blendmatbones(sc, *bc); else blendbones(sc, *bc); } } if(!skel->usegpuskel && vc.owner!=owner) { vc.owner = owner; (animcacheentry &)vc = sc; loopv(meshes) { skelmesh &m = *(skelmesh *)meshes[i]; if(skel->usematskel) m.interpverts(sc.mdata, bc ? bc->mdata : NULL, norms, tangents, (hasVBO ? vdata : vc.vdata) + m.voffset*vertsize, p->skins[i]); else m.interpverts(sc.bdata, bc ? bc->bdata : NULL, norms, tangents, (hasVBO ? vdata : vc.vdata) + m.voffset*vertsize, p->skins[i]); } if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, vc.vbuf); glBufferData_(GL_ARRAY_BUFFER_ARB, vlen*vertsize, vdata, GL_STREAM_DRAW_ARB); } } bindvbo(as, vc, &sc, bc); loopv(meshes) { skelmesh *m = (skelmesh *)meshes[i]; p->skins[i].bind(m, as); if(skel->usegpuskel) skel->setgpubones(sc, bc, vblends); m->render(as, p->skins[i], vc); } } skel->calctags(p, &sc); if(as->cur.anim&ANIM_RAGDOLL && skel->ragdoll && !d->ragdoll) { d->ragdoll = new ragdolldata(skel->ragdoll, p->model->scale); if(matskel) skel->initmatragdoll(*d->ragdoll, sc, p); else skel->initragdoll(*d->ragdoll, sc, p); d->ragdoll->init(d); } } }; struct animpartmask { animpartmask *next; int numbones; uchar bones[1]; }; struct skelpart : part { animpartmask *buildingpartmask; uchar *partmask; skelpart() : buildingpartmask(NULL), partmask(NULL) { } virtual ~skelpart() { DELETEA(buildingpartmask); } uchar *sharepartmask(animpartmask *o) { static animpartmask *partmasks = NULL; animpartmask *p = partmasks; for(; p; p = p->next) if(p->numbones==o->numbones && !memcmp(p->bones, o->bones, p->numbones)) { delete[] (uchar *)o; return p->bones; } o->next = p; partmasks = o; return o->bones; } animpartmask *newpartmask() { animpartmask *p = (animpartmask *)new uchar[sizeof(animpartmask) + ((skelmeshgroup *)meshes)->skel->numbones-1]; p->numbones = ((skelmeshgroup *)meshes)->skel->numbones; memset(p->bones, 0, p->numbones); return p; } void initanimparts() { DELETEA(buildingpartmask); buildingpartmask = newpartmask(); } bool addanimpart(ushort *bonemask) { if(!buildingpartmask || numanimparts>=MAXANIMPARTS) return false; ((skelmeshgroup *)meshes)->skel->applybonemask(bonemask, buildingpartmask->bones, numanimparts); numanimparts++; return true; } void endanimparts() { if(buildingpartmask) { partmask = sharepartmask(buildingpartmask); buildingpartmask = NULL; } ((skelmeshgroup *)meshes)->skel->optimize(); } }; skelmodel(const char *name) : animmodel(name) { } int linktype(animmodel *m) const { return type()==m->type() && ((skelmeshgroup *)parts[0]->meshes)->skel == ((skelmeshgroup *)m->parts[0]->meshes)->skel ? LINK_REUSE : LINK_TAG; } bool skeletal() const { return true; } }; struct skeladjustment { float yaw, pitch, roll; vec translate; skeladjustment(float yaw, float pitch, float roll, const vec &translate) : yaw(yaw), pitch(pitch), roll(roll), translate(translate) {} void adjust(dualquat &dq) { if(yaw) dq.mulorient(quat(vec(0, 0, 1), yaw*RAD)); if(pitch) dq.mulorient(quat(vec(0, -1, 0), pitch*RAD)); if(roll) dq.mulorient(quat(vec(-1, 0, 0), roll*RAD)); if(!translate.iszero()) dq.translate(translate); } }; template struct skelloader : modelloader { static vector adjustments; }; template vector skelloader::adjustments; template struct skelcommands : modelcommands { typedef modelcommands commands; typedef struct MDL::skeleton skeleton; typedef struct MDL::skelmeshgroup meshgroup; typedef struct MDL::skelpart part; typedef struct MDL::skin skin; typedef struct MDL::boneinfo boneinfo; typedef struct MDL::skelanimspec animspec; typedef struct MDL::pitchdep pitchdep; typedef struct MDL::pitchtarget pitchtarget; typedef struct MDL::pitchcorrect pitchcorrect; static void loadpart(char *meshfile, char *skelname, float *smooth) { if(!MDL::loading) { conoutf("not loading an %s", MDL::formatname()); return; } defformatstring(filename)("%s/%s", MDL::dir, meshfile); part &mdl = *new part; MDL::loading->parts.add(&mdl); mdl.model = MDL::loading; mdl.index = MDL::loading->parts.length()-1; mdl.pitchscale = mdl.pitchoffset = mdl.pitchmin = mdl.pitchmax = 0; MDL::adjustments.setsize(0); mdl.meshes = MDL::loading->sharemeshes(path(filename), skelname[0] ? skelname : NULL, double(*smooth > 0 ? cos(clamp(*smooth, 0.0f, 180.0f)*RAD) : 2)); if(!mdl.meshes) conoutf("could not load %s", filename); else { mdl.initanimparts(); mdl.initskins(); } } static void settag(char *name, char *tagname, float *tx, float *ty, float *tz, float *rx, float *ry, float *rz) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } part &mdl = *(part *)MDL::loading->parts.last(); int i = mdl.meshes ? ((meshgroup *)mdl.meshes)->skel->findbone(name) : -1; if(i >= 0) { float cx = *rx ? cosf(*rx/2*RAD) : 1, sx = *rx ? sinf(*rx/2*RAD) : 0, cy = *ry ? cosf(*ry/2*RAD) : 1, sy = *ry ? sinf(*ry/2*RAD) : 0, cz = *rz ? cosf(*rz/2*RAD) : 1, sz = *rz ? sinf(*rz/2*RAD) : 0; matrix3x4 m(matrix3x3(quat(sx*cy*cz - cx*sy*sz, cx*sy*cz + sx*cy*sz, cx*cy*sz - sx*sy*cz, cx*cy*cz + sx*sy*sz)), vec(*tx, *ty, *tz)); ((meshgroup *)mdl.meshes)->skel->addtag(tagname, i, m); return; } conoutf("could not find bone %s for tag %s", name, tagname); } static void setpitch(char *name, float *pitchscale, float *pitchoffset, float *pitchmin, float *pitchmax) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } part &mdl = *(part *)MDL::loading->parts.last(); if(name[0]) { int i = mdl.meshes ? ((meshgroup *)mdl.meshes)->skel->findbone(name) : -1; if(i>=0) { boneinfo &b = ((meshgroup *)mdl.meshes)->skel->bones[i]; b.pitchscale = *pitchscale; b.pitchoffset = *pitchoffset; if(*pitchmin || *pitchmax) { b.pitchmin = *pitchmin; b.pitchmax = *pitchmax; } else { b.pitchmin = -360*fabs(b.pitchscale) + b.pitchoffset; b.pitchmax = 360*fabs(b.pitchscale) + b.pitchoffset; } return; } conoutf("could not find bone %s to pitch", name); return; } mdl.pitchscale = *pitchscale; mdl.pitchoffset = *pitchoffset; if(*pitchmin || *pitchmax) { mdl.pitchmin = *pitchmin; mdl.pitchmax = *pitchmax; } else { mdl.pitchmin = -360*fabs(mdl.pitchscale) + mdl.pitchoffset; mdl.pitchmax = 360*fabs(mdl.pitchscale) + mdl.pitchoffset; } } static void setpitchtarget(char *name, char *animfile, int *frameoffset, float *pitchmin, float *pitchmax) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("\frnot loading an %s", MDL::formatname()); return; } part &mdl = *(part *)MDL::loading->parts.last(); if(!mdl.meshes) return; defformatstring(filename)("%s/%s", MDL::dir, animfile); animspec *sa = ((meshgroup *)mdl.meshes)->loadanim(path(filename)); if(!sa) { conoutf("\frcould not load %s anim file %s", MDL::formatname(), filename); return; } skeleton *skel = ((meshgroup *)mdl.meshes)->skel; int bone = skel ? skel->findbone(name) : -1; if(bone < 0) { conoutf("\frcould not find bone %s to pitch target", name); return; } loopv(skel->pitchtargets) if(skel->pitchtargets[i].bone == bone) return; pitchtarget &t = skel->pitchtargets.add(); t.bone = bone; t.frame = sa->frame + clamp(*frameoffset, 0, sa->range-1); t.pitchmin = *pitchmin; t.pitchmax = *pitchmax; } static void setpitchcorrect(char *name, char *targetname, float *scale, float *pitchmin, float *pitchmax) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("\frnot loading an %s", MDL::formatname()); return; } part &mdl = *(part *)MDL::loading->parts.last(); if(!mdl.meshes) return; skeleton *skel = ((meshgroup *)mdl.meshes)->skel; int bone = skel ? skel->findbone(name) : -1; if(bone < 0) { conoutf("\frcould not find bone %s to pitch correct", name); return; } if(skel->findpitchcorrect(bone) >= 0) return; int targetbone = skel->findbone(targetname), target = -1; if(targetbone >= 0) loopv(skel->pitchtargets) if(skel->pitchtargets[i].bone == targetbone) { target = i; break; } if(target < 0) { conoutf("\frcould not find pitch target %s to pitch correct %s", targetname, name); return; } pitchcorrect c; c.bone = bone; c.target = target; c.pitchmin = *pitchmin; c.pitchmax = *pitchmax; c.pitchscale = *scale; int pos = skel->pitchcorrects.length(); loopv(skel->pitchcorrects) if(bone <= skel->pitchcorrects[i].bone) { pos = i; break; break; } skel->pitchcorrects.insert(pos, c); } static void setanim(char *anim, char *animfile, float *speed, int *priority, int *startoffset, int *endoffset) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } vector anims; findanims(anim, anims); if(anims.empty()) conoutf("could not find animation %s", anim); else { part *p = (part *)MDL::loading->parts.last(); if(!p->meshes) return; defformatstring(filename)("%s/%s", MDL::dir, animfile); animspec *sa = ((meshgroup *)p->meshes)->loadanim(path(filename)); if(!sa) conoutf("could not load %s anim file %s", MDL::formatname(), filename); else loopv(anims) { int start = sa->frame, end = sa->range; if(*startoffset > 0) start += min(*startoffset, end-1); else if(*startoffset < 0) start += max(end + *startoffset, 0); end -= start - sa->frame; if(*endoffset > 0) end = min(end, *endoffset); else if(*endoffset < 0) end = max(end + *endoffset, 1); MDL::loading->parts.last()->setanim(p->numanimparts-1, anims[i], start, end, *speed, *priority); } } } static void setanimpart(char *maskstr) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } part *p = (part *)MDL::loading->parts.last(); vector bonestrs; explodelist(maskstr, bonestrs); vector bonemask; loopv(bonestrs) { char *bonestr = bonestrs[i]; int bone = p->meshes ? ((meshgroup *)p->meshes)->skel->findbone(bonestr[0]=='!' ? bonestr+1 : bonestr) : -1; if(bone<0) { conoutf("could not find bone %s for anim part mask [%s]", bonestr, maskstr); bonestrs.deletearrays(); return; } bonemask.add(bone | (bonestr[0]=='!' ? BONEMASK_NOT : 0)); } bonestrs.deletearrays(); bonemask.sort(); if(bonemask.length()) bonemask.add(BONEMASK_END); if(!p->addanimpart(bonemask.getbuf())) conoutf("too many animation parts"); } static void setadjust(char *name, float *yaw, float *pitch, float *roll, float *tx, float *ty, float *tz) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } part &mdl = *(part *)MDL::loading->parts.last(); if(!name[0]) return; int i = mdl.meshes ? ((meshgroup *)mdl.meshes)->skel->findbone(name) : -1; if(i < 0) { conoutf("could not find bone %s to adjust", name); return; } while(!MDL::adjustments.inrange(i)) MDL::adjustments.add(skeladjustment(0, 0, 0, vec(0, 0, 0))); MDL::adjustments[i] = skeladjustment(*yaw, *pitch, *roll, vec(*tx/4, *ty/4, *tz/4)); } skelcommands() { if(MDL::multiparted()) this->modelcommand(loadpart, "load", "ssf"); this->modelcommand(settag, "tag", "ssffffff"); this->modelcommand(setpitch, "pitch", "sffff"); this->modelcommand(setpitchtarget, "pitchtarget", "ssiff"); this->modelcommand(setpitchcorrect, "pitchcorrect", "ssfff"); if(MDL::animated()) { this->modelcommand(setanim, "anim", "ssfiii"); this->modelcommand(setanimpart, "animpart", "s"); this->modelcommand(setadjust, "adjust", "sffffff"); } } }; sauerbraten-0.0.20130203.dfsg/engine/octarender.cpp0000644000175000017500000016412012073615006021500 0ustar vincentvincent// octarender.cpp: fill vertex arrays with different cube surfaces. #include "engine.h" struct vboinfo { int uses; uchar *data; }; hashtable vbos; VAR(printvbo, 0, 0, 1); VARFN(vbosize, maxvbosize, 0, 1<<14, 1<<16, allchanged()); enum { VBO_VBUF = 0, VBO_EBUF, VBO_SKYBUF, NUMVBO }; static vector vbodata[NUMVBO]; static vector vbovas[NUMVBO]; static int vbosize[NUMVBO]; void destroyvbo(GLuint vbo) { vboinfo *exists = vbos.access(vbo); if(!exists) return; vboinfo &vbi = *exists; if(vbi.uses <= 0) return; vbi.uses--; if(!vbi.uses) { if(hasVBO) glDeleteBuffers_(1, &vbo); else if(vbi.data) delete[] vbi.data; vbos.remove(vbo); } } void genvbo(int type, void *buf, int len, vtxarray **vas, int numva) { GLuint vbo; uchar *data = NULL; if(hasVBO) { glGenBuffers_(1, &vbo); GLenum target = type==VBO_VBUF ? GL_ARRAY_BUFFER_ARB : GL_ELEMENT_ARRAY_BUFFER_ARB; glBindBuffer_(target, vbo); glBufferData_(target, len, buf, GL_STATIC_DRAW_ARB); glBindBuffer_(target, 0); } else { static GLuint nextvbo = 0; if(!nextvbo) nextvbo++; // just in case it ever wraps around vbo = nextvbo++; data = new uchar[len]; memcpy(data, buf, len); } vboinfo &vbi = vbos[vbo]; vbi.uses = numva; vbi.data = data; if(printvbo) conoutf(CON_DEBUG, "vbo %d: type %d, size %d, %d uses", vbo, type, len, numva); loopi(numva) { vtxarray *va = vas[i]; switch(type) { case VBO_VBUF: va->vbuf = vbo; if(!hasVBO) va->vdata = (vertex *)(data + (size_t)va->vdata); break; case VBO_EBUF: va->ebuf = vbo; if(!hasVBO) va->edata = (ushort *)(data + (size_t)va->edata); break; case VBO_SKYBUF: va->skybuf = vbo; if(!hasVBO) va->skydata = (ushort *)(data + (size_t)va->skydata); break; } } } bool readva(vtxarray *va, ushort *&edata, uchar *&vdata) { if(!va->vbuf || !va->ebuf) return false; edata = new ushort[3*va->tris]; vdata = new uchar[va->verts*VTXSIZE]; if(hasVBO) { glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->ebuf); glGetBufferSubData_(GL_ELEMENT_ARRAY_BUFFER_ARB, (size_t)va->edata, 3*va->tris*sizeof(ushort), edata); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glGetBufferSubData_(GL_ARRAY_BUFFER_ARB, va->voffset*VTXSIZE, va->verts*VTXSIZE, vdata); glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); return true; } else { memcpy(edata, va->edata, 3*va->tris*sizeof(ushort)); memcpy(vdata, (uchar *)va->vdata + va->voffset*VTXSIZE, va->verts*VTXSIZE); return true; } } void flushvbo(int type = -1) { if(type < 0) { loopi(NUMVBO) flushvbo(i); return; } vector &data = vbodata[type]; if(data.empty()) return; vector &vas = vbovas[type]; genvbo(type, data.getbuf(), data.length(), vas.getbuf(), vas.length()); data.setsize(0); vas.setsize(0); vbosize[type] = 0; } uchar *addvbo(vtxarray *va, int type, int numelems, int elemsize) { vbosize[type] += numelems; vector &data = vbodata[type]; vector &vas = vbovas[type]; vas.add(va); int len = numelems*elemsize; uchar *buf = data.reserve(len).buf; data.advance(len); return buf; } struct verthash { static const int SIZE = 1<<13; int table[SIZE]; vector verts; vector chain; verthash() { clearverts(); } void clearverts() { memset(table, -1, sizeof(table)); chain.setsize(0); verts.setsize(0); } int addvert(const vertex &v) { uint h = hthash(v.pos)&(SIZE-1); for(int i = table[h]; i>=0; i = chain[i]) { const vertex &c = verts[i]; if(c.pos==v.pos && c.u==v.u && c.v==v.v && c.norm==v.norm && c.tangent==v.tangent && c.bitangent==v.bitangent) { if(!v.lmu && !v.lmv) return i; if(c.lmu==v.lmu && c.lmv==v.lmv) return i; } } if(verts.length() >= USHRT_MAX) return -1; verts.add(v); chain.add(table[h]); return table[h] = verts.length()-1; } int addvert(const vec &pos, float u = 0, float v = 0, short lmu = 0, short lmv = 0, const bvec &norm = bvec(128, 128, 128), const bvec &tangent = bvec(128, 128, 128), uchar bitangent = 128) { vertex vtx; vtx.pos = pos; vtx.u = u; vtx.v = v; vtx.lmu = lmu; vtx.lmv = lmv; vtx.norm = norm; vtx.reserved = 0; vtx.tangent = tangent; vtx.bitangent = bitangent; return addvert(vtx); } }; enum { NO_ALPHA = 0, ALPHA_BACK, ALPHA_FRONT }; struct sortkey { ushort tex, lmid, envmap; uchar dim, layer, alpha; sortkey() {} sortkey(ushort tex, ushort lmid, uchar dim, uchar layer = LAYER_TOP, ushort envmap = EMID_NONE, uchar alpha = NO_ALPHA) : tex(tex), lmid(lmid), envmap(envmap), dim(dim), layer(layer), alpha(alpha) {} bool operator==(const sortkey &o) const { return tex==o.tex && lmid==o.lmid && envmap==o.envmap && dim==o.dim && layer==o.layer && alpha==o.alpha; } }; struct sortval { int unlit; vector tris[2]; sortval() : unlit(0) {} }; static inline bool htcmp(const sortkey &x, const sortkey &y) { return x == y; } static inline uint hthash(const sortkey &k) { return k.tex + k.lmid*9741; } struct vacollect : verthash { ivec origin; int size; hashtable indices; vector texs; vector grasstris; vector matsurfs; vector mapmodels; vector skyindices, explicitskyindices; vector skyfaces[6]; int worldtris, skytris, skymask, skyclip, skyarea; void clear() { clearverts(); worldtris = skytris = 0; skymask = 0; skyclip = INT_MAX; skyarea = 0; indices.clear(); skyindices.setsize(0); explicitskyindices.setsize(0); matsurfs.setsize(0); mapmodels.setsize(0); grasstris.setsize(0); texs.setsize(0); loopi(6) skyfaces[i].setsize(0); } void remapunlit(vector &remap) { uint lastlmid[8] = { LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT }, firstlmid[8] = { LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT, LMID_AMBIENT }; int firstlit[8] = { -1, -1, -1, -1, -1, -1, -1, -1 }; loopv(texs) { sortkey &k = texs[i]; if(k.lmid>=LMID_RESERVED) { LightMapTexture &lmtex = lightmaptexs[k.lmid]; int type = lmtex.type&LM_TYPE; if(k.layer==LAYER_BLEND) type += 2; else if(k.alpha) type += 4 + 2*(k.alpha-1); lastlmid[type] = lmtex.unlitx>=0 ? k.lmid : LMID_AMBIENT; if(firstlmid[type]==LMID_AMBIENT && lastlmid[type]!=LMID_AMBIENT) { firstlit[type] = i; firstlmid[type] = lastlmid[type]; } } else if(k.lmid==LMID_AMBIENT) { Shader *s = lookupvslot(k.tex, false).slot->shader; int type = s->type&SHADER_NORMALSLMS ? LM_BUMPMAP0 : LM_DIFFUSE; if(k.layer==LAYER_BLEND) type += 2; else if(k.alpha) type += 4 + 2*(k.alpha-1); if(lastlmid[type]!=LMID_AMBIENT) { sortval &t = indices[k]; if(t.unlit<=0) t.unlit = lastlmid[type]; } } } loopj(2) { int offset = 2*j; if(firstlmid[offset]==LMID_AMBIENT && firstlmid[offset+1]==LMID_AMBIENT) continue; loopi(max(firstlit[offset], firstlit[offset+1])) { sortkey &k = texs[i]; if((j ? k.layer!=LAYER_BLEND : k.layer==LAYER_BLEND) || k.alpha) continue; if(k.lmid!=LMID_AMBIENT) continue; Shader *s = lookupvslot(k.tex, false).slot->shader; int type = offset + (s->type&SHADER_NORMALSLMS ? LM_BUMPMAP0 : LM_DIFFUSE); if(firstlmid[type]==LMID_AMBIENT) continue; indices[k].unlit = firstlmid[type]; } } loopj(2) { int offset = 4 + 2*j; if(firstlmid[offset]==LMID_AMBIENT && firstlmid[offset+1]==LMID_AMBIENT) continue; loopi(max(firstlit[offset], firstlit[offset+1])) { sortkey &k = texs[i]; if(k.alpha != j+1) continue; if(k.lmid!=LMID_AMBIENT) continue; Shader *s = lookupvslot(k.tex, false).slot->shader; int type = offset + (s->type&SHADER_NORMALSLMS ? LM_BUMPMAP0 : LM_DIFFUSE); if(firstlmid[type]==LMID_AMBIENT) continue; indices[k].unlit = firstlmid[type]; } } loopv(remap) { sortkey &k = remap[i]; sortval &t = indices[k]; if(t.unlit<=0) continue; LightMapTexture &lm = lightmaptexs[t.unlit]; short u = short(ceil((lm.unlitx + 0.5f) * SHRT_MAX/lm.w)), v = short(ceil((lm.unlity + 0.5f) * SHRT_MAX/lm.h)); loopl(2) loopvj(t.tris[l]) { vertex &vtx = verts[t.tris[l][j]]; if(!vtx.lmu && !vtx.lmv) { vtx.lmu = u; vtx.lmv = v; } else if(vtx.lmu != u || vtx.lmv != v) { vertex vtx2 = vtx; vtx2.lmu = u; vtx2.lmv = v; t.tris[l][j] = addvert(vtx2); } } sortval *dst = indices.access(sortkey(k.tex, t.unlit, k.dim, k.layer, k.envmap, k.alpha)); if(dst) loopl(2) loopvj(t.tris[l]) dst->tris[l].add(t.tris[l][j]); } } void optimize() { vector remap; enumeratekt(indices, sortkey, k, sortval, t, loopl(2) if(t.tris[l].length() && t.unlit<=0) { if(k.lmid>=LMID_RESERVED && lightmaptexs[k.lmid].unlitx>=0) { sortkey ukey(k.tex, LMID_AMBIENT, k.dim, k.layer, k.envmap, k.alpha); sortval *uval = indices.access(ukey); if(uval && uval->unlit<=0) { if(uval->unlit<0) texs.removeobj(ukey); else remap.add(ukey); uval->unlit = k.lmid; } } else if(k.lmid==LMID_AMBIENT) { remap.add(k); t.unlit = -1; } texs.add(k); break; } ); texs.sort(texsort); remapunlit(remap); matsurfs.shrink(optimizematsurfs(matsurfs.getbuf(), matsurfs.length())); } static inline bool texsort(const sortkey &x, const sortkey &y) { if(x.alpha < y.alpha) return true; if(x.alpha > y.alpha) return false; if(x.layer < y.layer) return true; if(x.layer > y.layer) return false; if(x.tex == y.tex) { if(x.lmid < y.lmid) return true; if(x.lmid > y.lmid) return false; if(x.envmap < y.envmap) return true; if(x.envmap > y.envmap) return false; if(x.dim < y.dim) return true; if(x.dim > y.dim) return false; return false; } if(renderpath!=R_FIXEDFUNCTION) { VSlot &xs = lookupvslot(x.tex, false), &ys = lookupvslot(y.tex, false); if(xs.slot->shader < ys.slot->shader) return true; if(xs.slot->shader > ys.slot->shader) return false; if(xs.slot->params.length() < ys.slot->params.length()) return true; if(xs.slot->params.length() > ys.slot->params.length()) return false; } if(x.tex < y.tex) return true; else return false; } #define GENVERTS(type, ptr, body) do \ { \ type *f = (type *)ptr; \ loopv(verts) \ { \ const vertex &v = verts[i]; \ body; \ f++; \ } \ } while(0) #define GENVERTSPOSNORMUV(type, ptr, body) GENVERTS(type, ptr, { f->pos = v.pos; f->norm = v.norm; f->norm.flip(); f->reserved = 0; f->u = v.u; f->v = v.v; body; }) void genverts(void *buf) { if(renderpath==R_FIXEDFUNCTION) GENVERTSPOSNORMUV(vertexff, buf, { f->lmu = v.lmu/float(SHRT_MAX); f->lmv = v.lmv/float(SHRT_MAX); }); else GENVERTS(vertex, buf, { *f = v; f->norm.flip(); }); } void setupdata(vtxarray *va) { va->verts = verts.length(); va->tris = worldtris/3; va->vbuf = 0; va->vdata = 0; va->minvert = 0; va->maxvert = va->verts-1; va->voffset = 0; if(va->verts) { if(vbosize[VBO_VBUF] + verts.length() > maxvbosize || vbosize[VBO_EBUF] + worldtris > USHRT_MAX || vbosize[VBO_SKYBUF] + skytris > USHRT_MAX) flushvbo(); va->voffset = vbosize[VBO_VBUF]; uchar *vdata = addvbo(va, VBO_VBUF, va->verts, VTXSIZE); genverts(vdata); va->minvert += va->voffset; va->maxvert += va->voffset; } va->matbuf = NULL; va->matsurfs = matsurfs.length(); if(va->matsurfs) { va->matbuf = new materialsurface[matsurfs.length()]; memcpy(va->matbuf, matsurfs.getbuf(), matsurfs.length()*sizeof(materialsurface)); } va->skybuf = 0; va->skydata = 0; va->sky = skyindices.length(); va->explicitsky = explicitskyindices.length(); if(va->sky + va->explicitsky) { va->skydata += vbosize[VBO_SKYBUF]; ushort *skydata = (ushort *)addvbo(va, VBO_SKYBUF, va->sky+va->explicitsky, sizeof(ushort)); memcpy(skydata, skyindices.getbuf(), va->sky*sizeof(ushort)); memcpy(skydata+va->sky, explicitskyindices.getbuf(), va->explicitsky*sizeof(ushort)); if(va->voffset) loopi(va->sky+va->explicitsky) skydata[i] += va->voffset; } va->eslist = NULL; va->texs = texs.length(); va->blendtris = 0; va->blends = 0; va->alphabacktris = 0; va->alphaback = 0; va->alphafronttris = 0; va->alphafront = 0; va->ebuf = 0; va->edata = 0; if(va->texs) { va->eslist = new elementset[va->texs]; va->edata += vbosize[VBO_EBUF]; ushort *edata = (ushort *)addvbo(va, VBO_EBUF, worldtris, sizeof(ushort)), *curbuf = edata; loopv(texs) { const sortkey &k = texs[i]; const sortval &t = indices[k]; elementset &e = va->eslist[i]; e.texture = k.tex; e.lmid = t.unlit>0 ? t.unlit : k.lmid; e.dim = k.dim; e.layer = k.layer; e.envmap = k.envmap; ushort *startbuf = curbuf; loopl(2) { e.minvert[l] = USHRT_MAX; e.maxvert[l] = 0; if(t.tris[l].length()) { memcpy(curbuf, t.tris[l].getbuf(), t.tris[l].length() * sizeof(ushort)); loopvj(t.tris[l]) { curbuf[j] += va->voffset; e.minvert[l] = min(e.minvert[l], curbuf[j]); e.maxvert[l] = max(e.maxvert[l], curbuf[j]); } curbuf += t.tris[l].length(); } e.length[l] = curbuf-startbuf; } if(k.layer==LAYER_BLEND) { va->texs--; va->tris -= e.length[1]/3; va->blends++; va->blendtris += e.length[1]/3; } else if(k.alpha==ALPHA_BACK) { va->texs--; va->tris -= e.length[1]/3; va->alphaback++; va->alphabacktris += e.length[1]/3; } else if(k.alpha==ALPHA_FRONT) { va->texs--; va->tris -= e.length[1]/3; va->alphafront++; va->alphafronttris += e.length[1]/3; } } } va->texmask = 0; loopi(va->texs+va->blends+va->alphaback+va->alphafront) { Slot &slot = *lookupvslot(va->eslist[i].texture, false).slot; loopvj(slot.sts) va->texmask |= 1<type&SHADER_ENVMAP && (renderpath!=R_FIXEDFUNCTION || (slot.ffenv && hasCM && maxtmus >= 2))) va->texmask |= 1<grasstris.move(grasstris); useshaderbyname("grass"); } if(mapmodels.length()) va->mapmodels.put(mapmodels.getbuf(), mapmodels.length()); } bool emptyva() { return verts.empty() && matsurfs.empty() && skyindices.empty() && explicitskyindices.empty() && grasstris.empty() && mapmodels.empty(); } } vc; int recalcprogress = 0; #define progress(s) if((recalcprogress++&0xFFF)==0) renderprogress(recalcprogress/(float)allocnodes, s); vector tjoints; vec shadowmapmin, shadowmapmax; int calcshadowmask(vec *pos, int numpos) { extern vec shadowdir; int mask = 0, used = 1; vec pe = vec(pos[1]).sub(pos[0]); loopk(numpos-2) { vec e = vec(pos[k+2]).sub(pos[0]); if(vec().cross(pe, e).dot(shadowdir)>0) { mask |= 1< &idxs = key.tex==DEFAULT_SKY ? vc.explicitskyindices : vc.indices[key].tris[(shadowmask>>i)&1]; int left = index[0], mid = index[i+1], right = index[i+2], start = left, i0 = left, i1 = -1; loopk(4) { int i2 = -1, ctj = -1, cedge = -1; switch(k) { case 1: i1 = i2 = mid; cedge = edge+i+1; break; case 2: if(i1 != mid || i0 == left) { i0 = i1; i1 = right; } i2 = right; if(i+1 == numverts-2) cedge = edge+i+2; break; case 3: if(i0 == start) { i0 = i1; i1 = left; } i2 = left; // fall-through default: if(!i) cedge = edge; break; } if(i1 != i2) { if(total + 3 > USHRT_MAX) return; total += 3; idxs.add(i0); idxs.add(i1); idxs.add(i2); i1 = i2; } if(cedge >= 0) { for(ctj = tj;;) { if(ctj < 0) break; if(tjoints[ctj].edge < cedge) { ctj = tjoints[ctj].next; continue; } if(tjoints[ctj].edge != cedge) ctj = -1; break; } } if(ctj >= 0) { int e1 = cedge%(MAXFACEVERTS+1), e2 = (e1+1)%numverts; vertex &v1 = verts[e1], &v2 = verts[e2]; ivec d(vec(v2.pos).sub(v1.pos).mul(8)); int axis = abs(d.x) > abs(d.y) ? (abs(d.x) > abs(d.z) ? 0 : 2) : (abs(d.y) > abs(d.z) ? 1 : 2); if(d[axis] < 0) d.neg(); reduceslope(d); int origin = int(min(v1.pos[axis], v2.pos[axis])*8)&~0x7FFF, offset1 = (int(v1.pos[axis]*8) - origin) / d[axis], offset2 = (int(v2.pos[axis]*8) - origin) / d[axis]; vec o = vec(v1.pos).sub(d.tovec().mul(offset1/8.0f)); float doffset = 1.0f / (offset2 - offset1); if(i1 < 0) for(;;) { tjoint &t = tjoints[ctj]; if(t.next < 0 || tjoints[t.next].edge != cedge) break; ctj = t.next; } while(ctj >= 0) { tjoint &t = tjoints[ctj]; if(t.edge != cedge) break; float offset = (t.offset - offset1) * doffset; vertex vt; vt.pos = d.tovec().mul(t.offset/8.0f).add(o); vt.reserved = 0; vt.u = v1.u + (v2.u-v1.u)*offset; vt.v = v1.v + (v2.v-v1.v)*offset; vt.lmu = short(v1.lmu + (v2.lmu-v1.lmu)*offset), vt.lmv = short(v1.lmv + (v2.lmv-v1.lmv)*offset); vt.norm.lerp(v1.norm, v2.norm, offset); vt.tangent.lerp(v1.tangent, v2.tangent, offset); vt.bitangent = v1.bitangent; int i2 = vc.addvert(vt); if(i2 < 0) return; if(i1 >= 0) { if(total + 3 > USHRT_MAX) return; total += 3; idxs.add(i0); idxs.add(i1); idxs.add(i2); i1 = i2; } else start = i0 = i2; ctj = t.next; } } } } } void addgrasstri(int face, vertex *verts, int numv, ushort texture, ushort lmid) { grasstri &g = vc.grasstris.add(); int i1, i2, i3, i4; if(numv <= 3 && face%2) { i1 = face+1; i2 = face+2; i3 = i4 = 0; } else { i1 = 0; i2 = face+1; i3 = face+2; i4 = numv > 3 ? face+3 : i3; } g.v[0] = verts[i1].pos; g.v[1] = verts[i2].pos; g.v[2] = verts[i3].pos; g.v[3] = verts[i4].pos; g.numv = numv; g.surface.toplane(g.v[0], g.v[1], g.v[2]); if(g.surface.z <= 0) { vc.grasstris.pop(); return; } g.minz = min(min(g.v[0].z, g.v[1].z), min(g.v[2].z, g.v[3].z)); g.maxz = max(max(g.v[0].z, g.v[1].z), max(g.v[2].z, g.v[3].z)); g.center = vec(0, 0, 0); loopk(numv) g.center.add(g.v[k]); g.center.div(numv); g.radius = 0; loopk(numv) g.radius = max(g.radius, g.v[k].dist(g.center)); vec area, bx, by; area.cross(vec(g.v[1]).sub(g.v[0]), vec(g.v[2]).sub(g.v[0])); float scale; int px, py; if(fabs(area.x) >= fabs(area.y) && fabs(area.x) >= fabs(area.z)) scale = 1/area.x, px = 1, py = 2; else if(fabs(area.y) >= fabs(area.x) && fabs(area.y) >= fabs(area.z)) scale = -1/area.y, px = 0, py = 2; else scale = 1/area.z, px = 0, py = 1; bx.x = (g.v[2][py] - g.v[0][py])*scale; bx.y = (g.v[2][px] - g.v[0][px])*scale; bx.z = bx.x*g.v[2][px] - bx.y*g.v[2][py]; by.x = (g.v[2][py] - g.v[1][py])*scale; by.y = (g.v[2][px] - g.v[1][px])*scale; by.z = by.x*g.v[1][px] - by.y*g.v[1][py] - 1; by.sub(bx); float tc1u = verts[i1].lmu/float(SHRT_MAX), tc1v = verts[i1].lmv/float(SHRT_MAX), tc2u = (verts[i2].lmu - verts[i1].lmu)/float(SHRT_MAX), tc2v = (verts[i2].lmv - verts[i1].lmv)/float(SHRT_MAX), tc3u = (verts[i3].lmu - verts[i1].lmu)/float(SHRT_MAX), tc3v = (verts[i3].lmv - verts[i1].lmv)/float(SHRT_MAX); g.tcu = vec4(0, 0, 0, tc1u - (bx.z*tc2u + by.z*tc3u)); g.tcu[px] = bx.x*tc2u + by.x*tc3u; g.tcu[py] = -(bx.y*tc2u + by.y*tc3u); g.tcv = vec4(0, 0, 0, tc1v - (bx.z*tc2v + by.z*tc3v)); g.tcv[px] = bx.x*tc2v + by.x*tc3v; g.tcv[py] = -(bx.y*tc2v + by.y*tc3v); g.texture = texture; g.lmid = lmid; } static inline void calctexgen(VSlot &vslot, int dim, vec4 &sgen, vec4 &tgen) { Texture *tex = vslot.slot->sts.empty() ? notexture : vslot.slot->sts[0].t; float k = TEX_SCALE/vslot.scale, xs = vslot.rotation>=2 && vslot.rotation<=4 ? -tex->xs : tex->xs, ys = (vslot.rotation>=1 && vslot.rotation<=2) || vslot.rotation==5 ? -tex->ys : tex->ys, sk = k/xs, tk = k/ys, soff = -((vslot.rotation&5)==1 ? vslot.yoffset : vslot.xoffset)/xs, toff = -((vslot.rotation&5)==1 ? vslot.xoffset : vslot.yoffset)/ys; static const int si[] = { 1, 0, 0 }, ti[] = { 2, 2, 1 }; int sdim = si[dim], tdim = ti[dim]; sgen = vec4(0, 0, 0, soff); tgen = vec4(0, 0, 0, toff); if((vslot.rotation&5)==1) { sgen[tdim] = (dim <= 1 ? -sk : sk); tgen[sdim] = tk; } else { sgen[sdim] = sk; tgen[tdim] = (dim <= 1 ? -tk : tk); } } ushort encodenormal(const vec &n) { if(n.iszero()) return 0; int yaw = int(-atan2(n.x, n.y)/RAD), pitch = int(asin(n.z)/RAD); return ushort(clamp(pitch + 90, 0, 180)*360 + (yaw < 0 ? yaw%360 + 360 : yaw%360) + 1); } vec decodenormal(ushort norm) { if(!norm) return vec(0, 0, 1); norm--; const vec2 &yaw = sincos360[norm%360], &pitch = sincos360[norm/360+270]; return vec(-yaw.y*pitch.x, yaw.x*pitch.x, pitch.y); } void addcubeverts(VSlot &vslot, int orient, int size, vec *pos, int convex, ushort texture, ushort lmid, vertinfo *vinfo, int numverts, int tj = -1, ushort envmap = EMID_NONE, int grassy = 0, bool alpha = false, int layer = LAYER_TOP) { int dim = dimension(orient); int shadowmask = texture==DEFAULT_SKY || alpha ? 0 : calcshadowmask(pos, numverts); LightMap *lm = NULL; LightMapTexture *lmtex = NULL; if(!nolights && lightmaps.inrange(lmid-LMID_RESERVED)) { lm = &lightmaps[lmid-LMID_RESERVED]; if((lm->type&LM_TYPE)==LM_DIFFUSE || ((lm->type&LM_TYPE)==LM_BUMPMAP0 && lightmaps.inrange(lmid+1-LMID_RESERVED) && (lightmaps[lmid+1-LMID_RESERVED].type&LM_TYPE)==LM_BUMPMAP1)) lmtex = &lightmaptexs[lm->tex]; else lm = NULL; } vec4 sgen, tgen; calctexgen(vslot, dim, sgen, tgen); vertex verts[MAXFACEVERTS]; int index[MAXFACEVERTS]; loopk(numverts) { vertex &v = verts[k]; v.pos = pos[k]; v.reserved = 0; v.u = sgen.dot(v.pos); v.v = tgen.dot(v.pos); if(lmtex) { v.lmu = short(ceil((lm->offsetx + vinfo[k].u*(float(LM_PACKW)/float(USHRT_MAX+1)) + 0.5f) * float(SHRT_MAX)/lmtex->w)); v.lmv = short(ceil((lm->offsety + vinfo[k].v*(float(LM_PACKH)/float(USHRT_MAX+1)) + 0.5f) * float(SHRT_MAX)/lmtex->h)); } else v.lmu = v.lmv = 0; if(renderpath!=R_FIXEDFUNCTION && vinfo && vinfo[k].norm) { vec n = decodenormal(vinfo[k].norm), t = orientation_tangent[vslot.rotation][dim]; t.sub(vec(n).mul(n.dot(t))).normalize(); v.norm = bvec(n); v.tangent = bvec(t); v.bitangent = vec().cross(n, t).dot(orientation_binormal[vslot.rotation][dim]) < 0 ? 0 : 255; } else { v.norm = vinfo && vinfo[k].norm && envmap != EMID_NONE ? bvec(decodenormal(vinfo[k].norm)) : bvec(128, 128, 255); v.tangent = bvec(255, 128, 128); v.bitangent = 255; } index[k] = vc.addvert(v); if(index[k] < 0) return; } if(texture == DEFAULT_SKY) { loopk(numverts) vc.skyclip = min(vc.skyclip, int(pos[k].z*8)>>3); vc.skymask |= 0x3F&~(1<= LMID_RESERVED) lmid = lm ? lm->tex : LMID_AMBIENT; sortkey key(texture, lmid, vslot.scrollS || vslot.scrollT ? dim : 3, layer == LAYER_BLEND ? LAYER_BLEND : LAYER_TOP, envmap, alpha ? (vslot.alphaback ? ALPHA_BACK : (vslot.alphafront ? ALPHA_FRONT : NO_ALPHA)) : NO_ALPHA); addtris(key, orient, verts, index, numverts, convex, shadowmask, tj); if(grassy) { for(int i = 0; i < numverts-2; i += 2) { int faces = 0; if(index[0]!=index[i+1] && index[i+1]!=index[i+2] && index[i+2]!=index[0]) faces |= 1; if(i+3 < numverts && index[0]!=index[i+2] && index[i+2]!=index[i+3] && index[i+3]!=index[0]) faces |= 2; if(grassy > 1 && faces==3) addgrasstri(i, verts, 4, texture, lmid); else { if(faces&1) addgrasstri(i, verts, 3, texture, lmid); if(faces&2) addgrasstri(i+1, verts, 3, texture, lmid); } } } } struct edgegroup { ivec slope, origin; int axis; }; static uint hthash(const edgegroup &g) { return g.slope.x^g.slope.y^g.slope.z^g.origin.x^g.origin.y^g.origin.z; } static bool htcmp(const edgegroup &x, const edgegroup &y) { return x.slope==y.slope && x.origin==y.origin; } enum { CE_START = 1<<0, CE_END = 1<<1, CE_FLIP = 1<<2, CE_DUP = 1<<3 }; struct cubeedge { cube *c; int next, offset; ushort size; uchar index, flags; }; vector cubeedges; hashtable edgegroups(1<<13); void gencubeedges(cube &c, int x, int y, int z, int size) { ivec pos[MAXFACEVERTS]; int vis; loopi(6) if((vis = visibletris(c, i, x, y, z, size))) { int numverts = c.ext ? c.ext->surfaces[i].numverts&MAXFACEVERTS : 0; if(numverts) { vertinfo *verts = c.ext->verts() + c.ext->surfaces[i].verts; ivec vo = ivec(x, y, z).mask(~0xFFF).shl(3); loopj(numverts) { vertinfo &v = verts[j]; pos[j] = ivec(v.x, v.y, v.z).add(vo); } } else if(c.merged&(1< abs(d.y) ? (abs(d.x) > abs(d.z) ? 0 : 2) : (abs(d.y) > abs(d.z) ? 1 : 2); if(d[axis] < 0) { d.neg(); swap(e1, e2); } reduceslope(d); int t1 = pos[e1][axis]/d[axis], t2 = pos[e2][axis]/d[axis]; edgegroup g; g.origin = ivec(pos[e1]).sub(ivec(d).mul(t1)); g.slope = d; g.axis = axis; cubeedge ce; ce.c = &c; ce.offset = t1; ce.size = t2 - t1; ce.index = i*(MAXFACEVERTS+1)+j; ce.flags = CE_START | CE_END | (e1!=j ? CE_FLIP : 0); ce.next = -1; bool insert = true; int *exists = edgegroups.access(g); if(exists) { int prev = -1, cur = *exists; while(cur >= 0) { cubeedge &p = cubeedges[cur]; if(p.flags&CE_DUP ? ce.offset>=p.offset && ce.offset+ce.size<=p.offset+p.size : ce.offset==p.offset && ce.size==p.size) { p.flags |= CE_DUP; insert = false; break; } else if(ce.offset >= p.offset) { if(ce.offset == p.offset+p.size) ce.flags &= ~CE_START; prev = cur; cur = p.next; } else break; } if(insert) { ce.next = cur; while(cur >= 0) { cubeedge &p = cubeedges[cur]; if(ce.offset+ce.size==p.offset) { ce.flags &= ~CE_END; break; } cur = p.next; } if(prev>=0) cubeedges[prev].next = cubeedges.length(); else *exists = cubeedges.length(); } } else edgegroups[g] = cubeedges.length(); if(insert) cubeedges.add(ce); } } } void gencubeedges(cube *c = worldroot, int x = 0, int y = 0, int z = 0, int size = worldsize>>1) { progress("fixing t-joints..."); neighbourstack[++neighbourdepth] = c; loopi(8) { ivec o(i, x, y, z, size); if(c[i].ext) c[i].ext->tjoints = -1; if(c[i].children) gencubeedges(c[i].children, o.x, o.y, o.z, size>>1); else if(!isempty(c[i])) gencubeedges(c[i], o.x, o.y, o.z, size); } --neighbourdepth; } void gencubeverts(cube &c, int x, int y, int z, int size, int csi) { if(!(c.visible&0xC0)) return; int vismask = ~c.merged & 0x3F; if(!(c.visible&0x80)) vismask &= c.visible; if(!vismask) return; int tj = filltjoints && c.ext ? c.ext->tjoints : -1, vis; loopi(6) if(vismask&(1<surfaces[i].numverts&MAXFACEVERTS : 0, convex = 0; if(numverts) { verts = c.ext->verts() + c.ext->surfaces[i].verts; vec vo = ivec(x, y, z).mask(~0xFFF).tovec(); loopj(numverts) pos[j] = verts[j].getxyz().tovec().mul(1.0f/8).add(vo); if(!flataxisface(c, i)) convex = faceconvexity(verts, numverts, size); } else { ivec v[4]; genfaceverts(c, i, v); if(!flataxisface(c, i)) convex = faceconvexity(v); int order = vis&4 || convex < 0 ? 1 : 0; vec vo(x, y, z); pos[numverts++] = v[order].tovec().mul(size/8.0f).add(vo); if(vis&1) pos[numverts++] = v[order+1].tovec().mul(size/8.0f).add(vo); pos[numverts++] = v[order+2].tovec().mul(size/8.0f).add(vo); if(vis&2) pos[numverts++] = v[(order+3)&3].tovec().mul(size/8.0f).add(vo); } VSlot &vslot = lookupvslot(c.texture[i], true), *layer = vslot.layer && !(c.material&MAT_ALPHA) ? &lookupvslot(vslot.layer, true) : NULL; ushort envmap = vslot.slot->shader->type&SHADER_ENVMAP ? (vslot.slot->texmask&(1<slot->shader->type&SHADER_ENVMAP ? (layer->slot->texmask&(1<= 0 && tjoints[tj].edge < i*(MAXFACEVERTS+1)) tj = tjoints[tj].next; int hastj = tj >= 0 && tjoints[tj].edge < (i+1)*(MAXFACEVERTS+1) ? tj : -1; int grassy = vslot.slot->autograss && i!=O_BOTTOM ? (vis!=3 || convex ? 1 : 2) : 0; if(!c.ext) addcubeverts(vslot, i, size, pos, convex, c.texture[i], LMID_AMBIENT, NULL, numverts, hastj, envmap, grassy, (c.material&MAT_ALPHA)!=0); else { const surfaceinfo &surf = c.ext->surfaces[i]; if(!surf.numverts || surf.numverts&LAYER_TOP) addcubeverts(vslot, i, size, pos, convex, c.texture[i], surf.lmid[0], verts, numverts, hastj, envmap, grassy, (c.material&MAT_ALPHA)!=0, LAYER_TOP|(surf.numverts&LAYER_BLEND)); if(surf.numverts&LAYER_BOTTOM) addcubeverts(layer ? *layer : vslot, i, size, pos, convex, vslot.layer, surf.lmid[1], surf.numverts&LAYER_DUP ? verts + numverts : verts, numverts, hastj, envmap2); } } } static inline bool skyoccluded(cube &c, int orient) { return touchingface(c, orient) && faceedges(c, orient) == F_SOLID; } static int dummyskyfaces[6]; static inline int hasskyfaces(cube &c, int x, int y, int z, int size, int faces[6] = dummyskyfaces) { int numfaces = 0; if(isempty(c) || c.material&MAT_ALPHA) { if(x == 0) faces[numfaces++] = O_LEFT; if(x + size == worldsize) faces[numfaces++] = O_RIGHT; if(y == 0) faces[numfaces++] = O_BACK; if(y + size == worldsize) faces[numfaces++] = O_FRONT; if(z == 0) faces[numfaces++] = O_BOTTOM; if(z + size == worldsize) faces[numfaces++] = O_TOP; } else if(!isentirelysolid(c)) { if(x == 0 && !skyoccluded(c, O_LEFT)) faces[numfaces++] = O_LEFT; if(x + size == worldsize && !skyoccluded(c, O_RIGHT)) faces[numfaces++] = O_RIGHT; if(y == 0 && !skyoccluded(c, O_BACK)) faces[numfaces++] = O_BACK; if(y + size == worldsize && !skyoccluded(c, O_FRONT)) faces[numfaces++] = O_FRONT; if(z == 0 && !skyoccluded(c, O_BOTTOM)) faces[numfaces++] = O_BOTTOM; if(z + size == worldsize && !skyoccluded(c, O_TOP)) faces[numfaces++] = O_TOP; } return numfaces; } void minskyface(cube &cu, int orient, const ivec &co, int size, facebounds &orig) { facebounds mincf; mincf.u1 = orig.u2; mincf.u2 = orig.u1; mincf.v1 = orig.v2; mincf.v2 = orig.v1; mincubeface(cu, orient, co, size, orig, mincf, MAT_ALPHA, MAT_ALPHA); orig.u1 = max(mincf.u1, orig.u1); orig.u2 = min(mincf.u2, orig.u2); orig.v1 = max(mincf.v1, orig.v1); orig.v2 = min(mincf.v2, orig.v2); } void genskyfaces(cube &c, const ivec &o, int size) { int faces[6], numfaces = hasskyfaces(c, o.x, o.y, o.z, size, faces); if(!numfaces) return; loopi(numfaces) { int orient = faces[i], dim = dimension(orient); facebounds m; m.u1 = (o[C[dim]]&0xFFF)<<3; m.u2 = m.u1 + (size<<3); m.v1 = (o[R[dim]]&0xFFF)<<3; m.v2 = m.v1 + (size<<3); minskyface(c, orient, o, size, m); if(m.u1 >= m.u2 || m.v1 >= m.v2) continue; vc.skyarea += (int(m.u2-m.u1)*int(m.v2-m.v1) + (1<<(2*3))-1)>>(2*3); vc.skyfaces[orient].add(m); } } void addskyverts(const ivec &o, int size) { loopi(6) { int dim = dimension(i), c = C[dim], r = R[dim]; vector &sf = vc.skyfaces[i]; if(sf.empty()) continue; vc.skymask |= 0x3F&~(1<>3); } if(vc.skytris + 6 > USHRT_MAX) break; vc.skytris += 6; vc.skyindices.add(index[0]); vc.skyindices.add(index[1]); vc.skyindices.add(index[2]); vc.skyindices.add(index[0]); vc.skyindices.add(index[2]); vc.skyindices.add(index[3]); nextskyface:; } } } ////////// Vertex Arrays ////////////// int allocva = 0; int wtris = 0, wverts = 0, vtris = 0, vverts = 0, glde = 0, gbatches = 0; vector valist, varoot; vtxarray *newva(int x, int y, int z, int size) { vc.optimize(); vtxarray *va = new vtxarray; va->parent = NULL; va->o = ivec(x, y, z); va->size = size; va->skyarea = vc.skyarea; va->skyfaces = vc.skymask; va->skyclip = vc.skyclip < INT_MAX ? vc.skyclip : INT_MAX; va->curvfc = VFC_NOT_VISIBLE; va->occluded = OCCLUDE_NOTHING; va->query = NULL; va->bbmin = ivec(-1, -1, -1); va->bbmax = ivec(-1, -1, -1); va->hasmerges = 0; va->mergelevel = -1; vc.setupdata(va); wverts += va->verts; wtris += va->tris + va->blends + va->alphabacktris + va->alphafronttris; allocva++; valist.add(va); return va; } void destroyva(vtxarray *va, bool reparent) { wverts -= va->verts; wtris -= va->tris + va->blends + va->alphabacktris + va->alphafronttris; allocva--; valist.removeobj(va); if(!va->parent) varoot.removeobj(va); if(reparent) { if(va->parent) va->parent->children.removeobj(va); loopv(va->children) { vtxarray *child = va->children[i]; child->parent = va->parent; if(child->parent) child->parent->children.add(child); } } if(va->vbuf) destroyvbo(va->vbuf); if(va->ebuf) destroyvbo(va->ebuf); if(va->skybuf) destroyvbo(va->skybuf); if(va->eslist) delete[] va->eslist; if(va->matbuf) delete[] va->matbuf; delete va; } void clearvas(cube *c) { loopi(8) { if(c[i].ext) { if(c[i].ext->va) destroyva(c[i].ext->va, false); c[i].ext->va = NULL; c[i].ext->tjoints = -1; } if(c[i].children) clearvas(c[i].children); } } void updatevabb(vtxarray *va, bool force) { if(!force && va->bbmin.x >= 0) return; va->bbmin = va->geommin; va->bbmax = va->geommax; va->bbmin.min(va->matmin); va->bbmax.max(va->matmax); loopv(va->children) { vtxarray *child = va->children[i]; updatevabb(child, force); va->bbmin.min(child->bbmin); va->bbmax.max(child->bbmax); } loopv(va->mapmodels) { octaentities *oe = va->mapmodels[i]; va->bbmin.min(oe->bbmin); va->bbmax.max(oe->bbmax); } if(va->skyfaces) { va->skyfaces |= 0x80; if(va->sky) loop(dim, 3) if(va->skyfaces&(3<<(2*dim))) { int r = R[dim], c = C[dim]; if((va->skyfaces&(1<<(2*dim)) && va->o[dim] < va->bbmin[dim]) || (va->skyfaces&(2<<(2*dim)) && va->o[dim]+va->size > va->bbmax[dim]) || va->o[r] < va->bbmin[r] || va->o[r]+va->size > va->bbmax[r] || va->o[c] < va->bbmin[c] || va->o[c]+va->size > va->bbmax[c]) { va->skyfaces &= ~0x80; break; } } } } void updatevabbs(bool force) { loopv(varoot) updatevabb(varoot[i], force); } struct mergedface { uchar orient, lmid, numverts; ushort mat, tex, envmap; vertinfo *verts; int tjoints; }; #define MAXMERGELEVEL 12 static int vahasmerges = 0, vamergemax = 0; static vector vamerges[MAXMERGELEVEL+1]; int genmergedfaces(cube &c, const ivec &co, int size, int minlevel = -1) { if(!c.ext || isempty(c)) return -1; int tj = c.ext->tjoints, maxlevel = -1; loopi(6) if(c.merged&(1<surfaces[i]; int numverts = surf.numverts&MAXFACEVERTS; if(!numverts) { if(minlevel < 0) vahasmerges |= MERGE_PART; continue; } mergedface mf; mf.orient = i; mf.mat = c.material; mf.tex = c.texture[i]; mf.envmap = EMID_NONE; mf.lmid = surf.lmid[0]; mf.numverts = surf.numverts; mf.verts = c.ext->verts() + surf.verts; mf.tjoints = -1; int level = calcmergedsize(i, co, size, mf.verts, mf.numverts&MAXFACEVERTS); if(level > minlevel) { maxlevel = max(maxlevel, level); while(tj >= 0 && tjoints[tj].edge < i*(MAXFACEVERTS+1)) tj = tjoints[tj].next; if(tj >= 0 && tjoints[tj].edge < (i+1)*(MAXFACEVERTS+1)) mf.tjoints = tj; VSlot &vslot = lookupvslot(mf.tex, true), *layer = vslot.layer && !(c.material&MAT_ALPHA) ? &lookupvslot(vslot.layer, true) : NULL; if(vslot.slot->shader->type&SHADER_ENVMAP) mf.envmap = vslot.slot->texmask&(1<slot->shader->type&SHADER_ENVMAP ? (layer->slot->texmask&(1<= 0) { vamergemax = max(vamergemax, maxlevel); vahasmerges |= MERGE_ORIGIN; } return maxlevel; } int findmergedfaces(cube &c, const ivec &co, int size, int csi, int minlevel) { if(c.ext && c.ext->va && !(c.ext->va->hasmerges&MERGE_ORIGIN)) return c.ext->va->mergelevel; else if(c.children) { int maxlevel = -1; loopi(8) { ivec o(i, co.x, co.y, co.z, size/2); int level = findmergedfaces(c.children[i], o, size/2, csi-1, minlevel); maxlevel = max(maxlevel, level); } return maxlevel; } else if(c.ext && c.merged) return genmergedfaces(c, co, size, minlevel); else return -1; } void addmergedverts(int level, const ivec &o) { vector &mfl = vamerges[level]; if(mfl.empty()) return; vec vo = ivec(o).mask(~0xFFF).tovec(); vec pos[MAXFACEVERTS]; loopv(mfl) { mergedface &mf = mfl[i]; int numverts = mf.numverts&MAXFACEVERTS; loopi(numverts) { vertinfo &v = mf.verts[i]; pos[i] = vec(v.x, v.y, v.z).mul(1.0f/8).add(vo); } VSlot &vslot = lookupvslot(mf.tex, true); int grassy = vslot.slot->autograss && mf.orient!=O_BOTTOM && mf.numverts&LAYER_TOP ? 2 : 0; addcubeverts(vslot, mf.orient, 1<va) { maxlevel = max(maxlevel, c.ext->va->mergelevel); return; // don't re-render } if(c.children) { neighbourstack[++neighbourdepth] = c.children; c.escaped = 0; loopi(8) { ivec o(i, cx, cy, cz, size/2); int level = -1; rendercube(c.children[i], o.x, o.y, o.z, size/2, csi-1, level); if(level >= csi) c.escaped |= 1<ents && c.ext->ents->mapmodels.length()) vc.mapmodels.add(c.ext->ents); } return; } genskyfaces(c, ivec(cx, cy, cz), size); if(!isempty(c)) { gencubeverts(c, cx, cy, cz, size, csi); if(c.merged) maxlevel = max(maxlevel, genmergedfaces(c, ivec(cx, cy, cz), size)); } if(c.material != MAT_AIR) genmatsurfs(c, cx, cy, cz, size, vc.matsurfs); if(c.ext) { if(c.ext->ents && c.ext->ents->mapmodels.length()) vc.mapmodels.add(c.ext->ents); } if(csi <= MAXMERGELEVEL && vamerges[csi].length()) addmergedverts(csi, ivec(cx, cy, cz)); } void calcgeombb(int cx, int cy, int cz, int size, ivec &bbmin, ivec &bbmax) { vec vmin(cx, cy, cz), vmax = vmin; vmin.add(size); loopv(vc.verts) { const vec &v = vc.verts[i].pos; vmin.min(v); vmax.max(v); } bbmin = ivec(vmin.mul(8)).shr(3); bbmax = ivec(vmax.mul(8)).add(7).shr(3); } void calcmatbb(int cx, int cy, int cz, int size, ivec &bbmin, ivec &bbmax) { bbmax = ivec(cx, cy, cz); (bbmin = bbmax).add(size); loopv(vc.matsurfs) { materialsurface &m = vc.matsurfs[i]; switch(m.material&MATF_VOLUME) { case MAT_WATER: case MAT_GLASS: case MAT_LAVA: break; default: continue; } int dim = dimension(m.orient), r = R[dim], c = C[dim]; bbmin[dim] = min(bbmin[dim], m.o[dim]); bbmax[dim] = max(bbmax[dim], m.o[dim]); bbmin[r] = min(bbmin[r], m.o[r]); bbmax[r] = max(bbmax[r], m.o[r] + m.rsize); bbmin[c] = min(bbmin[c], m.o[c]); bbmax[c] = max(bbmax[c], m.o[c] + m.csize); } } void setva(cube &c, int cx, int cy, int cz, int size, int csi) { ASSERT(size <= 0x1000); int vamergeoffset[MAXMERGELEVEL+1]; loopi(MAXMERGELEVEL+1) vamergeoffset[i] = vamerges[i].length(); vc.origin = ivec(cx, cy, cz); vc.size = size; shadowmapmin = vec(cx+size, cy+size, cz+size); shadowmapmax = vec(cx, cy, cz); int maxlevel = -1; rendercube(c, cx, cy, cz, size, csi, maxlevel); ivec bbmin, bbmax; calcgeombb(cx, cy, cz, size, bbmin, bbmax); addskyverts(ivec(cx, cy, cz), size); if(size == min(0x1000, worldsize/2) || !vc.emptyva()) { vtxarray *va = newva(cx, cy, cz, size); ext(c).va = va; va->geommin = bbmin; va->geommax = bbmax; calcmatbb(cx, cy, cz, size, va->matmin, va->matmax); va->shadowmapmin = ivec(shadowmapmin.mul(8)).shr(3); va->shadowmapmax = ivec(shadowmapmax.mul(8)).add(7).shr(3); va->hasmerges = vahasmerges; va->mergelevel = vamergemax; } else { loopi(MAXMERGELEVEL+1) vamerges[i].setsize(vamergeoffset[i]); } vc.clear(); } static inline int setcubevisibility(cube &c, int x, int y, int z, int size) { int numvis = 0, vismask = 0, collidemask = 0, checkmask = 0; loopi(6) { int facemask = classifyface(c, i, x, y, z, size); if(facemask&1) { vismask |= 1<surfaces[i].numverts&MAXFACEVERTS) numvis++; } else { numvis++; if(c.texture[i] != DEFAULT_SKY && !(c.ext && c.ext->surfaces[i].numverts&MAXFACEVERTS)) checkmask |= 1<va) { varoot.add(c[i].ext->va); if(c[i].ext->va->hasmerges&MERGE_ORIGIN) findmergedfaces(c[i], o, size, csi, csi); } else { if(c[i].children) count += updateva(c[i].children, o.x, o.y, o.z, size/2, csi-1); else { if(!isempty(c[i])) count += setcubevisibility(c[i], o.x, o.y, o.z, size); count += hasskyfaces(c[i], o.x, o.y, o.z, size); } int tcount = count + (csi <= MAXMERGELEVEL ? vamerges[csi].length() : 0); if(tcount > vafacemax || (tcount >= vafacemin && size >= vacubesize) || size == min(0x1000, worldsize/2)) { loadprogress = clamp(recalcprogress/float(allocnodes), 0.0f, 1.0f); setva(c[i], o.x, o.y, o.z, size, csi); if(c[i].ext && c[i].ext->va) { while(varoot.length() > childpos) { vtxarray *child = varoot.pop(); c[i].ext->va->children.add(child); child->parent = c[i].ext->va; } varoot.add(c[i].ext->va); if(vamergemax > size) { cmergemax = max(cmergemax, vamergemax); chasmerges |= vahasmerges&~MERGE_USE; } continue; } else count = 0; } } if(csi+1 <= MAXMERGELEVEL && vamerges[csi].length()) vamerges[csi+1].move(vamerges[csi]); cmergemax = max(cmergemax, vamergemax); chasmerges |= vahasmerges; ccount += count; } --neighbourdepth; vamergemax = cmergemax; vahasmerges = chasmerges; return ccount; } void addtjoint(const edgegroup &g, const cubeedge &e, int offset) { int vcoord = (g.slope[g.axis]*offset + g.origin[g.axis]) & 0x7FFF; tjoint &tj = tjoints.add(); tj.offset = vcoord / g.slope[g.axis]; tj.edge = e.index; int prev = -1, cur = ext(*e.c).tjoints; while(cur >= 0) { tjoint &o = tjoints[cur]; if(tj.edge < o.edge || (tj.edge==o.edge && (e.flags&CE_FLIP ? tj.offset > o.offset : tj.offset < o.offset))) break; prev = cur; cur = o.next; } tj.next = cur; if(prev < 0) e.c->ext->tjoints = tjoints.length()-1; else tjoints[prev].next = tjoints.length()-1; } void findtjoints(int cur, const edgegroup &g) { int active = -1; while(cur >= 0) { cubeedge &e = cubeedges[cur]; int prevactive = -1, curactive = active; while(curactive >= 0) { cubeedge &a = cubeedges[curactive]; if(a.offset+a.size <= e.offset) { if(prevactive >= 0) cubeedges[prevactive].next = a.next; else active = a.next; } else { prevactive = curactive; if(!(a.flags&CE_DUP)) { if(e.flags&CE_START && e.offset > a.offset && e.offset < a.offset+a.size) addtjoint(g, a, e.offset); if(e.flags&CE_END && e.offset+e.size > a.offset && e.offset+e.size < a.offset+a.size) addtjoint(g, a, e.offset+e.size); } if(!(e.flags&CE_DUP)) { if(a.flags&CE_START && a.offset > e.offset && a.offset < e.offset+e.size) addtjoint(g, e, a.offset); if(a.flags&CE_END && a.offset+a.size > e.offset && a.offset+a.size < e.offset+e.size) addtjoint(g, e, a.offset+a.size); } } curactive = a.next; } int next = e.next; e.next = active; active = cur; cur = next; } } void findtjoints() { recalcprogress = 0; gencubeedges(); tjoints.setsize(0); enumeratekt(edgegroups, edgegroup, g, int, e, findtjoints(e, g)); cubeedges.setsize(0); edgegroups.clear(); } void octarender() // creates va s for all leaf cubes that don't already have them { int csi = 0; while(1<explicitsky; skyarea += va->skyarea; } extern vtxarray *visibleva; visibleva = NULL; } void precachetextures() { vector texs; loopv(valist) { vtxarray *va = valist[i]; loopj(va->texs + va->blends) if(texs.find(va->eslist[j].texture) < 0) texs.add(va->eslist[j].texture); } loopv(texs) { loadprogress = float(i+1)/texs.length(); lookupvslot(texs[i]); } loadprogress = 0; } void allchanged(bool load) { renderprogress(0, "clearing vertex arrays..."); clearvas(worldroot); resetqueries(); resetclipplanes(); if(load) initenvmaps(); guessshadowdir(); entitiesinoctanodes(); tjoints.setsize(0); if(filltjoints) findtjoints(); octarender(); if(load) precachetextures(); setupmaterials(); invalidatepostfx(); updatevabbs(true); resetblobs(); lightents(); if(load) { seedparticles(); drawtextures(); } } void recalc() { allchanged(true); } COMMAND(recalc, ""); sauerbraten-0.0.20130203.dfsg/engine/obj.h0000644000175000017500000001756112072642735017607 0ustar vincentvincentstruct obj; struct obj : vertmodel, vertloader { obj(const char *name) : vertmodel(name) {} static const char *formatname() { return "obj"; } static bool animated() { return false; } int type() const { return MDL_OBJ; } struct objmeshgroup : vertmeshgroup { void parsevert(char *s, vector &out) { vec &v = out.add(vec(0, 0, 0)); while(isalpha(*s)) s++; loopi(3) { v[i] = strtod(s, &s); while(isspace(*s)) s++; if(!*s) break; } } bool load(const char *filename, float smooth) { int len = strlen(filename); if(len < 4 || strcasecmp(&filename[len-4], ".obj")) return false; stream *file = openfile(filename, "rb"); if(!file) return false; name = newstring(filename); numframes = 1; vector attrib[3]; char buf[512]; hashtable verthash; vector verts; vector tcverts; vector tris; #define STARTMESH do { \ vertmesh &m = *new vertmesh; \ m.group = this; \ m.name = meshname[0] ? newstring(meshname) : NULL; \ meshes.add(&m); \ curmesh = &m; \ verthash.clear(); \ verts.setsize(0); \ tcverts.setsize(0); \ tris.setsize(0); \ } while(0) #define FLUSHMESH do { \ curmesh->numverts = verts.length(); \ if(verts.length()) \ { \ curmesh->verts = new vert[verts.length()]; \ memcpy(curmesh->verts, verts.getbuf(), verts.length()*sizeof(vert)); \ curmesh->tcverts = new tcvert[verts.length()]; \ memcpy(curmesh->tcverts, tcverts.getbuf(), tcverts.length()*sizeof(tcvert)); \ } \ curmesh->numtris = tris.length(); \ if(tris.length()) \ { \ curmesh->tris = new tri[tris.length()]; \ memcpy(curmesh->tris, tris.getbuf(), tris.length()*sizeof(tri)); \ } \ if(attrib[2].empty()) \ { \ if(smooth <= 1) curmesh->smoothnorms(smooth); \ else curmesh->buildnorms(); \ } \ } while(0) string meshname = ""; vertmesh *curmesh = NULL; while(file->getline(buf, sizeof(buf))) { char *c = buf; while(isspace(*c)) c++; switch(*c) { case '#': continue; case 'v': if(isspace(c[1])) parsevert(c, attrib[0]); else if(c[1]=='t') parsevert(c, attrib[1]); else if(c[1]=='n') parsevert(c, attrib[2]); break; case 'g': { while(isalpha(*c)) c++; while(isspace(*c)) c++; char *name = c; size_t namelen = strlen(name); while(namelen > 0 && isspace(name[namelen-1])) namelen--; copystring(meshname, name, min(namelen+1, sizeof(meshname))); if(curmesh) FLUSHMESH; curmesh = NULL; break; } case 'f': { if(!curmesh) STARTMESH; int v0 = -1, v1 = -1; while(isalpha(*c)) c++; for(;;) { while(isspace(*c)) c++; if(!*c) break; ivec vkey(-1, -1, -1); loopi(3) { vkey[i] = strtol(c, &c, 10); if(vkey[i] < 0) vkey[i] = attrib[i].length() + vkey[i]; else vkey[i]--; if(!attrib[i].inrange(vkey[i])) vkey[i] = -1; if(*c!='/') break; c++; } int *index = verthash.access(vkey); if(!index) { index = &verthash[vkey]; *index = verts.length(); vert &v = verts.add(); v.pos = vkey.x < 0 ? vec(0, 0, 0) : attrib[0][vkey.x]; v.pos = vec(v.pos.z, -v.pos.x, v.pos.y); v.norm = vkey.z < 0 ? vec(0, 0, 0) : attrib[2][vkey.z]; v.norm = vec(v.norm.z, -v.norm.x, v.norm.y); tcvert &tcv = tcverts.add(); if(vkey.y < 0) tcv.u = tcv.v = 0; else { tcv.u = attrib[1][vkey.y].x; tcv.v = 1-attrib[1][vkey.y].y; } } if(v0 < 0) v0 = *index; else if(v1 < 0) v1 = *index; else { tri &t = tris.add(); t.vert[0] = ushort(*index); t.vert[1] = ushort(v1); t.vert[2] = ushort(v0); v1 = *index; } } break; } } } if(curmesh) FLUSHMESH; delete file; return true; } }; meshgroup *loadmeshes(const char *name, va_list args) { objmeshgroup *group = new objmeshgroup; if(!group->load(name, va_arg(args, double))) { delete group; return NULL; } return group; } bool loaddefaultparts() { part &mdl = *new part; parts.add(&mdl); mdl.model = this; mdl.index = 0; const char *pname = parentdir(loadname); defformatstring(name1)("packages/models/%s/tris.obj", loadname); mdl.meshes = sharemeshes(path(name1), 2.0); if(!mdl.meshes) { defformatstring(name2)("packages/models/%s/tris.obj", pname); // try obj in parent folder (vert sharing) mdl.meshes = sharemeshes(path(name2), 2.0); if(!mdl.meshes) return false; } Texture *tex, *masks; loadskin(loadname, pname, tex, masks); mdl.initskins(tex, masks); if(tex==notexture) conoutf("could not load model skin for %s", name1); return true; } bool load() { if(loaded) return true; formatstring(dir)("packages/models/%s", loadname); defformatstring(cfgname)("packages/models/%s/obj.cfg", loadname); loading = this; identflags &= ~IDF_PERSIST; if(execfile(cfgname, false) && parts.length()) // configured obj, will call the obj* commands below { identflags |= IDF_PERSIST; loading = NULL; loopv(parts) if(!parts[i]->meshes) return false; } else // obj without configuration, try default tris and skin { identflags |= IDF_PERSIST; loading = NULL; if(!loaddefaultparts()) return false; } scale /= 4; translate.y = -translate.y; parts[0]->translate = translate; loopv(parts) parts[i]->meshes->shared++; return loaded = true; } }; vertcommands objcommands; sauerbraten-0.0.20130203.dfsg/engine/world.cpp0000644000175000017500000010611312071437735020510 0ustar vincentvincent// world.cpp: core map management stuff #include "engine.h" VARR(mapversion, 1, MAPVERSION, 0); VARNR(mapscale, worldscale, 1, 0, 0); VARNR(mapsize, worldsize, 1, 0, 0); SVARR(maptitle, "Untitled Map by Unknown"); VAR(octaentsize, 0, 128, 1024); VAR(entselradius, 0, 2, 10); bool getentboundingbox(extentity &e, ivec &o, ivec &r) { switch(e.type) { case ET_EMPTY: return false; case ET_MAPMODEL: { model *m = loadmodel(NULL, e.attr2); if(m) { vec center, radius; m->boundbox(0, center, radius); rotatebb(center, radius, e.attr1); o = e.o; o.add(center); r = radius; r.add(1); o.sub(r); r.mul(2); break; } } // invisible mapmodels use entselradius default: o = e.o; o.sub(entselradius); r.x = r.y = r.z = entselradius*2; break; } return true; } enum { MODOE_ADD = 1<<0, MODOE_UPDATEBB = 1<<1, MODOE_LIGHTENT = 1<<2 }; void modifyoctaentity(int flags, int id, extentity &e, cube *c, const ivec &cor, int size, const ivec &bo, const ivec &br, int leafsize, vtxarray *lastva = NULL) { loopoctabox(cor, size, bo, br) { ivec o(i, cor.x, cor.y, cor.z, size); vtxarray *va = c[i].ext && c[i].ext->va ? c[i].ext->va : lastva; if(c[i].children != NULL && size > leafsize) modifyoctaentity(flags, id, e, c[i].children, o, size>>1, bo, br, leafsize, va); else if(flags&MODOE_ADD) { if(!c[i].ext || !c[i].ext->ents) ext(c[i]).ents = new octaentities(o, size); octaentities &oe = *c[i].ext->ents; switch(e.type) { case ET_MAPMODEL: if(loadmodel(NULL, e.attr2)) { if(va) { va->bbmin.x = -1; if(oe.mapmodels.empty()) va->mapmodels.add(&oe); } oe.mapmodels.add(id); loopk(3) { oe.bbmin[k] = min(oe.bbmin[k], max(oe.o[k], bo[k])); oe.bbmax[k] = max(oe.bbmax[k], min(oe.o[k]+size, bo[k]+br[k])); } break; } // invisible mapmodel default: oe.other.add(id); break; } } else if(c[i].ext && c[i].ext->ents) { octaentities &oe = *c[i].ext->ents; switch(e.type) { case ET_MAPMODEL: if(loadmodel(NULL, e.attr2)) { oe.mapmodels.removeobj(id); if(va) { va->bbmin.x = -1; if(oe.mapmodels.empty()) va->mapmodels.removeobj(&oe); } oe.bbmin = oe.bbmax = oe.o; oe.bbmin.add(oe.size); loopvj(oe.mapmodels) { extentity &e = *entities::getents()[oe.mapmodels[j]]; ivec eo, er; if(getentboundingbox(e, eo, er)) loopk(3) { oe.bbmin[k] = min(oe.bbmin[k], eo[k]); oe.bbmax[k] = max(oe.bbmax[k], eo[k]+er[k]); } } loopk(3) { oe.bbmin[k] = max(oe.bbmin[k], oe.o[k]); oe.bbmax[k] = min(oe.bbmax[k], oe.o[k]+size); } break; } // invisible mapmodel default: oe.other.removeobj(id); break; } if(oe.mapmodels.empty() && oe.other.empty()) freeoctaentities(c[i]); } if(c[i].ext && c[i].ext->ents) c[i].ext->ents->query = NULL; if(va && va!=lastva) { if(lastva) { if(va->bbmin.x < 0) lastva->bbmin.x = -1; } else if(flags&MODOE_UPDATEBB) updatevabb(va); } } } vector outsideents; static bool modifyoctaent(int flags, int id, extentity &e) { if(flags&MODOE_ADD ? e.inoctanode : !e.inoctanode) return false; ivec o, r; if(!getentboundingbox(e, o, r)) return false; if(!insideworld(e.o)) { int idx = outsideents.find(id); if(flags&MODOE_ADD) { if(idx < 0) outsideents.add(id); } else if(idx >= 0) outsideents.removeunordered(idx); } else { int leafsize = octaentsize, limit = max(r.x, max(r.y, r.z)); while(leafsize < limit) leafsize *= 2; int diff = ~(leafsize-1) & ((o.x^(o.x+r.x))|(o.y^(o.y+r.y))|(o.z^(o.z+r.z))); if(diff && (limit > octaentsize/2 || diff < leafsize*2)) leafsize *= 2; modifyoctaentity(flags, id, e, worldroot, ivec(0, 0, 0), worldsize>>1, o, r, leafsize); } e.inoctanode = flags&MODOE_ADD ? 1 : 0; if(e.type == ET_LIGHT) clearlightcache(id); else if(e.type == ET_PARTICLES) clearparticleemitters(); else if(flags&MODOE_LIGHTENT) lightent(e); return true; } static inline bool modifyoctaent(int flags, int id) { vector &ents = entities::getents(); return ents.inrange(id) && modifyoctaent(flags, id, *ents[id]); } static inline void addentity(int id) { modifyoctaent(MODOE_ADD|MODOE_UPDATEBB|MODOE_LIGHTENT, id); } static inline void removeentity(int id) { modifyoctaent(MODOE_UPDATEBB, id); } void freeoctaentities(cube &c) { if(!c.ext) return; if(entities::getents().length()) { while(c.ext->ents && !c.ext->ents->mapmodels.empty()) removeentity(c.ext->ents->mapmodels.pop()); while(c.ext->ents && !c.ext->ents->other.empty()) removeentity(c.ext->ents->other.pop()); } if(c.ext->ents) { delete c.ext->ents; c.ext->ents = NULL; } } void entitiesinoctanodes() { vector &ents = entities::getents(); loopv(ents) modifyoctaent(MODOE_ADD, i, *ents[i]); } static inline void findents(octaentities &oe, int low, int high, bool notspawned, const vec &pos, const vec &radius, vector &found) { vector &ents = entities::getents(); loopv(oe.other) { int id = oe.other[i]; extentity &e = *ents[id]; if(e.type >= low && e.type <= high && (e.spawned || notspawned) && vec(e.o).mul(radius).squaredlen() <= 1) found.add(id); } } static inline void findents(cube *c, const ivec &o, int size, const ivec &bo, const ivec &br, int low, int high, bool notspawned, const vec &pos, const vec &radius, vector &found) { loopoctabox(o, size, bo, br) { if(c[i].ext && c[i].ext->ents) findents(*c[i].ext->ents, low, high, notspawned, pos, radius, found); if(c[i].children && size > octaentsize) { ivec co(i, o.x, o.y, o.z, size); findents(c[i].children, co, size>>1, bo, br, low, high, notspawned, pos, radius, found); } } } void findents(int low, int high, bool notspawned, const vec &pos, const vec &radius, vector &found) { vec invradius(1/radius.x, 1/radius.y, 1/radius.z); ivec bo = vec(pos).sub(radius).sub(1), br = vec(radius).add(1).mul(2); int diff = (bo.x^(bo.x+br.x)) | (bo.y^(bo.y+br.y)) | (bo.z^(bo.z+br.z)) | octaentsize, scale = worldscale-1; if(diff&~((1<= uint(worldsize)) { findents(worldroot, ivec(0, 0, 0), 1<ext && c->ext->ents) findents(*c->ext->ents, low, high, notspawned, pos, invradius, found); scale--; while(c->children && !(diff&(1<children[octastep(bo.x, bo.y, bo.z, scale)]; if(c->ext && c->ext->ents) findents(*c->ext->ents, low, high, notspawned, pos, invradius, found); scale--; } if(c->children && 1<= octaentsize) findents(c->children, ivec(bo).mask(~((2<= sel.o.x && o.y <= sel.o.y+sel.s.y*sel.grid && o.y >= sel.o.y && o.z <= sel.o.z+sel.s.z*sel.grid && o.z >= sel.o.z); } vector entgroup; bool haveselent() { return entgroup.length() > 0; } void entcancel() { entgroup.shrink(0); } void entadd(int id) { undonext = true; entgroup.add(id); } undoblock *newundoent() { int numents = entgroup.length(); if(numents <= 0) return NULL; undoblock *u = (undoblock *)new uchar[sizeof(undoblock) + numents*sizeof(undoent)]; u->numents = numents; undoent *e = (undoent *)(u + 1); loopv(entgroup) { e->i = entgroup[i]; e->e = *entities::getents()[entgroup[i]]; e++; } return u; } void makeundoent() { if(!undonext) return; undonext = false; oldhover = enthover; undoblock *u = newundoent(); if(u) addundo(u); } void detachentity(extentity &e) { if(!e.attached) return; e.attached->attached = NULL; e.attached = NULL; } VAR(attachradius, 1, 100, 1000); void attachentity(extentity &e) { switch(e.type) { case ET_SPOTLIGHT: break; default: if(e.type &ents = entities::getents(); int closest = -1; float closedist = 1e10f; loopv(ents) { extentity *a = ents[i]; if(a->attached) continue; switch(e.type) { case ET_SPOTLIGHT: if(a->type!=ET_LIGHT) continue; break; default: if(e.typeo); if(dist < closedist) { closest = i; closedist = dist; } } if(closedist>attachradius) return; e.attached = ents[closest]; ents[closest]->attached = &e; } void attachentities() { vector &ents = entities::getents(); loopv(ents) attachentity(*ents[i]); } // convenience macros implicitly define: // e entity, currently edited ent // n int, index to currently edited ent #define addimplicit(f) { if(entgroup.empty() && enthover>=0) { entadd(enthover); undonext = (enthover != oldhover); f; entgroup.drop(); } else f; } #define entfocus(i, f) { int n = efocus = (i); if(n>=0) { extentity &e = *entities::getents()[n]; f; } } #define entedit(i, f) \ { \ entfocus(i, \ int oldtype = e.type; \ removeentity(n); \ f; \ if(oldtype!=e.type) detachentity(e); \ if(e.type!=ET_EMPTY) { addentity(n); if(oldtype!=e.type) attachentity(e); } \ entities::editent(n, true)); \ } #define addgroup(exp) { loopv(entities::getents()) entfocus(i, if(exp) entadd(n)); } #define setgroup(exp) { entcancel(); addgroup(exp); } #define groupeditloop(f){ entlooplevel++; int _ = efocus; loopv(entgroup) entedit(entgroup[i], f); efocus = _; entlooplevel--; } #define groupeditpure(f){ if(entlooplevel>0) { entedit(efocus, f); } else groupeditloop(f); } #define groupeditundo(f){ makeundoent(); groupeditpure(f); } #define groupedit(f) { addimplicit(groupeditundo(f)); } vec getselpos() { vector &ents = entities::getents(); if(entgroup.length() && ents.inrange(entgroup[0])) return ents[entgroup[0]]->o; if(ents.inrange(enthover)) return ents[enthover]->o; return sel.o.tovec(); } undoblock *copyundoents(undoblock *u) { entcancel(); undoent *e = u->ents(); loopi(u->numents) entadd(e[i].i); undoblock *c = newundoent(); loopi(u->numents) if(e[i].e.type==ET_EMPTY) entgroup.removeobj(e[i].i); return c; } void pasteundoents(undoblock *u) { undoent *ue = u->ents(); loopi(u->numents) entedit(ue[i].i, (entity &)e = ue[i].e); } void entflip() { if(noentedit()) return; int d = dimension(sel.orient); float mid = sel.s[d]*sel.grid/2+sel.o[d]; groupeditundo(e.o[d] -= (e.o[d]-mid)*2); } void entrotate(int *cw) { if(noentedit()) return; int d = dimension(sel.orient); int dd = (*cw<0) == dimcoord(sel.orient) ? R[d] : C[d]; float mid = sel.s[dd]*sel.grid/2+sel.o[dd]; vec s(sel.o.v); groupeditundo( e.o[dd] -= (e.o[dd]-mid)*2; e.o.sub(s); swap(e.o[R[d]], e.o[C[d]]); e.o.add(s); ); } void entselectionbox(const entity &e, vec &eo, vec &es) { model *m = NULL; const char *mname = entities::entmodel(e); if(mname && (m = loadmodel(mname))) { m->collisionbox(0, eo, es); if(es.x > es.y) es.y = es.x; else es.x = es.y; // square es.z = (es.z + eo.z + 1 + entselradius)/2; // enclose ent radius box and model box eo.x += e.o.x; eo.y += e.o.y; eo.z = e.o.z - entselradius + es.z; } else if(e.type == ET_MAPMODEL && (m = loadmodel(NULL, e.attr2))) { m->collisionbox(0, eo, es); rotatebb(eo, es, e.attr1); #if 0 if(m->collide) eo.z -= player->aboveeye; // wacky but true. see physics collide else es.div(2); // cause the usual bb is too big... #endif eo.add(e.o); } else { es = vec(entselradius); eo = e.o; } eo.sub(es); es.mul(2); } VAR(entselsnap, 0, 0, 1); VAR(entmovingshadow, 0, 1, 1); extern void boxs(int orient, vec o, const vec &s); extern void boxs3D(const vec &o, vec s, int g); extern void editmoveplane(const vec &o, const vec &ray, int d, float off, vec &handle, vec &dest, bool first); bool initentdragging = true; void entdrag(const vec &ray) { if(noentedit() || !haveselent()) return; float r = 0, c = 0; static vec v, handle; vec eo, es; int d = dimension(entorient), dc= dimcoord(entorient); entfocus(entgroup.last(), entselectionbox(e, eo, es); editmoveplane(e.o, ray, d, eo[d] + (dc ? es[d] : 0), handle, v, initentdragging); ivec g(v); int z = g[d]&(~(sel.grid-1)); g.add(sel.grid/2).mask(~(sel.grid-1)); g[d] = z; r = (entselsnap ? g[R[d]] : v[R[d]]) - e.o[R[d]]; c = (entselsnap ? g[C[d]] : v[C[d]]) - e.o[C[d]]; ); if(initentdragging) makeundoent(); groupeditpure(e.o[R[d]] += r; e.o[C[d]] += c); initentdragging = false; } VAR(showentradius, 0, 1, 1); void renderentring(const extentity &e, float radius, int axis) { if(radius <= 0) return; glBegin(GL_LINE_LOOP); loopi(15) { vec p(e.o); const vec2 &sc = sincos360[i*(360/15)]; p[axis>=2 ? 1 : 0] += radius*sc.x; p[axis>=1 ? 2 : 1] += radius*sc.y; glVertex3fv(p.v); } glEnd(); } void renderentsphere(const extentity &e, float radius) { if(radius <= 0) return; loopk(3) renderentring(e, radius, k); } void renderentattachment(const extentity &e) { if(!e.attached) return; glBegin(GL_LINES); glVertex3fv(e.o.v); glVertex3fv(e.attached->o.v); glEnd(); } void renderentarrow(const extentity &e, const vec &dir, float radius) { if(radius <= 0) return; float arrowsize = min(radius/8, 0.5f); vec target = vec(dir).mul(radius).add(e.o), arrowbase = vec(dir).mul(radius - arrowsize).add(e.o), spoke; spoke.orthogonal(dir); spoke.normalize(); spoke.mul(arrowsize); glBegin(GL_LINES); glVertex3fv(e.o.v); glVertex3fv(target.v); glEnd(); glBegin(GL_TRIANGLE_FAN); glVertex3fv(target.v); loopi(5) { vec p(spoke); p.rotate(2*M_PI*i/4.0f, dir); p.add(arrowbase); glVertex3fv(p.v); } glEnd(); } void renderentcone(const extentity &e, const vec &dir, float radius, float angle) { if(radius <= 0) return; vec spot = vec(dir).mul(radius*cosf(angle*RAD)).add(e.o), spoke; spoke.orthogonal(dir); spoke.normalize(); spoke.mul(radius*sinf(angle*RAD)); glBegin(GL_LINES); loopi(8) { vec p(spoke); p.rotate(2*M_PI*i/8.0f, dir); p.add(spot); glVertex3fv(e.o.v); glVertex3fv(p.v); } glEnd(); glBegin(GL_LINE_LOOP); loopi(8) { vec p(spoke); p.rotate(2*M_PI*i/8.0f, dir); p.add(spot); glVertex3fv(p.v); } glEnd(); } void renderentradius(extentity &e, bool color) { switch(e.type) { case ET_LIGHT: if(color) glColor3f(e.attr2/255.0f, e.attr3/255.0f, e.attr4/255.0f); renderentsphere(e, e.attr1); break; case ET_SPOTLIGHT: if(e.attached) { if(color) glColor3f(0, 1, 1); float radius = e.attached->attr1; if(!radius) radius = 2*e.o.dist(e.attached->o); vec dir = vec(e.o).sub(e.attached->o).normalize(); float angle = clamp(int(e.attr1), 1, 89); renderentattachment(e); renderentcone(*e.attached, dir, radius, angle); } break; case ET_SOUND: if(color) glColor3f(0, 1, 1); renderentsphere(e, e.attr2); break; case ET_ENVMAP: { extern int envmapradius; if(color) glColor3f(0, 1, 1); renderentsphere(e, e.attr1 ? max(0, min(10000, int(e.attr1))) : envmapradius); break; } case ET_MAPMODEL: case ET_PLAYERSTART: { if(color) glColor3f(0, 1, 1); entities::entradius(e, color); vec dir; vecfromyawpitch(e.attr1, 0, 1, 0, dir); renderentarrow(e, dir, 4); break; } default: if(e.type>=ET_GAMESPECIFIC) { if(color) glColor3f(0, 1, 1); entities::entradius(e, color); } break; } } void renderentselection(const vec &o, const vec &ray, bool entmoving) { if(noentedit()) return; vec eo, es; glColor3ub(0, 40, 0); loopv(entgroup) entfocus(entgroup[i], entselectionbox(e, eo, es); boxs3D(eo, es, 1); ); if(enthover >= 0) { entfocus(enthover, entselectionbox(e, eo, es)); // also ensures enthover is back in focus boxs3D(eo, es, 1); if(entmoving && entmovingshadow==1) { vec a, b; glColor3ub(20, 20, 20); (a = eo).x = eo.x - fmod(eo.x, worldsize); (b = es).x = a.x + worldsize; boxs3D(a, b, 1); (a = eo).y = eo.y - fmod(eo.y, worldsize); (b = es).y = a.x + worldsize; boxs3D(a, b, 1); (a = eo).z = eo.z - fmod(eo.z, worldsize); (b = es).z = a.x + worldsize; boxs3D(a, b, 1); } glColor3ub(150,0,0); glLineWidth(5); boxs(entorient, eo, es); glLineWidth(1); } if(showentradius && (entgroup.length() || enthover >= 0)) { glDepthFunc(GL_GREATER); glColor3f(0.25f, 0.25f, 0.25f); loopv(entgroup) entfocus(entgroup[i], renderentradius(e, false)); if(enthover>=0) entfocus(enthover, renderentradius(e, false)); glDepthFunc(GL_LESS); loopv(entgroup) entfocus(entgroup[i], renderentradius(e, true)); if(enthover>=0) entfocus(enthover, renderentradius(e, true)); } } bool enttoggle(int id) { undonext = true; int i = entgroup.find(id); if(i < 0) entadd(id); else entgroup.remove(i); return i < 0; } bool hoveringonent(int ent, int orient) { if(noentedit()) return false; entorient = orient; if((efocus = enthover = ent) >= 0) return true; efocus = entgroup.empty() ? -1 : entgroup.last(); enthover = -1; return false; } VAR(entitysurf, 0, 0, 1); VARF(entmoving, 0, 0, 2, if(enthover < 0 || noentedit()) entmoving = 0; else if(entmoving == 1) entmoving = enttoggle(enthover); else if(entmoving == 2 && entgroup.find(enthover) < 0) entadd(enthover); if(entmoving > 0) initentdragging = true; ); void entpush(int *dir) { if(noentedit()) return; int d = dimension(entorient); int s = dimcoord(entorient) ? -*dir : *dir; if(entmoving) { groupeditpure(e.o[d] += float(s*sel.grid)); // editdrag supplies the undo } else groupedit(e.o[d] += float(s*sel.grid)); if(entitysurf==1) { player->o[d] += float(s*sel.grid); player->resetinterp(); } } VAR(entautoviewdist, 0, 25, 100); void entautoview(int *dir) { if(!haveselent()) return; static int s = 0; vec v(player->o); v.sub(worldpos); v.normalize(); v.mul(entautoviewdist); int t = s + *dir; s = abs(t) % entgroup.length(); if(t<0 && s>0) s = entgroup.length() - s; entfocus(entgroup[s], v.add(e.o); player->o = v; player->resetinterp(); ); } COMMAND(entautoview, "i"); COMMAND(entflip, ""); COMMAND(entrotate, "i"); COMMAND(entpush, "i"); void delent() { if(noentedit()) return; groupedit(e.type = ET_EMPTY;); entcancel(); } int findtype(char *what) { for(int i = 0; *entities::entname(i); i++) if(strcmp(what, entities::entname(i))==0) return i; conoutf(CON_ERROR, "unknown entity type \"%s\"", what); return ET_EMPTY; } VAR(entdrop, 0, 2, 3); bool dropentity(entity &e, int drop = -1) { vec radius(4.0f, 4.0f, 4.0f); if(drop<0) drop = entdrop; if(e.type == ET_MAPMODEL) { model *m = loadmodel(NULL, e.attr2); if(m) { vec center; m->boundbox(0, center, radius); rotatebb(center, radius, e.attr1); radius.x += fabs(center.x); radius.y += fabs(center.y); } radius.z = 0.0f; } switch(drop) { case 1: if(e.type != ET_LIGHT && e.type != ET_SPOTLIGHT) dropenttofloor(&e); break; case 2: case 3: int cx = 0, cy = 0; if(sel.cxs == 1 && sel.cys == 1) { cx = (sel.cx ? 1 : -1) * sel.grid / 2; cy = (sel.cy ? 1 : -1) * sel.grid / 2; } e.o = sel.o.tovec(); int d = dimension(sel.orient), dc = dimcoord(sel.orient); e.o[R[d]] += sel.grid / 2 + cx; e.o[C[d]] += sel.grid / 2 + cy; if(!dc) e.o[D[d]] -= radius[D[d]]; else e.o[D[d]] += sel.grid + radius[D[d]]; if(drop == 3) dropenttofloor(&e); break; } return true; } void dropent() { if(noentedit()) return; groupedit(dropentity(e)); } void attachent() { if(noentedit()) return; groupedit(attachentity(e)); } COMMAND(attachent, ""); static int keepents = 0; extentity *newentity(bool local, const vec &o, int type, int v1, int v2, int v3, int v4, int v5, int &idx) { vector &ents = entities::getents(); if(local) { idx = -1; for(int i = keepents; i < ents.length(); i++) if(ents[i]->type == ET_EMPTY) { idx = i; break; } if(idx < 0 && ents.length() >= MAXENTS) { conoutf("too many entities"); return NULL; } } else while(ents.length() < idx) ents.add(entities::newentity())->type = ET_EMPTY; extentity &e = *entities::newentity(); e.o = o; e.attr1 = v1; e.attr2 = v2; e.attr3 = v3; e.attr4 = v4; e.attr5 = v5; e.type = type; e.reserved = 0; e.spawned = false; e.inoctanode = false; e.light.color = vec(1, 1, 1); e.light.dir = vec(0, 0, 1); if(local) { switch(type) { case ET_MAPMODEL: case ET_PLAYERSTART: e.attr5 = e.attr4; e.attr4 = e.attr3; e.attr3 = e.attr2; e.attr2 = e.attr1; e.attr1 = (int)camera1->yaw; break; } entities::fixentity(e); } if(ents.inrange(idx)) { entities::deleteentity(ents[idx]); ents[idx] = &e; } else { idx = ents.length(); ents.add(&e); } return &e; } void newentity(int type, int a1, int a2, int a3, int a4, int a5) { int idx; extentity *t = newentity(true, player->o, type, a1, a2, a3, a4, a5, idx); if(!t) return; dropentity(*t); t->type = ET_EMPTY; enttoggle(idx); makeundoent(); entedit(idx, e.type = type); } void newent(char *what, int *a1, int *a2, int *a3, int *a4, int *a5) { if(noentedit()) return; int type = findtype(what); if(type != ET_EMPTY) newentity(type, *a1, *a2, *a3, *a4, *a5); } int entcopygrid; vector entcopybuf; void entcopy() { if(noentedit()) return; entcopygrid = sel.grid; entcopybuf.shrink(0); loopv(entgroup) entfocus(entgroup[i], entcopybuf.add(e).o.sub(sel.o.tovec())); } void entpaste() { if(noentedit()) return; if(entcopybuf.length()==0) return; entcancel(); float m = float(sel.grid)/float(entcopygrid); loopv(entcopybuf) { entity &c = entcopybuf[i]; vec o(c.o); o.mul(m).add(sel.o.tovec()); int idx; extentity *e = newentity(true, o, ET_EMPTY, c.attr1, c.attr2, c.attr3, c.attr4, c.attr5, idx); if(!e) continue; entadd(idx); keepents = max(keepents, idx+1); } keepents = 0; int j = 0; groupeditundo(e.type = entcopybuf[j++].type;); } COMMAND(newent, "siiiii"); COMMAND(delent, ""); COMMAND(dropent, ""); COMMAND(entcopy, ""); COMMAND(entpaste, ""); void entset(char *what, int *a1, int *a2, int *a3, int *a4, int *a5) { if(noentedit()) return; int type = findtype(what); if(type != ET_EMPTY) groupedit(e.type=type; e.attr1=*a1; e.attr2=*a2; e.attr3=*a3; e.attr4=*a4; e.attr5=*a5); } void printent(extentity &e, char *buf) { switch(e.type) { case ET_PARTICLES: if(printparticles(e, buf)) return; break; default: if(e.type >= ET_GAMESPECIFIC && entities::printent(e, buf)) return; break; } formatstring(buf)("%s %d %d %d %d %d", entities::entname(e.type), e.attr1, e.attr2, e.attr3, e.attr4, e.attr5); } void nearestent() { if(noentedit()) return; int closest = -1; float closedist = 1e16f; vector &ents = entities::getents(); loopv(ents) { extentity &e = *ents[i]; if(e.type == ET_EMPTY) continue; float dist = e.o.dist(player->o); if(dist < closedist) { closest = i; closedist = dist; } } if(closest >= 0) entadd(closest); } ICOMMAND(enthavesel,"", (), addimplicit(intret(entgroup.length()))); ICOMMAND(entselect, "e", (uint *body), if(!noentedit()) addgroup(e.type != ET_EMPTY && entgroup.find(n)<0 && executebool(body))); ICOMMAND(entloop, "e", (uint *body), if(!noentedit()) addimplicit(groupeditloop(((void)e, execute(body))))); ICOMMAND(insel, "", (), entfocus(efocus, intret(pointinsel(sel, e.o)))); ICOMMAND(entget, "", (), entfocus(efocus, string s; printent(e, s); result(s))); ICOMMAND(entindex, "", (), intret(efocus)); COMMAND(entset, "siiiii"); COMMAND(nearestent, ""); void enttype(char *type, int *numargs) { if(*numargs >= 1) { int typeidx = findtype(type); if(typeidx != ET_EMPTY) groupedit(e.type = typeidx); } else entfocus(efocus, { result(entities::entname(e.type)); }) } void entattr(int *attr, int *val, int *numargs) { if(*numargs >= 2) { if(*attr >= 0 && *attr <= 4) groupedit( switch(*attr) { case 0: e.attr1 = *val; break; case 1: e.attr2 = *val; break; case 2: e.attr3 = *val; break; case 3: e.attr4 = *val; break; case 4: e.attr5 = *val; break; } ); } else entfocus(efocus, { switch(*attr) { case 0: intret(e.attr1); break; case 1: intret(e.attr2); break; case 2: intret(e.attr3); break; case 3: intret(e.attr4); break; case 4: intret(e.attr5); break; } }); } COMMAND(enttype, "sN"); COMMAND(entattr, "iiN"); int findentity(int type, int index, int attr1, int attr2) { const vector &ents = entities::getents(); for(int i = index; ipitch = 0; d->roll = 0; for(int attempt = pick;;) { d->o = entities::getents()[attempt]->o; d->yaw = entities::getents()[attempt]->attr1; if(entinmap(d, true)) break; attempt = findentity(ET_PLAYERSTART, attempt+1, -1, tag); if(attempt<0 || attempt==pick) { d->o = entities::getents()[attempt]->o; d->yaw = entities::getents()[attempt]->attr1; entinmap(d); break; } } } else { d->o.x = d->o.y = d->o.z = 0.5f*worldsize; d->o.z += 1; entinmap(d); } } void splitocta(cube *c, int size) { if(size <= 0x1000) return; loopi(8) { if(!c[i].children) c[i].children = newcubes(isempty(c[i]) ? F_EMPTY : F_SOLID); splitocta(c[i].children, size>>1); } } void resetmap() { clearoverrides(); clearmapsounds(); cleanreflections(); resetblendmap(); resetlightmaps(); clearpvs(); clearslots(); clearparticles(); cleardecals(); clearsleep(); cancelsel(); pruneundos(); clearmapcrc(); entities::clearents(); outsideents.setsize(0); } void startmap(const char *name) { game::startmap(name); } bool emptymap(int scale, bool force, const char *mname, bool usecfg) // main empty world creation routine { if(!force && !editmode) { conoutf(CON_ERROR, "newmap only allowed in edit mode"); return false; } resetmap(); setvar("mapscale", scale<10 ? 10 : (scale>16 ? 16 : scale), true, false); setvar("mapsize", 1< 0x1000) splitocta(worldroot, worldsize>>1); clearmainmenu(); if(usecfg) { identflags |= IDF_OVERRIDDEN; execfile("data/default_map_settings.cfg", false); identflags &= ~IDF_OVERRIDDEN; } initlights(); allchanged(true); startmap(mname); return true; } bool enlargemap(bool force) { if(!force && !editmode) { conoutf(CON_ERROR, "mapenlarge only allowed in edit mode"); return false; } if(worldsize >= 1<<16) return false; while(outsideents.length()) removeentity(outsideents.pop()); worldscale++; worldsize *= 2; cube *c = newcubes(F_EMPTY); c[0].children = worldroot; loopi(3) solidfaces(c[i+1]); worldroot = c; if(worldsize > 0x1000) splitocta(worldroot, worldsize>>1); enlargeblendmap(); allchanged(); return true; } static bool isallempty(cube &c) { if(!c.children) return isempty(c); loopi(8) if(!isallempty(c.children[i])) return false; return true; } void shrinkmap() { extern int nompedit; if(noedit(true) || (nompedit && multiplayer())) return; if(worldsize <= 1<<10) return; int octant = -1; loopi(8) if(!isallempty(worldroot[i])) { if(octant >= 0) return; octant = i; } if(octant < 0) return; while(outsideents.length()) removeentity(outsideents.pop()); if(!worldroot[octant].children) subdividecube(worldroot[octant], false, false); cube *root = worldroot[octant].children; worldroot[octant].children = NULL; freeocta(worldroot); worldroot = root; worldscale--; worldsize /= 2; ivec offset(octant, 0, 0, 0, worldsize); vector &ents = entities::getents(); loopv(ents) ents[i]->o.sub(offset.tovec()); shrinkblendmap(octant); allchanged(); conoutf("shrunk map to size %d", worldscale); } void newmap(int *i) { bool force = !isconnected(); if(force) game::forceedit(""); if(emptymap(*i, force, NULL)) game::newmap(max(*i, 0)); } void mapenlarge() { if(enlargemap(false)) game::newmap(-1); } COMMAND(newmap, "i"); COMMAND(mapenlarge, ""); COMMAND(shrinkmap, ""); void mapname() { result(game::getclientmap()); } COMMAND(mapname, ""); void mpeditent(int i, const vec &o, int type, int attr1, int attr2, int attr3, int attr4, int attr5, bool local) { if(i < 0 || i >= MAXENTS) return; vector &ents = entities::getents(); if(ents.length()<=i) { extentity *e = newentity(local, o, type, attr1, attr2, attr3, attr4, attr5, i); if(!e) return; addentity(i); attachentity(*e); } else { extentity &e = *ents[i]; removeentity(i); int oldtype = e.type; if(oldtype!=type) detachentity(e); e.type = type; e.o = o; e.attr1 = attr1; e.attr2 = attr2; e.attr3 = attr3; e.attr4 = attr4; e.attr5 = attr5; addentity(i); if(oldtype!=type) attachentity(e); } entities::editent(i, local); } int getworldsize() { return worldsize; } int getmapversion() { return mapversion; } sauerbraten-0.0.20130203.dfsg/engine/model.h0000644000175000017500000000567112072642735020134 0ustar vincentvincentenum { MDL_MD2 = 0, MDL_MD3, MDL_MD5, MDL_OBJ, MDL_SMD, MDL_IQM, NUMMODELTYPES }; struct model { float spinyaw, spinpitch, offsetyaw, offsetpitch; bool collide, ellipsecollide, shadow, alphadepth, depthoffset; float scale; vec translate; BIH *bih; vec bbcenter, bbradius, bbextend; float eyeheight, collideradius, collideheight; int batch; model() : spinyaw(0), spinpitch(0), offsetyaw(0), offsetpitch(0), collide(true), ellipsecollide(false), shadow(true), alphadepth(true), depthoffset(false), scale(1.0f), translate(0, 0, 0), bih(0), bbcenter(0, 0, 0), bbradius(0, 0, 0), bbextend(0, 0, 0), eyeheight(0.9f), collideradius(0), collideheight(0), batch(-1) {} virtual ~model() { DELETEP(bih); } virtual void calcbb(int frame, vec ¢er, vec &radius) = 0; virtual void render(int anim, int basetime, int basetime2, const vec &o, float yaw, float pitch, dynent *d, modelattach *a = NULL, const vec &color = vec(0, 0, 0), const vec &dir = vec(0, 0, 0), float transparent = 1) = 0; virtual bool load() = 0; virtual const char *name() const = 0; virtual int type() const = 0; virtual BIH *setBIH() { return 0; } virtual bool envmapped() { return false; } virtual bool skeletal() const { return false; } virtual void setshader(Shader *shader) {} virtual void setenvmap(float envmapmin, float envmapmax, Texture *envmap) {} virtual void setspec(float spec) {} virtual void setambient(float ambient) {} virtual void setglow(float glow, float glowdelta, float glowpulse) {} virtual void setglare(float specglare, float glowglare) {} virtual void setalphatest(float alpha) {} virtual void setalphablend(bool blend) {} virtual void setfullbright(float fullbright) {} virtual void setcullface(bool cullface) {} virtual void preloadBIH() { if(!bih) setBIH(); } virtual void preloadshaders() {} virtual void preloadmeshes() {} virtual void cleanup() {} virtual void startrender() {} virtual void endrender() {} void boundbox(int frame, vec ¢er, vec &radius) { if(frame) calcbb(frame, center, radius); else { if(bbradius.iszero()) calcbb(0, bbcenter, bbradius); center = bbcenter; radius = bbradius; } radius.add(bbextend); } void collisionbox(int frame, vec ¢er, vec &radius) { boundbox(frame, center, radius); if(collideradius) { center[0] = center[1] = 0; radius[0] = radius[1] = collideradius; } if(collideheight) { center[2] = radius[2] = collideheight/2; } } float boundsphere(int frame, vec ¢er) { vec radius; boundbox(frame, center, radius); return radius.magnitude(); } float above(int frame = 0) { vec center, radius; boundbox(frame, center, radius); return center.z+radius.z; } }; sauerbraten-0.0.20130203.dfsg/engine/physics.cpp0000644000175000017500000021127012072267722021042 0ustar vincentvincent// physics.cpp: no physics books were hurt nor consulted in the construction of this code. // All physics computations and constants were invented on the fly and simply tweaked until // they "felt right", and have no basis in reality. Collision detection is simplistic but // very robust (uses discrete steps at fixed fps). #include "engine.h" #include "mpr.h" const int MAXCLIPPLANES = 1024; static clipplanes clipcache[MAXCLIPPLANES]; static int clipcacheversion = -2; static inline clipplanes &getclipplanes(const cube &c, const ivec &o, int size, bool collide = true, int offset = 0) { clipplanes &p = clipcache[int(&c - worldroot)&(MAXCLIPPLANES-1)]; if(p.owner != &c || p.version != clipcacheversion+offset) { p.owner = &c; p.version = clipcacheversion+offset; genclipplanes(c, o.x, o.y, o.z, size, p, collide); } return p; } void resetclipplanes() { clipcacheversion += 2; if(!clipcacheversion) { memset(clipcache, 0, sizeof(clipcache)); clipcacheversion = 2; } } ///////////////////////// ray - cube collision /////////////////////////////////////////////// static inline bool pointinbox(const vec &v, const vec &bo, const vec &br) { return v.x <= bo.x+br.x && v.x >= bo.x-br.x && v.y <= bo.y+br.y && v.y >= bo.y-br.y && v.z <= bo.z+br.z && v.z >= bo.z-br.z; } bool pointincube(const clipplanes &p, const vec &v) { if(!pointinbox(v, p.o, p.r)) return false; loopi(p.size) if(p.p[i].dist(v)>1e-3f) return false; return true; } #define INTERSECTPLANES(setentry, exit) \ float enterdist = -1e16f, exitdist = 1e16f; \ loopi(p.size) \ { \ float pdist = p.p[i].dist(v), facing = ray.dot(p.p[i]); \ if(facing < 0) \ { \ pdist /= -facing; \ if(pdist > enterdist) \ { \ if(pdist > exitdist) exit; \ enterdist = pdist; \ setentry; \ } \ } \ else if(facing > 0) \ { \ pdist /= -facing; \ if(pdist < exitdist) \ { \ if(pdist < enterdist) exit; \ exitdist = pdist; \ } \ } \ else if(pdist > 0) exit; \ } #define INTERSECTBOX(setentry, exit) \ loop(i, 3) \ { \ if(ray[i]) \ { \ float prad = fabs(p.r[i] * invray[i]), pdist = (p.o[i] - v[i]) * invray[i], pmin = pdist - prad, pmax = pdist + prad; \ if(pmin > enterdist) \ { \ if(pmin > exitdist) exit; \ enterdist = pmin; \ setentry; \ } \ if(pmax < exitdist) \ { \ if(pmax < enterdist) exit; \ exitdist = pmax; \ } \ } \ else if(v[i] < p.o[i]-p.r[i] || v[i] > p.o[i]+p.r[i]) exit; \ } vec hitsurface; static inline bool raycubeintersect(const clipplanes &p, const cube &c, const vec &v, const vec &ray, const vec &invray, float &dist) { int entry = -1, bbentry = -1; INTERSECTPLANES(entry = i, return false); INTERSECTBOX(bbentry = i, return false); if(exitdist < 0) return false; dist = max(enterdist+0.1f, 0.0f); if(bbentry>=0) { hitsurface = vec(0, 0, 0); hitsurface[bbentry] = ray[bbentry]>0 ? -1 : 1; } else hitsurface = p.p[entry]; return true; } extern void entselectionbox(const entity &e, vec &eo, vec &es); extern int entselradius; float hitentdist; int hitent, hitorient; static float disttoent(octaentities *oc, octaentities *last, const vec &o, const vec &ray, float radius, int mode, extentity *t) { vec eo, es; int orient; float dist = 1e16f, f = 0.0f; if(oc == last) return dist; const vector &ents = entities::getents(); #define entintersect(mask, type, func) {\ if((mode&(mask))==(mask)) \ { \ loopv(oc->type) \ if(!last || last->type.find(oc->type[i])<0) \ { \ extentity &e = *ents[oc->type[i]]; \ if(!e.inoctanode || &e==t) continue; \ func; \ if(f0) \ { \ hitentdist = dist = f; \ hitent = oc->type[i]; \ hitorient = orient; \ } \ } \ } \ } entintersect(RAY_POLY, mapmodels, orient = 0; // FIXME, not set if(!mmintersect(e, o, ray, radius, mode, f)) continue; ); entintersect(RAY_ENTS, other, entselectionbox(e, eo, es); if(!rayrectintersect(eo, es, o, ray, f, orient)) continue; ); entintersect(RAY_ENTS, mapmodels, entselectionbox(e, eo, es); if(!rayrectintersect(eo, es, o, ray, f, orient)) continue; ); return dist; } static float disttooutsideent(const vec &o, const vec &ray, float radius, int mode, extentity *t) { vec eo, es; int orient; float dist = 1e16f, f = 0.0f; const vector &ents = entities::getents(); loopv(outsideents) { extentity &e = *ents[outsideents[i]]; if(!e.inoctanode || &e == t) continue; entselectionbox(e, eo, es); if(!rayrectintersect(eo, es, o, ray, f, orient)) continue; if(f0) { hitentdist = dist = f; hitent = outsideents[i]; hitorient = orient; } } return dist; } // optimized shadow version static float shadowent(octaentities *oc, octaentities *last, const vec &o, const vec &ray, float radius, int mode, extentity *t) { float dist = 1e16f, f = 0.0f; if(oc == last) return dist; const vector &ents = entities::getents(); loopv(oc->mapmodels) if(!last || last->mapmodels.find(oc->mapmodels[i])<0) { extentity &e = *ents[oc->mapmodels[i]]; if(!e.inoctanode || &e==t) continue; if(!mmintersect(e, o, ray, radius, mode, f)) continue; if(f>0 && f0 ? 1 : 0, invray.y>0 ? 1 : 0, invray.z>0 ? 1 : 0); \ #define CHECKINSIDEWORLD \ if(!insideworld(o)) \ { \ float disttoworld = 0, exitworld = 1e16f; \ loopi(3) \ { \ float c = v[i]; \ if(c<0 || c>=worldsize) \ { \ float d = ((invray[i]>0?0:worldsize)-c)*invray[i]; \ if(d<0) return (radius>0?radius:-1); \ disttoworld = max(disttoworld, 0.1f + d); \ } \ float e = ((invray[i]>0?worldsize:0)-c)*invray[i]; \ exitworld = min(exitworld, e); \ } \ if(disttoworld > exitworld) return (radius>0?radius:-1); \ v.add(vec(ray).mul(disttoworld)); \ dist += disttoworld; \ } #define DOWNOCTREE(disttoent, earlyexit) \ cube *lc = levels[lshift]; \ for(;;) \ { \ lshift--; \ lc += octastep(x, y, z, lshift); \ if(lc->ext && lc->ext->ents && lshift < elvl) \ { \ float edist = disttoent(lc->ext->ents, oclast, o, ray, radius, mode, t); \ if(edist < 1e15f) \ { \ if(earlyexit) return min(edist, dist); \ elvl = lshift; \ dent = min(dent, edist); \ } \ oclast = lc->ext->ents; \ } \ if(lc->children==NULL) break; \ lc = lc->children; \ levels[lshift] = lc; \ } #define FINDCLOSEST(xclosest, yclosest, zclosest) \ float dx = (lo.x+(lsizemask.x<= uint(worldsize)) exitworld; \ diff >>= lshift; \ if(!diff) exitworld; \ do \ { \ lshift++; \ diff >>= 1; \ } while(diff); float raycube(const vec &o, const vec &ray, float radius, int mode, int size, extentity *t) { if(ray.iszero()) return 0; INITRAYCUBE; CHECKINSIDEWORLD; int closest = -1, x = int(v.x), y = int(v.y), z = int(v.z); for(;;) { DOWNOCTREE(disttoent, mode&RAY_SHADOW); int lsize = 1<0 || !(mode&RAY_SKIPFIRST)) && (((mode&RAY_CLIPMAT) && isclipped(c.material&MATF_VOLUME)) || ((mode&RAY_EDITMAT) && c.material != MAT_AIR) || (!(mode&RAY_PASS) && lsize==size && !isempty(c)) || isentirelysolid(c) || dent < dist)) { if(closest >= 0) { hitsurface = vec(0, 0, 0); hitsurface[closest] = ray[closest]>0 ? -1 : 1; } return min(dent, dist); } ivec lo(x&(~0<0 || !(mode&RAY_SKIPFIRST))) return min(dent, dist+f); } FINDCLOSEST(closest = 0, closest = 1, closest = 2); if(radius>0 && dist>=radius) return min(dent, dist); UPOCTREE(return min(dent, radius>0 ? radius : dist)); } } // optimized version for lightmap shadowing... every cycle here counts!!! float shadowray(const vec &o, const vec &ray, float radius, int mode, extentity *t) { INITRAYCUBE; CHECKINSIDEWORLD; int side = O_BOTTOM, x = int(v.x), y = int(v.y), z = int(v.z); for(;;) { DOWNOCTREE(shadowent, true); cube &c = *lc; ivec lo(x&(~0<= 0) return c.texture[side]==DEFAULT_SKY && mode&RAY_SKIPSKY ? radius : dist+max(enterdist+0.1f, 0.0f); } nextcube: FINDCLOSEST(side = O_RIGHT - lsizemask.x, side = O_FRONT - lsizemask.y, side = O_TOP - lsizemask.z); if(dist>=radius) return dist; UPOCTREE(return radius); } } // thread safe version struct ShadowRayCache { clipplanes clipcache[MAXCLIPPLANES]; int version; ShadowRayCache() : version(-1) {} }; ShadowRayCache *newshadowraycache() { return new ShadowRayCache; } void freeshadowraycache(ShadowRayCache *&cache) { delete cache; cache = NULL; } void resetshadowraycache(ShadowRayCache *cache) { cache->version++; if(!cache->version) { memset(cache->clipcache, 0, sizeof(cache->clipcache)); cache->version = 1; } } float shadowray(ShadowRayCache *cache, const vec &o, const vec &ray, float radius, int mode, extentity *t) { INITRAYCUBE; CHECKINSIDEWORLD; int side = O_BOTTOM, x = int(v.x), y = int(v.y), z = int(v.z); for(;;) { DOWNOCTREE(shadowent, true); cube &c = *lc; ivec lo(x&(~0<clipcache[int(&c - worldroot)&(MAXCLIPPLANES-1)]; if(p.owner != &c || p.version != cache->version) { p.owner = &c; p.version = cache->version; genclipplanes(c, lo.x, lo.y, lo.z, 1<= 0) return c.texture[side]==DEFAULT_SKY && mode&RAY_SKIPSKY ? radius : dist+max(enterdist+0.1f, 0.0f); } nextcube: FINDCLOSEST(side = O_RIGHT - lsizemask.x, side = O_FRONT - lsizemask.y, side = O_TOP - lsizemask.z); if(dist>=radius) return dist; UPOCTREE(return radius); } } float rayent(const vec &o, const vec &ray, float radius, int mode, int size, int &orient, int &ent) { hitent = -1; hitentdist = radius; float dist = raycube(o, ray, radius, mode, size); if((mode&RAY_ENTS) == RAY_ENTS) { float dent = disttooutsideent(o, ray, dist < 0 ? 1e16f : dist, mode, NULL); if(dent < 1e15f && (dist < 0 || dent < dist)) dist = dent; } orient = hitorient; ent = hitentdist == dist ? hitent : -1; return dist; } float raycubepos(const vec &o, const vec &ray, vec &hitpos, float radius, int mode, int size) { hitpos = ray; float dist = raycube(o, ray, radius, mode, size); if(radius>0 && dist>=radius) dist = radius; hitpos.mul(dist).add(o); return dist; } bool raycubelos(const vec &o, const vec &dest, vec &hitpos) { vec ray(dest); ray.sub(o); float mag = ray.magnitude(); ray.mul(1/mag); float distance = raycubepos(o, ray, hitpos, mag, RAY_CLIPMAT|RAY_POLY); return distance >= mag; } float rayfloor(const vec &o, vec &floor, int mode, float radius) { if(o.z<=0) return -1; hitsurface = vec(0, 0, 1); float dist = raycube(o, vec(0, 0, -1), radius, mode); if(dist<0 || (radius>0 && dist>=radius)) return dist; floor = hitsurface; return dist; } ///////////////////////// entity collision /////////////////////////////////////////////// // info about collisions bool inside; // whether an internal collision happened physent *hitplayer; // whether the collection hit a player vec wall; // just the normal vectors. const float STAIRHEIGHT = 4.1f; const float FLOORZ = 0.867f; const float SLOPEZ = 0.5f; const float WALLZ = 0.2f; extern const float JUMPVEL = 125.0f; extern const float GRAVITY = 200.0f; bool ellipserectcollide(physent *d, const vec &dir, const vec &o, const vec ¢er, float yaw, float xr, float yr, float hi, float lo) { float below = (o.z+center.z-lo) - (d->o.z+d->aboveeye), above = (d->o.z-d->eyeheight) - (o.z+center.z+hi); if(below>=0 || above>=0) return true; vec yo(d->o); yo.sub(o); yo.rotate_around_z(-yaw*RAD); yo.sub(center); float dx = clamp(yo.x, -xr, xr) - yo.x, dy = clamp(yo.y, -yr, yr) - yo.y, dist = sqrtf(dx*dx + dy*dy) - d->radius; if(dist < 0) { int sx = yo.x <= -xr ? -1 : (yo.x >= xr ? 1 : 0), sy = yo.y <= -yr ? -1 : (yo.y >= yr ? 1 : 0); if(dist > (yo.z < 0 ? below : above) && (sx || sy)) { vec ydir(dir); ydir.rotate_around_z(-yaw*RAD); if(sx*yo.x - xr > sy*yo.y - yr) { if(dir.iszero() || sx*ydir.x < -1e-6f) { wall = vec(sx, 0, 0); wall.rotate_around_z(yaw*RAD); return false; } } else if(dir.iszero() || sy*ydir.y < -1e-6f) { wall = vec(0, sy, 0); wall.rotate_around_z(yaw*RAD); return false; } } if(yo.z < 0) { if(dir.iszero() || (dir.z > 0 && (d->type>=ENT_INANIMATE || below >= d->zmargin-(d->eyeheight+d->aboveeye)/4.0f))) { wall = vec(0, 0, -1); return false; } } else if(dir.iszero() || (dir.z < 0 && (d->type>=ENT_INANIMATE || above >= d->zmargin-(d->eyeheight+d->aboveeye)/3.0f))) { wall = vec(0, 0, 1); return false; } inside = true; } return true; } bool ellipsecollide(physent *d, const vec &dir, const vec &o, const vec ¢er, float yaw, float xr, float yr, float hi, float lo) { float below = (o.z+center.z-lo) - (d->o.z+d->aboveeye), above = (d->o.z-d->eyeheight) - (o.z+center.z+hi); if(below>=0 || above>=0) return true; vec yo(center); yo.rotate_around_z(yaw*RAD); yo.add(o); float x = yo.x - d->o.x, y = yo.y - d->o.y; float angle = atan2f(y, x), dangle = angle-(d->yaw+90)*RAD, eangle = angle-(yaw+90)*RAD; float dx = d->xradius*cosf(dangle), dy = d->yradius*sinf(dangle); float ex = xr*cosf(eangle), ey = yr*sinf(eangle); float dist = sqrtf(x*x + y*y) - sqrtf(dx*dx + dy*dy) - sqrtf(ex*ex + ey*ey); if(dist < 0) { if(dist > (d->o.z < yo.z ? below : above) && (dir.iszero() || x*dir.x + y*dir.y > 0)) { wall = vec(-x, -y, 0); if(!wall.iszero()) wall.normalize(); return false; } if(d->o.z < yo.z) { if(dir.iszero() || (dir.z > 0 && (d->type>=ENT_INANIMATE || below >= d->zmargin-(d->eyeheight+d->aboveeye)/4.0f))) { wall = vec(0, 0, -1); return false; } } else if(dir.iszero() || (dir.z < 0 && (d->type>=ENT_INANIMATE || above >= d->zmargin-(d->eyeheight+d->aboveeye)/3.0f))) { wall = vec(0, 0, 1); return false; } inside = true; } return true; } bool rectcollide(physent *d, const vec &dir, const vec &o, float xr, float yr, float hi, float lo, uchar visible = 0xFF) { vec s(d->o); s.sub(o); float dxr = d->collidetype==COLLIDE_AABB ? d->xradius : d->radius, dyr = d->collidetype==COLLIDE_AABB ? d->yradius : d->radius; xr += dxr; yr += dyr; float zr = s.z>0 ? d->eyeheight+hi : d->aboveeye+lo; float ax = fabs(s.x)-xr; float ay = fabs(s.y)-yr; float az = fabs(s.z)-zr; if(ax>0 || ay>0 || az>0) return true; wall.x = wall.y = wall.z = 0; #define TRYCOLLIDE(dim, ON, OP, N, P) \ { \ if(s.dim<0) { if(visible&(1<0 && (d->type>=ENT_INANIMATE || (N))))) { wall.dim = -1; return false; } } \ else if(visible&(1<type>=ENT_INANIMATE || (P))))) { wall.dim = 1; return false; } \ } if(ax>ay && ax>az) TRYCOLLIDE(x, O_LEFT, O_RIGHT, ax > -dxr, ax > -dxr); if(ay>az) TRYCOLLIDE(y, O_BACK, O_FRONT, ay > -dyr, ay > -dyr); TRYCOLLIDE(z, O_BOTTOM, O_TOP, az >= d->zmargin-(d->eyeheight+d->aboveeye)/4.0f, az >= d->zmargin-(d->eyeheight+d->aboveeye)/3.0f); inside = true; return true; } #define DYNENTCACHESIZE 1024 static uint dynentframe = 0; static struct dynentcacheentry { int x, y; uint frame; vector dynents; } dynentcache[DYNENTCACHESIZE]; void cleardynentcache() { dynentframe++; if(!dynentframe || dynentframe == 1) loopi(DYNENTCACHESIZE) dynentcache[i].frame = 0; if(!dynentframe) dynentframe = 1; } VARF(dynentsize, 4, 7, 12, cleardynentcache()); #define DYNENTHASH(x, y) (((((x)^(y))<<5) + (((x)^(y))>>5)) & (DYNENTCACHESIZE - 1)) const vector &checkdynentcache(int x, int y) { dynentcacheentry &dec = dynentcache[DYNENTHASH(x, y)]; if(dec.x == x && dec.y == y && dec.frame == dynentframe) return dec.dynents; dec.x = x; dec.y = y; dec.frame = dynentframe; dec.dynents.shrink(0); int numdyns = game::numdynents(), dsize = 1<state != CS_ALIVE || d->o.x+d->radius <= dx || d->o.x-d->radius >= dx+dsize || d->o.y+d->radius <= dy || d->o.y-d->radius >= dy+dsize) continue; dec.dynents.add(d); } return dec.dynents; } #define loopdynentcache(curx, cury, o, radius) \ for(int curx = max(int(o.x-radius), 0)>>dynentsize, endx = min(int(o.x+radius), worldsize-1)>>dynentsize; curx <= endx; curx++) \ for(int cury = max(int(o.y-radius), 0)>>dynentsize, endy = min(int(o.y+radius), worldsize-1)>>dynentsize; cury <= endy; cury++) void updatedynentcache(physent *d) { loopdynentcache(x, y, d->o, d->radius) { dynentcacheentry &dec = dynentcache[DYNENTHASH(x, y)]; if(dec.x != x || dec.y != y || dec.frame != dynentframe || dec.dynents.find(d) >= 0) continue; dec.dynents.add(d); } } bool overlapsdynent(const vec &o, float radius) { loopdynentcache(x, y, o, radius) { const vector &dynents = checkdynentcache(x, y); loopv(dynents) { physent *d = dynents[i]; if(o.dist(d->o)-d->radius < radius) return true; } } return false; } template static inline bool plcollide(physent *d, const vec &dir, physent *o) { E entvol(d); O obvol(o); vec cp; if(mpr::collide(entvol, obvol, NULL, NULL, &cp)) { vec wn = vec(cp).sub(obvol.center()); wall = obvol.contactface(wn, dir.iszero() ? vec(wn).neg() : dir); if(!wall.iszero()) return false; inside = true; } return true; } bool plcollide(physent *d, const vec &dir) // collide with player or monster { if(d->type==ENT_CAMERA || d->state!=CS_ALIVE) return true; loopdynentcache(x, y, d->o, d->radius) { const vector &dynents = checkdynentcache(x, y); loopv(dynents) { physent *o = dynents[i]; if(o==d || d->o.reject(o->o, d->radius+o->radius)) continue; switch(d->collidetype) { case COLLIDE_ELLIPSE: if(o->collidetype == COLLIDE_ELLIPSE) { if(ellipsecollide(d, dir, o->o, vec(0, 0, 0), o->yaw, o->xradius, o->yradius, o->aboveeye, o->eyeheight)) continue; } else if(ellipserectcollide(d, dir, o->o, vec(0, 0, 0), o->yaw, o->xradius, o->yradius, o->aboveeye, o->eyeheight)) continue; break; case COLLIDE_OBB: if(o->collidetype == COLLIDE_ELLIPSE) { if(plcollide(d, dir, o)) continue; } else if(plcollide(d, dir, o)) continue; break; case COLLIDE_AABB: default: if(rectcollide(d, dir, o->o, o->collidetype == COLLIDE_AABB ? o->xradius : o->radius, o->collidetype == COLLIDE_AABB ? o->yradius : o->radius, o->aboveeye, o->eyeheight)) continue; break; } hitplayer = o; game::dynentcollide(d, o, wall); return false; } } return true; } void rotatebb(vec ¢er, vec &radius, int yaw) { if(yaw < 0) yaw = 360 + yaw%360; else if(yaw >= 360) yaw %= 360; const vec2 &rot = sincos360[yaw]; vec2 oldcenter(center), oldradius(radius); center.x = oldcenter.x*rot.x - oldcenter.y*rot.y; center.y = oldcenter.y*rot.x + oldcenter.x*rot.y; radius.x = fabs(oldradius.x*rot.x) + fabs(oldradius.y*rot.y); radius.y = fabs(oldradius.y*rot.x) + fabs(oldradius.x*rot.y); } template static inline bool mmcollide(physent *d, const vec &dir, const extentity &e, const vec ¢er, const vec &radius, float yaw) { E entvol(d); M mdlvol(e.o, center, radius, yaw); vec cp; if(mpr::collide(entvol, mdlvol, NULL, NULL, &cp)) { vec wn = vec(cp).sub(mdlvol.center()); wall = mdlvol.contactface(wn, dir.iszero() ? vec(wn).neg() : dir); if(!wall.iszero()) return false; inside = true; } return true; } bool mmcollide(physent *d, const vec &dir, octaentities &oc) // collide with a mapmodel { const vector &ents = entities::getents(); loopv(oc.mapmodels) { extentity &e = *ents[oc.mapmodels[i]]; if(e.flags&extentity::F_NOCOLLIDE) continue; model *m = loadmodel(NULL, e.attr2); if(!m || !m->collide) continue; vec center, radius; m->collisionbox(0, center, radius); float yaw = e.attr1; switch(d->collidetype) { case COLLIDE_ELLIPSE: if(m->ellipsecollide) { //if(!mmcollide(d, dir, e, center, radius, yaw)) return false; if(!ellipsecollide(d, dir, e.o, center, yaw, radius.x, radius.y, radius.z, radius.z)) return false; } //else if(!mmcollide(d, dir, e, center, radius, yaw)) return false; else if(!ellipserectcollide(d, dir, e.o, center, yaw, radius.x, radius.y, radius.z, radius.z)) return false; break; case COLLIDE_OBB: if(m->ellipsecollide) { if(!mmcollide(d, dir, e, center, radius, yaw)) return false; } else if(!mmcollide(d, dir, e, center, radius, yaw)) return false; break; case COLLIDE_AABB: default: rotatebb(center, radius, e.attr1); if(!rectcollide(d, dir, center.add(e.o), radius.x, radius.y, radius.z, radius.z)) return false; break; } } return true; } template static bool fuzzycollidesolid(physent *d, const vec &dir, float cutoff, const cube &c, const ivec &co, int size) // collide with solid cube geometry { int crad = size/2; if(fabs(d->o.x - co.x - crad) > d->radius + crad || fabs(d->o.y - co.y - crad) > d->radius + crad || d->o.z + d->aboveeye < co.z || d->o.z - d->eyeheight > co.z + size) return true; E entvol(d); wall = vec(0, 0, 0); float bestdist = -1e10f; int visible = isentirelysolid(c) ? c.visible : 0xFF; loopi(6) if(visible&(1< 0) return true; if(dist <= bestdist) continue; if(!dir.iszero()) { if(w.dot(dir) >= -cutoff*dir.magnitude()) continue; if(d->typezmargin-(d->eyeheight+d->aboveeye)/(dir.z < 0 ? 3.0f : 4.0f) : ((dir.x*w.x < 0 || dir.y*w.y < 0) ? -d->radius : 0))) continue; } wall = w; bestdist = dist; } if(wall.iszero()) { inside = true; return true; } return false; } template static inline bool clampcollide(const clipplanes &p, const E &entvol, const plane &w, const vec &pw) { if(w.x && (w.y || w.z) && fabs(pw.x - p.o.x) > p.r.x) { vec c = entvol.center(); float fv = pw.x < p.o.x ? p.o.x-p.r.x : p.o.x+p.r.x, fdist = (w.x*fv + w.y*c.y + w.z*c.z + w.offset) / (w.y*w.y + w.z*w.z); vec fdir(fv - c.x, -w.y*fdist, -w.z*fdist); if((pw.y-c.y-fdir.y)*w.y + (pw.z-c.z-fdir.z)*w.z >= 0 && entvol.supportpoint(fdir).squaredist(c) < fdir.squaredlen()) return true; } if(w.y && (w.x || w.z) && fabs(pw.y - p.o.y) > p.r.y) { vec c = entvol.center(); float fv = pw.y < p.o.y ? p.o.y-p.r.y : p.o.y+p.r.y, fdist = (w.x*c.x + w.y*fv + w.z*c.z + w.offset) / (w.x*w.x + w.z*w.z); vec fdir(-w.x*fdist, fv - c.y, -w.z*fdist); if((pw.x-c.x-fdir.x)*w.x + (pw.z-c.z-fdir.z)*w.z >= 0 && entvol.supportpoint(fdir).squaredist(c) < fdir.squaredlen()) return true; } if(w.z && (w.x || w.y) && fabs(pw.z - p.o.z) > p.r.z) { vec c = entvol.center(); float fv = pw.z < p.o.z ? p.o.z-p.r.z : p.o.z+p.r.z, fdist = (w.x*c.x + w.y*c.y + w.z*fv + w.offset) / (w.x*w.x + w.y*w.y); vec fdir(-w.x*fdist, -w.y*fdist, fv - c.z); if((pw.x-c.x-fdir.x)*w.x + (pw.y-c.y-fdir.y)*w.y >= 0 && entvol.supportpoint(fdir).squaredist(c) < fdir.squaredlen()) return true; } return false; } template static bool fuzzycollideplanes(physent *d, const vec &dir, float cutoff, const cube &c, const ivec &co, int size) // collide with deformed cube geometry { const clipplanes &p = getclipplanes(c, co, size); if(fabs(d->o.x - p.o.x) > p.r.x + d->radius || fabs(d->o.y - p.o.y) > p.r.y + d->radius || d->o.z + d->aboveeye < p.o.z - p.r.z || d->o.z - d->eyeheight > p.o.z + p.r.z) return true; E entvol(d); wall = vec(0, 0, 0); float bestdist = -1e10f; loopi(6) if(p.visible&(1<= 0) return true; if(dist <= bestdist) continue; if(!dir.iszero()) { if(w.dot(dir) >= -cutoff*dir.magnitude()) continue; if(d->typezmargin-(d->eyeheight+d->aboveeye)/(dir.z < 0 ? 3.0f : 4.0f) : ((dir.x*w.x < 0 || dir.y*w.y < 0) ? -d->radius : 0))) continue; } wall = w; bestdist = dist; } int bestplane = -1; loopi(p.size) { const plane &w = p.p[i]; vec pw = entvol.supportpoint(vec(w).neg()); float dist = w.dist(pw); if(dist >= 0) return true; if(dist <= bestdist) continue; bestplane = -1; bestdist = dist; if(!dir.iszero()) { if(w.dot(dir) >= -cutoff*dir.magnitude()) continue; if(d->typezmargin-(d->eyeheight+d->aboveeye)/(dir.z < 0 ? 3.0f : 4.0f) : ((dir.x*w.x < 0 || dir.y*w.y < 0) ? -d->radius : 0))) continue; } if(clampcollide(p, entvol, w, pw)) continue; bestplane = i; } if(bestplane >= 0) wall = p.p[bestplane]; else if(wall.iszero()) { inside = true; return true; } return false; } template static bool cubecollidesolid(physent *d, const vec &dir, float cutoff, const cube &c, const ivec &co, int size) // collide with solid cube geometry { int crad = size/2; if(fabs(d->o.x - co.x - crad) > d->radius + crad || fabs(d->o.y - co.y - crad) > d->radius + crad || d->o.z + d->aboveeye < co.z || d->o.z - d->eyeheight > co.z + size) return true; E entvol(d); bool collided = mpr::collide(mpr::SolidCube(co, size), entvol); if(!collided) return true; wall = vec(0, 0, 0); float bestdist = -1e10f; int visible = isentirelysolid(c) ? c.visible : 0xFF; loopi(6) if(visible&(1<= -cutoff*dir.magnitude()) continue; if(d->typezmargin-(d->eyeheight+d->aboveeye)/(dir.z < 0 ? 3.0f : 4.0f) : ((dir.x*w.x < 0 || dir.y*w.y < 0) ? -d->radius : 0))) continue; } wall = w; bestdist = dist; } if(wall.iszero()) { inside = true; return true; } return false; } template static bool cubecollideplanes(physent *d, const vec &dir, float cutoff, const cube &c, const ivec &co, int size) // collide with deformed cube geometry { const clipplanes &p = getclipplanes(c, co, size); if(fabs(d->o.x - p.o.x) > p.r.x + d->radius || fabs(d->o.y - p.o.y) > p.r.y + d->radius || d->o.z + d->aboveeye < p.o.z - p.r.z || d->o.z - d->eyeheight > p.o.z + p.r.z) return true; E entvol(d); bool collided = mpr::collide(mpr::CubePlanes(p), entvol); if(!collided) return true; wall = vec(0, 0, 0); float bestdist = -1e10f; loopi(6) if(p.visible&(1<= -cutoff*dir.magnitude()) continue; if(d->typezmargin-(d->eyeheight+d->aboveeye)/(dir.z < 0 ? 3.0f : 4.0f) : ((dir.x*w.x < 0 || dir.y*w.y < 0) ? -d->radius : 0))) continue; } wall = w; bestdist = dist; } int bestplane = -1; loopi(p.size) { const plane &w = p.p[i]; vec pw = entvol.supportpoint(vec(w).neg()); float dist = w.dist(pw); if(dist <= bestdist) continue; bestplane = -1; bestdist = dist; if(!dir.iszero()) { if(w.dot(dir) >= -cutoff*dir.magnitude()) continue; if(d->typezmargin-(d->eyeheight+d->aboveeye)/(dir.z < 0 ? 3.0f : 4.0f) : ((dir.x*w.x < 0 || dir.y*w.y < 0) ? -d->radius : 0))) continue; } if(clampcollide(p, entvol, w, pw)) continue; bestplane = i; } if(bestplane >= 0) wall = p.p[bestplane]; else if(wall.iszero()) { inside = true; return true; } return false; } static inline bool cubecollide(physent *d, const vec &dir, float cutoff, const cube &c, const ivec &co, int size, bool solid) { switch(d->collidetype) { case COLLIDE_AABB: if(isentirelysolid(c) || solid) { if(cutoff <= 0) { int crad = size/2; return rectcollide(d, dir, vec(co.x + crad, co.y + crad, co.z), crad, crad, size, 0, isentirelysolid(c) ? c.visible : 0xFF); } #if 0 else return cubecollidesolid(d, dir, cutoff, c, co, size); #else else return fuzzycollidesolid(d, dir, cutoff, c, co, size); #endif } else { #if 0 if(cutoff <= 0) { const clipplanes &p = getclipplanes(c, co, size); if(!p.size) return rectcollide(d, dir, p.o, p.r.x, p.r.y, p.r.z, p.r.z, p.visible); } return cubecollideplanes(d, dir, cutoff, c, co, size); #else return fuzzycollideplanes(d, dir, cutoff, c, co, size); #endif } case COLLIDE_OBB: if(isentirelysolid(c) || solid) return cubecollidesolid(d, dir, cutoff, c, co, size); else return cubecollideplanes(d, dir, cutoff, c, co, size); case COLLIDE_ELLIPSE: default: if(d->type < ENT_CAMERA) { if(isentirelysolid(c) || solid) return fuzzycollidesolid(d, dir, cutoff, c, co, size); else return fuzzycollideplanes(d, dir, cutoff, c, co, size); } else if(isentirelysolid(c) || solid) return cubecollidesolid(d, dir, cutoff, c, co, size); else return cubecollideplanes(d, dir, cutoff, c, co, size); } } static inline bool octacollide(physent *d, const vec &dir, float cutoff, const ivec &bo, const ivec &bs, const cube *c, const ivec &cor, int size) // collide with octants { loopoctabox(cor, size, bo, bs) { if(c[i].ext && c[i].ext->ents) if(!mmcollide(d, dir, *c[i].ext->ents)) return false; ivec o(i, cor.x, cor.y, cor.z, size); if(c[i].children) { if(!octacollide(d, dir, cutoff, bo, bs, c[i].children, o, size>>1)) return false; } else { bool solid = false; switch(c[i].material&MATF_CLIP) { case MAT_NOCLIP: continue; case MAT_GAMECLIP: if(d->type==ENT_AI) solid = true; break; case MAT_CLIP: if(isclipped(c[i].material&MATF_VOLUME) || d->type= uint(worldsize)) return octacollide(d, dir, cutoff, bo, bs, worldroot, ivec(0, 0, 0), worldsize>>1); const cube *c = &worldroot[octastep(bo.x, bo.y, bo.z, scale)]; if(c->ext && c->ext->ents && !mmcollide(d, dir, *c->ext->ents)) return false; scale--; while(c->children && !(diff&(1<children[octastep(bo.x, bo.y, bo.z, scale)]; if(c->ext && c->ext->ents && !mmcollide(d, dir, *c->ext->ents)) return false; scale--; } if(c->children) return octacollide(d, dir, cutoff, bo, bs, c->children, ivec(bo).mask(~((2<material&MATF_CLIP) { case MAT_NOCLIP: return true; case MAT_GAMECLIP: if(d->type==ENT_AI) solid = true; break; case MAT_CLIP: if(isclipped(c->material&MATF_VOLUME) || d->typeo.x-d->radius), int(d->o.y-d->radius), int(d->o.z-d->eyeheight)), bs(int(d->radius*2), int(d->radius*2), int(d->eyeheight+d->aboveeye)); bs.add(2); // guard space for rounding errors if(!octacollide(d, dir, cutoff, bo, bs)) return false;//, worldroot, ivec(0, 0, 0), worldsize>>1)) return false; // collide with world return !playercol || plcollide(d, dir); } void recalcdir(physent *d, const vec &oldvel, vec &dir) { float speed = oldvel.magnitude(); if(speed > 1e-6f) { float step = dir.magnitude(); dir = d->vel; dir.add(d->falling); dir.mul(step/speed); } } void slideagainst(physent *d, vec &dir, const vec &obstacle, bool foundfloor, bool slidecollide) { vec wall(obstacle); if(foundfloor ? wall.z > 0 : slidecollide) { wall.z = 0; if(!wall.iszero()) wall.normalize(); } vec oldvel(d->vel); oldvel.add(d->falling); d->vel.project(wall); d->falling.project(wall); recalcdir(d, oldvel, dir); } void switchfloor(physent *d, vec &dir, const vec &floor) { if(floor.z >= FLOORZ) d->falling = vec(0, 0, 0); vec oldvel(d->vel); oldvel.add(d->falling); if(dir.dot(floor) >= 0) { if(d->physstate < PHYS_SLIDE || fabs(dir.dot(d->floor)) > 0.01f*dir.magnitude()) return; d->vel.projectxy(floor, 0.0f); } else d->vel.projectxy(floor); d->falling.project(floor); recalcdir(d, oldvel, dir); } bool trystepup(physent *d, vec &dir, const vec &obstacle, float maxstep, const vec &floor) { vec old(d->o), stairdir = (obstacle.z >= 0 && obstacle.z < SLOPEZ ? vec(-obstacle.x, -obstacle.y, 0) : vec(dir.x, dir.y, 0)).rescale(1); bool cansmooth = true; /* check if there is space atop the stair to move to */ if(d->physstate != PHYS_STEP_UP) { vec checkdir = stairdir; checkdir.mul(0.1f); checkdir.z += maxstep + 0.1f; d->o.add(checkdir); if(!collide(d)) { d->o = old; if(collide(d, vec(0, 0, -1), SLOPEZ)) return false; cansmooth = false; } } if(cansmooth) { vec checkdir = stairdir; checkdir.z += 1; checkdir.mul(maxstep); d->o = old; d->o.add(checkdir); int scale = 2; if(!collide(d, checkdir)) { if(collide(d, vec(0, 0, -1), SLOPEZ)) { d->o = old; return false; } d->o.add(checkdir); if(!collide(d, vec(0, 0, -1), SLOPEZ)) scale = 1; } if(scale != 1) { d->o = old; d->o.sub(checkdir.mul(vec(2, 2, 1))); if(collide(d, vec(0, 0, -1), SLOPEZ)) scale = 1; } d->o = old; vec smoothdir(dir.x, dir.y, 0); float magxy = smoothdir.magnitude(); if(magxy > 1e-9f) { if(magxy > scale*dir.z) { smoothdir.mul(1/magxy); smoothdir.z = 1.0f/scale; smoothdir.mul(dir.magnitude()/smoothdir.magnitude()); } else smoothdir.z = dir.z; d->o.add(smoothdir); d->o.z += maxstep + 0.1f; if(collide(d, smoothdir)) { d->o.z -= maxstep + 0.1f; if(d->physstate == PHYS_FALL || d->floor != floor) { d->timeinair = 0; d->floor = floor; switchfloor(d, dir, d->floor); } d->physstate = PHYS_STEP_UP; return true; } } } /* try stepping up */ d->o = old; d->o.z += dir.magnitude(); if(collide(d, vec(0, 0, 1))) { if(d->physstate == PHYS_FALL || d->floor != floor) { d->timeinair = 0; d->floor = floor; switchfloor(d, dir, d->floor); } if(cansmooth) d->physstate = PHYS_STEP_UP; return true; } d->o = old; return false; } bool trystepdown(physent *d, vec &dir, float step, float xy, float z, bool init = false) { vec stepdir(dir.x, dir.y, 0); stepdir.z = -stepdir.magnitude2()*z/xy; if(!stepdir.z) return false; stepdir.normalize(); vec old(d->o); d->o.add(vec(stepdir).mul(STAIRHEIGHT/fabs(stepdir.z))).z -= STAIRHEIGHT; d->zmargin = -STAIRHEIGHT; if(!collide(d, vec(0, 0, -1), SLOPEZ)) { d->o = old; d->o.add(vec(stepdir).mul(step)); d->zmargin = 0; if(collide(d, vec(0, 0, -1))) { vec stepfloor(stepdir); stepfloor.mul(-stepfloor.z).z += 1; stepfloor.normalize(); if(d->physstate >= PHYS_SLOPE && d->floor != stepfloor) { // prevent alternating step-down/step-up states if player would keep bumping into the same floor vec stepped(d->o); d->o.z -= 0.5f; d->zmargin = -0.5f; if(!collide(d, stepdir) && wall == d->floor) { d->o = old; if(!init) { d->o.x += dir.x; d->o.y += dir.y; if(dir.z <= 0 || !collide(d, dir)) d->o.z += dir.z; } d->zmargin = 0; d->physstate = PHYS_STEP_DOWN; d->timeinair = 0; return true; } d->o = init ? old : stepped; d->zmargin = 0; } else if(init) d->o = old; switchfloor(d, dir, stepfloor); d->floor = stepfloor; d->physstate = PHYS_STEP_DOWN; d->timeinair = 0; return true; } } d->o = old; d->zmargin = 0; return false; } bool trystepdown(physent *d, vec &dir, bool init = false) { if(!game::allowmove(d) || (!d->move && !d->strafe)) return false; vec old(d->o); d->o.z -= STAIRHEIGHT; d->zmargin = -STAIRHEIGHT; if(collide(d, vec(0, 0, -1), SLOPEZ)) { d->o = old; d->zmargin = 0; return false; } d->o = old; d->zmargin = 0; float step = dir.magnitude(); #if 1 // weaker check, just enough to avoid hopping up slopes if(trystepdown(d, dir, step, 4, 1, init)) return true; #else if(trystepdown(d, dir, step, 2, 1, init)) return true; if(trystepdown(d, dir, step, 1, 1, init)) return true; if(trystepdown(d, dir, step, 1, 2, init)) return true; #endif return false; } void falling(physent *d, vec &dir, const vec &floor) { if(floor.z > 0.0f && floor.z < SLOPEZ) { if(floor.z >= WALLZ) switchfloor(d, dir, floor); d->timeinair = 0; d->physstate = PHYS_SLIDE; d->floor = floor; } else if(d->physstate < PHYS_SLOPE || dir.dot(d->floor) > 0.01f*dir.magnitude() || (floor.z != 0.0f && floor.z != 1.0f) || !trystepdown(d, dir, true)) d->physstate = PHYS_FALL; } void landing(physent *d, vec &dir, const vec &floor, bool collided) { #if 0 if(d->physstate == PHYS_FALL) { d->timeinair = 0; if(dir.z < 0.0f) dir.z = d->vel.z = 0.0f; } #endif switchfloor(d, dir, floor); d->timeinair = 0; if((d->physstate!=PHYS_STEP_UP && d->physstate!=PHYS_STEP_DOWN) || !collided) d->physstate = floor.z >= FLOORZ ? PHYS_FLOOR : PHYS_SLOPE; d->floor = floor; } bool findfloor(physent *d, bool collided, const vec &obstacle, bool &slide, vec &floor) { bool found = false; vec moved(d->o); d->o.z -= 0.1f; if(!collide(d, vec(0, 0, -1), d->physstate == PHYS_SLOPE || d->physstate == PHYS_STEP_DOWN ? SLOPEZ : FLOORZ)) { floor = wall; found = true; } else if(collided && obstacle.z >= SLOPEZ) { floor = obstacle; found = true; slide = false; } else if(d->physstate == PHYS_STEP_UP || d->physstate == PHYS_SLIDE) { if(!collide(d, vec(0, 0, -1)) && wall.z > 0.0f) { floor = wall; if(floor.z >= SLOPEZ) found = true; } } else if(d->physstate >= PHYS_SLOPE && d->floor.z < 1.0f) { if(!collide(d, vec(d->floor).neg(), 0.95f) || !collide(d, vec(0, 0, -1))) { floor = wall; if(floor.z >= SLOPEZ && floor.z < 1.0f) found = true; } } if(collided && (!found || obstacle.z > floor.z)) { floor = obstacle; slide = !found && (floor.z < WALLZ || floor.z >= SLOPEZ); } d->o = moved; return found; } bool move(physent *d, vec &dir) { vec old(d->o); bool collided = false, slidecollide = false; vec obstacle; d->o.add(dir); if(!collide(d, dir) || ((d->type==ENT_AI || d->type==ENT_INANIMATE) && !collide(d, vec(0, 0, 0), 0, false))) { obstacle = wall; /* check to see if there is an obstacle that would prevent this one from being used as a floor (or ceiling bump) */ if(d->type==ENT_PLAYER && ((wall.z>=SLOPEZ && dir.z<0) || (wall.z<=-SLOPEZ && dir.z>0)) && (dir.x || dir.y) && !collide(d, vec(dir.x, dir.y, 0))) { if(wall.dot(dir) >= 0) slidecollide = true; obstacle = wall; } d->o = old; d->o.z -= STAIRHEIGHT; d->zmargin = -STAIRHEIGHT; if(d->physstate == PHYS_SLOPE || d->physstate == PHYS_FLOOR || (!collide(d, vec(0, 0, -1), SLOPEZ) && (d->physstate==PHYS_STEP_UP || d->physstate==PHYS_STEP_DOWN || wall.z>=FLOORZ))) { d->o = old; d->zmargin = 0; if(trystepup(d, dir, obstacle, STAIRHEIGHT, d->physstate == PHYS_SLOPE || d->physstate == PHYS_FLOOR ? d->floor : vec(wall))) return true; } else { d->o = old; d->zmargin = 0; } /* can't step over the obstacle, so just slide against it */ collided = true; } else if(d->physstate == PHYS_STEP_UP) { if(!collide(d, vec(0, 0, -1), SLOPEZ)) { d->o = old; if(trystepup(d, dir, vec(0, 0, 1), STAIRHEIGHT, vec(wall))) return true; d->o.add(dir); } } else if(d->physstate == PHYS_STEP_DOWN && dir.dot(d->floor) <= 1e-6f) { vec moved(d->o); d->o = old; if(trystepdown(d, dir)) return true; d->o = moved; } vec floor(0, 0, 0); bool slide = collided, found = findfloor(d, collided, obstacle, slide, floor); if(slide || (!collided && floor.z > 0 && floor.z < WALLZ)) { slideagainst(d, dir, slide ? obstacle : floor, found, slidecollide); //if(d->type == ENT_AI || d->type == ENT_INANIMATE) d->blocked = true; } if(found) landing(d, dir, floor, collided); else falling(d, dir, floor); return !collided; } bool bounce(physent *d, float secs, float elasticity, float waterfric, float grav) { // make sure bouncers don't start inside geometry if(d->physstate!=PHYS_BOUNCE && !collide(d, vec(0, 0, 0), 0, false)) return true; int mat = lookupmaterial(vec(d->o.x, d->o.y, d->o.z + (d->aboveeye - d->eyeheight)/2)); bool water = isliquid(mat); if(water) { d->vel.z -= grav*GRAVITY/16*secs; d->vel.mul(max(1.0f - secs/waterfric, 0.0f)); } else d->vel.z -= grav*GRAVITY*secs; vec old(d->o); loopi(2) { vec dir(d->vel); dir.mul(secs); d->o.add(dir); if(collide(d, dir)) { if(inside) { d->o = old; d->vel.mul(-elasticity); } break; } else if(hitplayer) break; d->o = old; game::bounced(d, wall); float c = wall.dot(d->vel), k = 1.0f + (1.0f-elasticity)*c/d->vel.magnitude(); d->vel.mul(k); d->vel.sub(vec(wall).mul(elasticity*2.0f*c)); } if(d->physstate!=PHYS_BOUNCE) { // make sure bouncers don't start inside geometry if(d->o == old) return !hitplayer; d->physstate = PHYS_BOUNCE; } return hitplayer!=0; } void avoidcollision(physent *d, const vec &dir, physent *obstacle, float space) { float rad = obstacle->radius+d->radius; vec bbmin(obstacle->o); bbmin.x -= rad; bbmin.y -= rad; bbmin.z -= obstacle->eyeheight+d->aboveeye; bbmin.sub(space); vec bbmax(obstacle->o); bbmax.x += rad; bbmax.y += rad; bbmax.z += obstacle->aboveeye+d->eyeheight; bbmax.add(space); loopi(3) if(d->o[i] <= bbmin[i] || d->o[i] >= bbmax[i]) return; float mindist = 1e16f; loopi(3) if(dir[i] != 0) { float dist = ((dir[i] > 0 ? bbmax[i] : bbmin[i]) - d->o[i]) / dir[i]; mindist = min(mindist, dist); } if(mindist >= 0.0f && mindist < 1e15f) d->o.add(vec(dir).mul(mindist)); } bool movecamera(physent *pl, const vec &dir, float dist, float stepdist) { int steps = (int)ceil(dist/stepdist); if(steps <= 0) return true; vec d(dir); d.mul(dist/steps); loopi(steps) { vec oldpos(pl->o); pl->o.add(d); if(!collide(pl, vec(0, 0, 0), 0, false)) { pl->o = oldpos; return false; } } return true; } bool droptofloor(vec &o, float radius, float height) { static struct dropent : physent { dropent() { type = ENT_CAMERA; collidetype = COLLIDE_AABB; vel = vec(0, 0, -1); } } d; d.o = o; if(!insideworld(d.o)) { if(d.o.z < worldsize) return false; d.o.z = worldsize - 1e-3f; if(!insideworld(d.o)) return false; } vec v(0.0001f, 0.0001f, -1); v.normalize(); if(raycube(d.o, v, worldsize) >= worldsize) return false; d.radius = d.xradius = d.yradius = radius; d.eyeheight = height; d.aboveeye = radius; if(!movecamera(&d, d.vel, worldsize, 1)) { o = d.o; return true; } return false; } float dropheight(entity &e) { switch(e.type) { case ET_PARTICLES: case ET_MAPMODEL: return 0.0f; default: if(e.type >= ET_GAMESPECIFIC) return entities::dropheight(e); return 4.0f; } } void dropenttofloor(entity *e) { droptofloor(e->o, 1.0f, dropheight(*e)); } void phystest() { static const char *states[] = {"float", "fall", "slide", "slope", "floor", "step up", "step down", "bounce"}; printf ("PHYS(pl): %s, air %d, floor: (%f, %f, %f), vel: (%f, %f, %f), g: (%f, %f, %f)\n", states[player->physstate], player->timeinair, player->floor.x, player->floor.y, player->floor.z, player->vel.x, player->vel.y, player->vel.z, player->falling.x, player->falling.y, player->falling.z); printf ("PHYS(cam): %s, air %d, floor: (%f, %f, %f), vel: (%f, %f, %f), g: (%f, %f, %f)\n", states[camera1->physstate], camera1->timeinair, camera1->floor.x, camera1->floor.y, camera1->floor.z, camera1->vel.x, camera1->vel.y, camera1->vel.z, camera1->falling.x, camera1->falling.y, camera1->falling.z); } COMMAND(phystest, ""); void vecfromyawpitch(float yaw, float pitch, int move, int strafe, vec &m) { if(move) { m.x = move*-sinf(RAD*yaw); m.y = move*cosf(RAD*yaw); } else m.x = m.y = 0; if(pitch) { m.x *= cosf(RAD*pitch); m.y *= cosf(RAD*pitch); m.z = move*sinf(RAD*pitch); } else m.z = 0; if(strafe) { m.x += strafe*cosf(RAD*yaw); m.y += strafe*sinf(RAD*yaw); } } void vectoyawpitch(const vec &v, float &yaw, float &pitch) { yaw = -atan2(v.x, v.y)/RAD; pitch = asin(v.z/v.magnitude())/RAD; } #define PHYSFRAMETIME 5 VARP(maxroll, 0, 0, 20); FVAR(straferoll, 0, 0.033f, 90); FVAR(faderoll, 0, 0.95f, 1); VAR(floatspeed, 1, 100, 10000); void modifyvelocity(physent *pl, bool local, bool water, bool floating, int curtime) { if(floating) { if(pl->jumping) { pl->jumping = false; pl->vel.z = max(pl->vel.z, JUMPVEL); } } else if(pl->physstate >= PHYS_SLOPE || water) { if(water && !pl->inwater) pl->vel.div(8); if(pl->jumping) { pl->jumping = false; pl->vel.z = max(pl->vel.z, JUMPVEL); // physics impulse upwards if(water) { pl->vel.x /= 8.0f; pl->vel.y /= 8.0f; } // dampen velocity change even harder, gives correct water feel game::physicstrigger(pl, local, 1, 0); } } if(!floating && pl->physstate == PHYS_FALL) pl->timeinair += curtime; vec m(0.0f, 0.0f, 0.0f); if(game::allowmove(pl) && (pl->move || pl->strafe)) { vecfromyawpitch(pl->yaw, floating || water || pl->type==ENT_CAMERA ? pl->pitch : 0, pl->move, pl->strafe, m); if(!floating && pl->physstate >= PHYS_SLOPE) { /* move up or down slopes in air * but only move up slopes in water */ float dz = -(m.x*pl->floor.x + m.y*pl->floor.y)/pl->floor.z; m.z = water ? max(m.z, dz) : dz; } m.normalize(); } vec d(m); d.mul(pl->maxspeed); if(pl->type==ENT_PLAYER) { if(floating) { if(pl==player) d.mul(floatspeed/100.0f); } else if(!water && game::allowmove(pl)) d.mul((pl->move && !pl->strafe ? 1.3f : 1.0f) * (pl->physstate < PHYS_SLOPE ? 1.3f : 1.0f)); } float fric = water && !floating ? 20.0f : (pl->physstate >= PHYS_SLOPE || floating ? 6.0f : 30.0f); pl->vel.lerp(d, pl->vel, pow(1 - 1/fric, curtime/20.0f)); // old fps friction // float friction = water && !floating ? 20.0f : (pl->physstate >= PHYS_SLOPE || floating ? 6.0f : 30.0f); // float fpsfric = min(curtime/(20.0f*friction), 1.0f); // pl->vel.lerp(pl->vel, d, fpsfric); } void modifygravity(physent *pl, bool water, int curtime) { float secs = curtime/1000.0f; vec g(0, 0, 0); if(pl->physstate == PHYS_FALL) g.z -= GRAVITY*secs; else if(pl->floor.z > 0 && pl->floor.z < FLOORZ) { g.z = -1; g.project(pl->floor); g.normalize(); g.mul(GRAVITY*secs); } if(!water || !game::allowmove(pl) || (!pl->move && !pl->strafe)) pl->falling.add(g); if(water || pl->physstate >= PHYS_SLOPE) { float fric = water ? 2.0f : 6.0f, c = water ? 1.0f : clamp((pl->floor.z - SLOPEZ)/(FLOORZ-SLOPEZ), 0.0f, 1.0f); pl->falling.mul(pow(1 - c/fric, curtime/20.0f)); // old fps friction // float friction = water ? 2.0f : 6.0f, // fpsfric = friction/curtime*20.0f, // c = water ? 1.0f : clamp((pl->floor.z - SLOPEZ)/(FLOORZ-SLOPEZ), 0.0f, 1.0f); // pl->falling.mul(1 - c/fpsfric); } } // main physics routine, moves a player/monster for a curtime step // moveres indicated the physics precision (which is lower for monsters and multiplayer prediction) // local is false for multiplayer prediction bool moveplayer(physent *pl, int moveres, bool local, int curtime) { int material = lookupmaterial(vec(pl->o.x, pl->o.y, pl->o.z + (3*pl->aboveeye - pl->eyeheight)/4)); bool water = isliquid(material&MATF_VOLUME); bool floating = pl->type==ENT_PLAYER && (pl->state==CS_EDITING || pl->state==CS_SPECTATOR); float secs = curtime/1000.f; // apply gravity if(!floating) modifygravity(pl, water, curtime); // apply any player generated changes in velocity modifyvelocity(pl, local, water, floating, curtime); vec d(pl->vel); if(!floating && water) d.mul(0.5f); d.add(pl->falling); d.mul(secs); pl->blocked = false; if(floating) // just apply velocity { if(pl->physstate != PHYS_FLOAT) { pl->physstate = PHYS_FLOAT; pl->timeinair = 0; pl->falling = vec(0, 0, 0); } pl->o.add(d); } else // apply velocity with collision { const float f = 1.0f/moveres; const int timeinair = pl->timeinair; int collisions = 0; d.mul(f); loopi(moveres) if(!move(pl, d) && ++collisions<5) i--; // discrete steps collision detection & sliding if(timeinair > 800 && !pl->timeinair && !water) // if we land after long time must have been a high jump, make thud sound { game::physicstrigger(pl, local, -1, 0); } } if(pl->state==CS_ALIVE) updatedynentcache(pl); // automatically apply smooth roll when strafing if(pl->strafe && maxroll) pl->roll = clamp(pl->roll - pow(clamp(1.0f + pl->strafe*pl->roll/maxroll, 0.0f, 1.0f), 0.33f)*pl->strafe*curtime*straferoll, -maxroll, maxroll); else pl->roll *= curtime == PHYSFRAMETIME ? faderoll : pow(faderoll, curtime/float(PHYSFRAMETIME)); // play sounds on water transitions if(pl->inwater && !water) { material = lookupmaterial(vec(pl->o.x, pl->o.y, pl->o.z + (pl->aboveeye - pl->eyeheight)/2)); water = isliquid(material&MATF_VOLUME); } if(!pl->inwater && water) game::physicstrigger(pl, local, 0, -1, material&MATF_VOLUME); else if(pl->inwater && !water) game::physicstrigger(pl, local, 0, 1, pl->inwater); pl->inwater = water ? material&MATF_VOLUME : MAT_AIR; if(pl->state==CS_ALIVE && (pl->o.z < 0 || material&MAT_DEATH)) game::suicide(pl); return true; } int physsteps = 0, physframetime = PHYSFRAMETIME, lastphysframe = 0; void physicsframe() // optimally schedule physics frames inside the graphics frames { int diff = lastmillis - lastphysframe; if(diff <= 0) physsteps = 0; else { physframetime = clamp(game::scaletime(PHYSFRAMETIME)/100, 1, PHYSFRAMETIME); physsteps = (diff + physframetime - 1)/physframetime; lastphysframe += physsteps * physframetime; } cleardynentcache(); } VAR(physinterp, 0, 1, 1); void interppos(physent *pl) { pl->o = pl->newpos; int diff = lastphysframe - lastmillis; if(diff <= 0 || !physinterp) return; vec deltapos(pl->deltapos); deltapos.mul(min(diff, physframetime)/float(physframetime)); pl->o.add(deltapos); } void moveplayer(physent *pl, int moveres, bool local) { if(physsteps <= 0) { if(local) interppos(pl); return; } if(local) pl->o = pl->newpos; loopi(physsteps-1) moveplayer(pl, moveres, local, physframetime); if(local) pl->deltapos = pl->o; moveplayer(pl, moveres, local, physframetime); if(local) { pl->newpos = pl->o; pl->deltapos.sub(pl->newpos); interppos(pl); } } bool bounce(physent *d, float elasticity, float waterfric, float grav) { if(physsteps <= 0) { interppos(d); return false; } d->o = d->newpos; bool hitplayer = false; loopi(physsteps-1) { if(bounce(d, physframetime/1000.0f, elasticity, waterfric, grav)) hitplayer = true; } d->deltapos = d->o; if(bounce(d, physframetime/1000.0f, elasticity, waterfric, grav)) hitplayer = true; d->newpos = d->o; d->deltapos.sub(d->newpos); interppos(d); return hitplayer; } void updatephysstate(physent *d) { if(d->physstate == PHYS_FALL) return; d->timeinair = 0; vec old(d->o); /* Attempt to reconstruct the floor state. * May be inaccurate since movement collisions are not considered. * If good floor is not found, just keep the old floor and hope it's correct enough. */ switch(d->physstate) { case PHYS_SLOPE: case PHYS_FLOOR: case PHYS_STEP_DOWN: d->o.z -= 0.15f; if(!collide(d, vec(0, 0, -1), d->physstate == PHYS_SLOPE || d->physstate == PHYS_STEP_DOWN ? SLOPEZ : FLOORZ)) d->floor = wall; break; case PHYS_STEP_UP: d->o.z -= STAIRHEIGHT+0.15f; if(!collide(d, vec(0, 0, -1), SLOPEZ)) d->floor = wall; break; case PHYS_SLIDE: d->o.z -= 0.15f; if(!collide(d, vec(0, 0, -1)) && wall.z < SLOPEZ) d->floor = wall; break; } if(d->physstate > PHYS_FALL && d->floor.z <= 0) d->floor = vec(0, 0, 1); d->o = old; } const float PLATFORMMARGIN = 0.2f; const float PLATFORMBORDER = 10.0f; struct platforment { physent *d; int stacks, chains; platforment() {} platforment(physent *d) : d(d), stacks(-1), chains(-1) {} bool operator==(const physent *o) const { return d == o; } }; struct platformcollision { platforment *ent; int next; platformcollision() {} platformcollision(platforment *ent, int next) : ent(ent), next(next) {} }; template static inline bool platformcollide(physent *d, const vec &dir, physent *o, float margin) { E entvol(d); O obvol(o, margin); vec cp; if(mpr::collide(entvol, obvol, NULL, NULL, &cp)) { vec wn = vec(cp).sub(obvol.center()); return obvol.contactface(wn, dir.iszero() ? vec(wn).neg() : dir).iszero(); } return true; } bool platformcollide(physent *d, physent *o, const vec &dir, float margin = 0) { if(d->collidetype == COLLIDE_ELLIPSE) { if(o->collidetype == COLLIDE_ELLIPSE) return ellipsecollide(d, dir, o->o, vec(0, 0, 0), o->yaw, o->xradius, o->yradius, o->aboveeye, o->eyeheight + margin); else return ellipserectcollide(d, dir, o->o, vec(0, 0, 0), o->yaw, o->xradius, o->yradius, o->aboveeye, o->eyeheight + margin); } else if(o->collidetype == COLLIDE_ELLIPSE) return platformcollide(d, dir, o, margin); else return platformcollide(d, dir, o, margin); } bool moveplatform(physent *p, const vec &dir) { if(!insideworld(p->newpos)) return false; vec oldpos(p->o); (p->o = p->newpos).add(dir); if(!collide(p, dir, 0, dir.z<=0)) { p->o = oldpos; return false; } p->o = oldpos; static vector ents; ents.setsize(0); for(int x = int(max(p->o.x-p->radius-PLATFORMBORDER, 0.0f))>>dynentsize, ex = int(min(p->o.x+p->radius+PLATFORMBORDER, worldsize-1.0f))>>dynentsize; x <= ex; x++) for(int y = int(max(p->o.y-p->radius-PLATFORMBORDER, 0.0f))>>dynentsize, ey = int(min(p->o.y+p->radius+PLATFORMBORDER, worldsize-1.0f))>>dynentsize; y <= ey; y++) { const vector &dynents = checkdynentcache(x, y); loopv(dynents) { physent *d = dynents[i]; if(p==d || d->o.z-d->eyeheight < p->o.z+p->aboveeye || p->o.reject(d->o, p->radius+PLATFORMBORDER+d->radius) || ents.find(d) >= 0) continue; ents.add(d); } } static vector passengers, colliders; passengers.setsize(0); colliders.setsize(0); static vector collisions; collisions.setsize(0); // build up collision DAG of colliders to be pushed off, and DAG of stacked passengers loopv(ents) { platforment &ent = ents[i]; physent *d = ent.d; // check if the dynent is on top of the platform if(!platformcollide(p, d, vec(0, 0, 1), PLATFORMMARGIN)) passengers.add(&ent); vec doldpos(d->o); (d->o = d->newpos).add(dir); if(!collide(d, dir, 0, false)) colliders.add(&ent); d->o = doldpos; loopvj(ents) { platforment &o = ents[j]; if(!platformcollide(d, o.d, dir)) { collisions.add(platformcollision(&ent, o.chains)); o.chains = collisions.length() - 1; } if(d->o.z < o.d->o.z && !platformcollide(d, o.d, vec(0, 0, 1), PLATFORMMARGIN)) { collisions.add(platformcollision(&o, ent.stacks)); ent.stacks = collisions.length() - 1; } } } loopv(colliders) // propagate collisions { platforment *ent = colliders[i]; for(int n = ent->chains; n>=0; n = collisions[n].next) { platforment *o = collisions[n].ent; if(colliders.find(o)<0) colliders.add(o); } } if(dir.z>0) { loopv(passengers) // if any stacked passengers collide, stop the platform { platforment *ent = passengers[i]; if(colliders.find(ent)>=0) return false; for(int n = ent->stacks; n>=0; n = collisions[n].next) { platforment *o = collisions[n].ent; if(passengers.find(o)<0) passengers.add(o); } } loopv(passengers) { physent *d = passengers[i]->d; d->o.add(dir); d->newpos.add(dir); if(dir.x || dir.y) updatedynentcache(d); } } else loopv(passengers) // move any stacked passengers who aren't colliding with non-passengers { platforment *ent = passengers[i]; if(colliders.find(ent)>=0) continue; physent *d = ent->d; d->o.add(dir); d->newpos.add(dir); if(dir.x || dir.y) updatedynentcache(d); for(int n = ent->stacks; n>=0; n = collisions[n].next) { platforment *o = collisions[n].ent; if(passengers.find(o)<0) passengers.add(o); } } p->o.add(dir); p->newpos.add(dir); if(dir.x || dir.y) updatedynentcache(p); return true; } #define dir(name,v,d,s,os) ICOMMAND(name, "D", (int *down), { player->s = *down!=0; player->v = player->s ? d : (player->os ? -(d) : 0); }); dir(backward, move, -1, k_down, k_up); dir(forward, move, 1, k_up, k_down); dir(left, strafe, 1, k_left, k_right); dir(right, strafe, -1, k_right, k_left); ICOMMAND(jump, "D", (int *down), { if(!*down || game::canjump()) player->jumping = *down!=0; }); ICOMMAND(attack, "D", (int *down), { game::doattack(*down!=0); }); bool entinmap(dynent *d, bool avoidplayers) // brute force but effective way to find a free spawn spot in the map { d->o.z += d->eyeheight; // pos specified is at feet vec orig = d->o; loopi(100) // try max 100 times { if(i) { d->o = orig; d->o.x += (rnd(21)-10)*i/5; // increasing distance d->o.y += (rnd(21)-10)*i/5; d->o.z += (rnd(21)-10)*i/5; } if(collide(d) && !inside) { if(hitplayer) { if(!avoidplayers) continue; d->o = orig; d->resetinterp(); return false; } d->resetinterp(); return true; } } // leave ent at original pos, possibly stuck d->o = orig; d->resetinterp(); conoutf(CON_WARN, "can't find entity spawn spot! (%.1f, %.1f, %.1f)", d->o.x, d->o.y, d->o.z); return false; } sauerbraten-0.0.20130203.dfsg/engine/decal.cpp0000644000175000017500000005124212062503331020415 0ustar vincentvincent#include "engine.h" struct decalvert { vec pos; float u, v; bvec color; uchar alpha; }; struct decalinfo { int millis; bvec color; ushort startvert, endvert; }; enum { DF_RND4 = 1<<0, DF_ROTATE = 1<<1, DF_INVMOD = 1<<2, DF_OVERBRIGHT = 1<<3, DF_ADD = 1<<4, DF_SATURATE = 1<<5 }; VARFP(maxdecaltris, 1, 1024, 16384, initdecals()); VARP(decalfade, 1000, 10000, 60000); VAR(dbgdec, 0, 0, 1); struct decalrenderer { const char *texname; int flags, fadeintime, fadeouttime, timetolive; Texture *tex; decalinfo *decals; int maxdecals, startdecal, enddecal; decalvert *verts; int maxverts, startvert, endvert, availverts; decalrenderer(const char *texname, int flags = 0, int fadeintime = 0, int fadeouttime = 1000, int timetolive = -1) : texname(texname), flags(flags), fadeintime(fadeintime), fadeouttime(fadeouttime), timetolive(timetolive), tex(NULL), decals(NULL), maxdecals(0), startdecal(0), enddecal(0), verts(NULL), maxverts(0), startvert(0), endvert(0), availverts(0), decalu(0), decalv(0) { } void init(int tris) { if(decals) { DELETEA(decals); maxdecals = startdecal = enddecal = 0; } if(verts) { DELETEA(verts); maxverts = startvert = endvert = availverts = 0; } decals = new decalinfo[tris]; maxdecals = tris; tex = textureload(texname, 3); maxverts = tris*3 + 3; availverts = maxverts - 3; verts = new decalvert[maxverts]; } int hasdecals() { return enddecal < startdecal ? maxdecals - (startdecal - enddecal) : enddecal - startdecal; } void cleardecals() { startdecal = enddecal = 0; startvert = endvert = 0; availverts = maxverts - 3; } int freedecal() { if(startdecal==enddecal) return 0; decalinfo &d = decals[startdecal]; startdecal++; if(startdecal >= maxdecals) startdecal = 0; int removed = d.endvert < d.startvert ? maxverts - (d.startvert - d.endvert) : d.endvert - d.startvert; startvert = d.endvert; if(startvert==endvert) startvert = endvert = 0; availverts += removed; return removed; } void fadedecal(decalinfo &d, uchar alpha) { bvec color; if(flags&DF_OVERBRIGHT) { if(renderpath!=R_FIXEDFUNCTION || hasTE) color = bvec(128, 128, 128); else color = bvec(alpha, alpha, alpha); } else { color = d.color; if(flags&(DF_ADD|DF_INVMOD)) loopk(3) color[k] = uchar((int(color[k])*int(alpha))>>8); } decalvert *vert = &verts[d.startvert], *end = &verts[d.endvert < d.startvert ? maxverts : d.endvert]; while(vert < end) { vert->color = color; vert->alpha = alpha; vert++; } if(d.endvert < d.startvert) { vert = verts; end = &verts[d.endvert]; while(vert < end) { vert->color = color; vert->alpha = alpha; vert++; } } } void clearfadeddecals() { int threshold = lastmillis - (timetolive>=0 ? timetolive : decalfade) - fadeouttime; decalinfo *d = &decals[startdecal], *end = &decals[enddecal < startdecal ? maxdecals : enddecal]; while(d < end && d->millis <= threshold) d++; if(d >= end && enddecal < startdecal) { d = decals; end = &decals[enddecal]; while(d < end && d->millis <= threshold) d++; } startdecal = d - decals; if(startdecal!=enddecal) startvert = decals[startdecal].startvert; else startvert = endvert = 0; availverts = endvert < startvert ? startvert - endvert - 3 : maxverts - 3 - (endvert - startvert); } void fadeindecals() { if(!fadeintime) return; decalinfo *d = &decals[enddecal], *end = &decals[enddecal < startdecal ? 0 : startdecal]; while(d > end) { d--; int fade = lastmillis - d->millis; if(fade >= fadeintime) return; fadedecal(*d, (fade<<8)/fadeintime); } if(enddecal < startdecal) { d = &decals[maxdecals]; end = &decals[startdecal]; while(d > end) { d--; int fade = lastmillis - d->millis; if(fade >= fadeintime) return; fadedecal(*d, (fade<<8)/fadeintime); } } } void fadeoutdecals() { decalinfo *d = &decals[startdecal], *end = &decals[enddecal < startdecal ? maxdecals : enddecal]; int offset = (timetolive>=0 ? timetolive : decalfade) + fadeouttime - lastmillis; while(d < end) { int fade = d->millis + offset; if(fade >= fadeouttime) return; fadedecal(*d, (fade<<8)/fadeouttime); d++; } if(enddecal < startdecal) { d = decals; end = &decals[enddecal]; while(d < end) { int fade = d->millis + offset; if(fade >= fadeouttime) return; fadedecal(*d, (fade<<8)/fadeouttime); d++; } } } static void setuprenderstate() { enablepolygonoffset(GL_POLYGON_OFFSET_FILL); glDepthMask(GL_FALSE); glEnable(GL_BLEND); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); } static void cleanuprenderstate() { glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDepthMask(GL_TRUE); glDisable(GL_BLEND); disablepolygonoffset(GL_POLYGON_OFFSET_FILL); } void render() { if(startvert==endvert) return; float oldfogc[4]; if(flags&(DF_ADD|DF_INVMOD|DF_OVERBRIGHT)) { glGetFloatv(GL_FOG_COLOR, oldfogc); static float zerofog[4] = { 0, 0, 0, 1 }, grayfog[4] = { 0.5f, 0.5f, 0.5f, 1 }; glFogfv(GL_FOG_COLOR, flags&DF_OVERBRIGHT && (renderpath!=R_FIXEDFUNCTION || hasTE) ? grayfog : zerofog); } if(flags&DF_OVERBRIGHT) { if(renderpath!=R_FIXEDFUNCTION) { glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR); SETSHADER(overbrightdecal); } else if(hasTE) { glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR); setuptmu(0, "T , C @ Ca"); } else glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA); } else { if(flags&DF_INVMOD) glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR); else if(flags&DF_ADD) glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR); else glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if(flags&DF_SATURATE) { if(renderpath!=R_FIXEDFUNCTION) SETSHADER(saturatedecal); else if(hasTE) setuptmu(0, "C * T x 2"); } else foggedshader->set(); } glBindTexture(GL_TEXTURE_2D, tex->id); glVertexPointer(3, GL_FLOAT, sizeof(decalvert), &verts->pos); glTexCoordPointer(2, GL_FLOAT, sizeof(decalvert), &verts->u); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(decalvert), &verts->color); int count = endvert < startvert ? maxverts - startvert : endvert - startvert; glDrawArrays(GL_TRIANGLES, startvert, count); if(endvert < startvert) { count += endvert; glDrawArrays(GL_TRIANGLES, 0, endvert); } xtravertsva += count; if(flags&(DF_ADD|DF_INVMOD|DF_OVERBRIGHT)) glFogfv(GL_FOG_COLOR, oldfogc); if(flags&(DF_OVERBRIGHT|DF_SATURATE) && renderpath==R_FIXEDFUNCTION && hasTE) resettmu(0); extern int intel_vertexarray_bug; if(intel_vertexarray_bug) glFlush(); } decalinfo &newdecal() { decalinfo &d = decals[enddecal]; int next = enddecal + 1; if(next>=maxdecals) next = 0; if(next==startdecal) freedecal(); enddecal = next; return d; } ivec bborigin, bbsize; vec decalcenter, decalnormal, decaltangent, decalbitangent; float decalradius, decalu, decalv; bvec decalcolor; void adddecal(const vec ¢er, const vec &dir, float radius, const bvec &color, int info) { int isz = int(ceil(radius)); bborigin = ivec(center).sub(isz); bbsize = ivec(isz*2, isz*2, isz*2); decalcolor = color; decalcenter = center; decalradius = radius; decalnormal = dir; #if 0 decaltangent.orthogonal(dir); #else decaltangent = vec(dir.z, -dir.x, dir.y); decaltangent.sub(vec(dir).mul(decaltangent.dot(dir))); #endif if(flags&DF_ROTATE) decaltangent.rotate(rnd(360)*RAD, dir); decaltangent.normalize(); decalbitangent.cross(decaltangent, dir); if(flags&DF_RND4) { decalu = 0.5f*(info&1); decalv = 0.5f*((info>>1)&1); } ushort dstart = endvert; gentris(worldroot, ivec(0, 0, 0), worldsize>>1); if(dbgdec) { int nverts = endvert < dstart ? endvert + maxverts - dstart : endvert - dstart; conoutf(CON_DEBUG, "tris = %d, verts = %d, total tris = %d", nverts/3, nverts, (maxverts - 3 - availverts)/3); } if(endvert==dstart) return; decalinfo &d = newdecal(); d.color = color; d.millis = lastmillis; d.startvert = dstart; d.endvert = endvert; } static int clip(const vec *in, int numin, const vec &dir, float below, float above, vec *out) { int numout = 0; const vec *p = &in[numin-1]; float pc = dir.dot(*p); loopi(numin) { const vec &v = in[i]; float c = dir.dot(v); if(c < below) { if(pc > above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); if(pc > below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); } else if(c > above) { if(pc < below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); if(pc < above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); } else { if(pc < below) { if(c > below) out[numout++] = vec(*p).sub(v).mul((below - c)/(pc - c)).add(v); } else if(pc > above && c < above) out[numout++] = vec(*p).sub(v).mul((above - c)/(pc - c)).add(v); out[numout++] = v; } p = &v; pc = c; } return numout; } void gentris(cube &cu, int orient, const ivec &o, int size, materialsurface *mat = NULL, int vismask = 0) { vec pos[MAXFACEVERTS+4]; int numverts = 0, numplanes = 1; vec planes[2]; if(mat) { planes[0] = vec(0, 0, 0); switch(orient) { #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: \ planes[0][dimension(orient)] = dimcoord(orient) ? 1 : -1; \ v0 v1 v2 v3 \ break; #define GENFACEVERT(orient, vert, x,y,z, xv,yv,zv) \ pos[numverts++] = vec(x xv, y yv, z zv); GENFACEVERTS(o.x, o.x, o.y, o.y, o.z, o.z, , + mat->csize, , + mat->rsize, + 0.1f, - 0.1f); #undef GENFACEORIENT #undef GENFACEVERT } } else if(cu.texture[orient] == DEFAULT_SKY) return; else if(cu.ext && (numverts = cu.ext->surfaces[orient].numverts&MAXFACEVERTS)) { vertinfo *verts = cu.ext->verts() + cu.ext->surfaces[orient].verts; ivec vo = ivec(o).mask(~0xFFF).shl(3); loopj(numverts) pos[j] = verts[j].getxyz().add(vo).tovec().mul(1/8.0f); planes[0].cross(pos[0], pos[1], pos[2]).normalize(); if(numverts >= 4 && !(cu.merged&(1< decalradius) continue; vec pcenter = vec(decalnormal).mul(dist).add(decalcenter); #else // travel back along plane normal from the decal center float dist = n.dot(p); if(fabs(dist) > decalradius) continue; vec pcenter = vec(n).mul(dist).add(decalcenter); #endif vec ft, fb; ft.orthogonal(n); ft.normalize(); fb.cross(ft, n); vec pt = vec(ft).mul(ft.dot(decaltangent)).add(vec(fb).mul(fb.dot(decaltangent))).normalize(), pb = vec(ft).mul(ft.dot(decalbitangent)).add(vec(fb).mul(fb.dot(decalbitangent))).normalize(); // orthonormalize projected bitangent to prevent streaking pb.sub(vec(pt).mul(pt.dot(pb))).normalize(); vec v1[MAXFACEVERTS+4], v2[MAXFACEVERTS+4]; float ptc = pt.dot(pcenter), pbc = pb.dot(pcenter); int numv; if(numplanes >= 2) { if(l) { pos[1] = pos[2]; pos[2] = pos[3]; } numv = clip(pos, 3, pt, ptc - decalradius, ptc + decalradius, v1); if(numv<3) continue; } else { numv = clip(pos, numverts, pt, ptc - decalradius, ptc + decalradius, v1); if(numv<3) continue; } numv = clip(v1, numv, pb, pbc - decalradius, pbc + decalradius, v2); if(numv<3) continue; float tsz = flags&DF_RND4 ? 0.5f : 1.0f, scale = tsz*0.5f/decalradius, tu = decalu + tsz*0.5f - ptc*scale, tv = decalv + tsz*0.5f - pbc*scale; pt.mul(scale); pb.mul(scale); decalvert dv1 = { v2[0], pt.dot(v2[0]) + tu, pb.dot(v2[0]) + tv, decalcolor, 255 }, dv2 = { v2[1], pt.dot(v2[1]) + tu, pb.dot(v2[1]) + tv, decalcolor, 255 }; int totalverts = 3*(numv-2); if(totalverts > maxverts-3) return; while(availverts < totalverts) { if(!freedecal()) return; } availverts -= totalverts; loopk(numv-2) { verts[endvert++] = dv1; verts[endvert++] = dv2; dv2.pos = v2[k+2]; dv2.u = pt.dot(v2[k+2]) + tu; dv2.v = pb.dot(v2[k+2]) + tv; verts[endvert++] = dv2; if(endvert>=maxverts) endvert = 0; } } } void findmaterials(vtxarray *va) { materialsurface *matbuf = va->matbuf; int matsurfs = va->matsurfs; loopi(matsurfs) { materialsurface &m = matbuf[i]; if(!isclipped(m.material&MATF_VOLUME)) { i += m.skip; continue; } int dim = dimension(m.orient), dc = dimcoord(m.orient); if(dc ? decalnormal[dim] <= 0 : decalnormal[dim] >= 0) { i += m.skip; continue; } int c = C[dim], r = R[dim]; for(;;) { materialsurface &m = matbuf[i]; if(m.o[dim] >= bborigin[dim] && m.o[dim] <= bborigin[dim] + bbsize[dim] && m.o[c] + m.csize >= bborigin[c] && m.o[c] <= bborigin[c] + bbsize[c] && m.o[r] + m.rsize >= bborigin[r] && m.o[r] <= bborigin[r] + bbsize[r]) { static cube dummy; gentris(dummy, m.orient, m.o, max(m.csize, m.rsize), &m); } if(i+1 >= matsurfs) break; materialsurface &n = matbuf[i+1]; if(n.material != m.material || n.orient != m.orient) break; i++; } } } void findescaped(cube *cu, const ivec &o, int size, int escaped) { loopi(8) { if(escaped&(1<>1, cu[i].escaped); else { int vismask = cu[i].merged; if(vismask) loopj(6) if(vismask&(1<va && cu[i].ext->va->matsurfs) findmaterials(cu[i].ext->va); if(cu[i].children) gentris(cu[i].children, co, size>>1, cu[i].escaped); else { int vismask = cu[i].visible; if(vismask&0xC0) { if(vismask&0x80) loopj(6) gentris(cu[i], j, co, size, NULL, vismask); else loopj(6) if(vismask&(1<>1, cu[i].escaped); else { int vismask = cu[i].merged; if(vismask) loopj(6) if(vismask&(1<packages/particles/scorch.png", DF_ROTATE, 500), decalrenderer("packages/particles/blood.png", DF_RND4|DF_ROTATE|DF_INVMOD), decalrenderer("packages/particles/bullet.png", DF_OVERBRIGHT) }; void initdecals() { loopi(sizeof(decals)/sizeof(decals[0])) decals[i].init(maxdecaltris); } void cleardecals() { loopi(sizeof(decals)/sizeof(decals[0])) decals[i].cleardecals(); } VARNP(decals, showdecals, 0, 1, 1); void renderdecals(bool mainpass) { bool rendered = false; loopi(sizeof(decals)/sizeof(decals[0])) { decalrenderer &d = decals[i]; if(mainpass) { d.clearfadeddecals(); d.fadeindecals(); d.fadeoutdecals(); } if(!showdecals || !d.hasdecals()) continue; if(!rendered) { rendered = true; decalrenderer::setuprenderstate(); } d.render(); } if(!rendered) return; decalrenderer::cleanuprenderstate(); } VARP(maxdecaldistance, 1, 512, 10000); void adddecal(int type, const vec ¢er, const vec &surface, float radius, const bvec &color, int info) { if(!showdecals || type<0 || (size_t)type>=sizeof(decals)/sizeof(decals[0]) || center.dist(camera1->o) - radius > maxdecaldistance) return; decalrenderer &d = decals[type]; d.adddecal(center, surface, radius, color, info); } sauerbraten-0.0.20130203.dfsg/engine/command.cpp0000644000175000017500000027243412077564412021010 0ustar vincentvincent// command.cpp: implements the parsing and execution of a tiny script language which // is largely backwards compatible with the quake console language. #include "engine.h" hashset idents; // contains ALL vars/commands/aliases vector identmap; ident *dummyident = NULL; int identflags = 0; static const int MAXARGS = 25; VARN(numargs, _numargs, MAXARGS, 0, 0); static inline void freearg(tagval &v) { switch(v.type) { case VAL_STR: delete[] v.s; break; case VAL_CODE: if(v.code[-1] == CODE_START) delete[] (uchar *)&v.code[-1]; break; } } static inline void forcenull(tagval &v) { switch(v.type) { case VAL_NULL: return; } freearg(v); v.setnull(); } static inline float forcefloat(tagval &v) { float f = 0.0f; switch(v.type) { case VAL_INT: f = v.i; break; case VAL_STR: f = parsefloat(v.s); break; case VAL_MACRO: f = parsefloat(v.s); break; case VAL_FLOAT: return v.f; } freearg(v); v.setfloat(f); return f; } static inline int forceint(tagval &v) { int i = 0; switch(v.type) { case VAL_FLOAT: i = v.f; break; case VAL_STR: i = parseint(v.s); break; case VAL_MACRO: i = parseint(v.s); break; case VAL_INT: return v.i; } freearg(v); v.setint(i); return i; } static inline const char *forcestr(tagval &v) { const char *s = ""; switch(v.type) { case VAL_FLOAT: s = floatstr(v.f); break; case VAL_INT: s = intstr(v.i); break; case VAL_STR: case VAL_MACRO: return v.s; } freearg(v); v.setstr(newstring(s)); return s; } static inline void forcearg(tagval &v, int type) { switch(type) { case RET_STR: if(v.type != VAL_STR) forcestr(v); break; case RET_INT: if(v.type != VAL_INT) forceint(v); break; case RET_FLOAT: if(v.type != VAL_FLOAT) forcefloat(v); break; } } static inline ident *forceident(tagval &v) { switch(v.type) { case VAL_IDENT: return v.id; case VAL_MACRO: { ident *id = newident(v.s, IDF_UNKNOWN); v.setident(id); return id; } case VAL_STR: { ident *id = newident(v.s, IDF_UNKNOWN); delete[] v.s; v.setident(id); return id; } } freearg(v); v.setident(dummyident); return dummyident; } void tagval::cleanup() { freearg(*this); } static inline void freeargs(tagval *args, int &oldnum, int newnum) { for(int i = newnum; i < oldnum; i++) freearg(args[i]); oldnum = newnum; } static inline void cleancode(ident &id) { if(id.code) { id.code[0] -= 0x100; if(int(id.code[0]) < 0x100) delete[] id.code; id.code = NULL; } } struct nullval : tagval { nullval() { setnull(); } } nullval; tagval noret = nullval, *commandret = &noret; void clear_command() { enumerate(idents, ident, i, { if(i.type==ID_ALIAS) { DELETEA(i.name); i.forcenull(); DELETEA(i.code); } }); } void clearoverride(ident &i) { if(!(i.flags&IDF_OVERRIDDEN)) return; switch(i.type) { case ID_ALIAS: if(i.valtype==VAL_STR) { if(!i.val.s[0]) break; delete[] i.val.s; } cleancode(i); i.valtype = VAL_STR; i.val.s = newstring(""); break; case ID_VAR: *i.storage.i = i.overrideval.i; i.changed(); break; case ID_FVAR: *i.storage.f = i.overrideval.f; i.changed(); break; case ID_SVAR: delete[] *i.storage.s; *i.storage.s = i.overrideval.s; i.changed(); break; } i.flags &= ~IDF_OVERRIDDEN; } void clearoverrides() { enumerate(idents, ident, i, clearoverride(i)); } static bool initedidents = false; static vector *identinits = NULL; static inline ident *addident(const ident &id) { if(!initedidents) { if(!identinits) identinits = new vector; identinits->add(id); return NULL; } ident &def = idents.access(id.name, id); def.index = identmap.length(); return identmap.add(&def); } static bool initidents() { initedidents = true; for(int i = 0; i < MAXARGS; i++) { defformatstring(argname)("arg%d", i+1); newident(argname, IDF_ARG); } dummyident = newident("//dummy", IDF_UNKNOWN); if(identinits) { loopv(*identinits) addident((*identinits)[i]); DELETEP(identinits); } return true; } static bool forceinitidents = initidents(); static const char *sourcefile = NULL, *sourcestr = NULL; static const char *debugline(const char *p, const char *fmt) { if(!sourcestr) return fmt; int num = 1; const char *line = sourcestr; for(;;) { const char *end = strchr(line, '\n'); if(!end) end = line + strlen(line); if(p >= line && p <= end) { static string buf; if(sourcefile) formatstring(buf)("%s:%d: %s", sourcefile, num, fmt); else formatstring(buf)("%d: %s", num, fmt); return buf; } if(!*end) break; line = end + 1; num++; } return fmt; } static struct identlink { ident *id; identlink *next; int usedargs; identstack *argstack; } noalias = { NULL, NULL, (1<next) total++; for(identlink *l = aliasstack; l != &noalias; l = l->next) { ident *id = l->id; ++depth; if(depth < dbgalias) conoutf(CON_ERROR, " %d) %s", total-depth+1, id->name); else if(l->next == &noalias) conoutf(CON_ERROR, depth == dbgalias ? " %d) %s" : " ..%d) %s", total-depth+1, id->name); } } static int nodebug = 0; static void debugcode(const char *fmt, ...) PRINTFARGS(1, 2); static void debugcode(const char *fmt, ...) { if(nodebug) return; va_list args; va_start(args, fmt); conoutfv(CON_ERROR, fmt, args); va_end(args); debugalias(); } static void debugcodeline(const char *p, const char *fmt, ...) PRINTFARGS(2, 3); static void debugcodeline(const char *p, const char *fmt, ...) { if(nodebug) return; va_list args; va_start(args, fmt); conoutfv(CON_ERROR, debugline(p, fmt), args); va_end(args); debugalias(); } ICOMMAND(nodebug, "e", (uint *body), { nodebug++; executeret(body, *commandret); nodebug--; }); void addident(ident *id) { addident(*id); } static inline void pusharg(ident &id, const tagval &v, identstack &stack) { stack.val = id.val; stack.valtype = id.valtype; stack.next = id.stack; id.stack = &stack; id.setval(v); cleancode(id); } static inline void poparg(ident &id) { if(!id.stack) return; identstack *stack = id.stack; if(id.valtype == VAL_STR) delete[] id.val.s; id.setval(*stack); cleancode(id); id.stack = stack->next; } ICOMMAND(push, "rte", (ident *id, tagval *v, uint *code), { if(id->type != ID_ALIAS || id->index < MAXARGS) return; identstack stack; pusharg(*id, *v, stack); v->type = VAL_NULL; id->flags &= ~IDF_UNKNOWN; executeret(code, *commandret); poparg(*id); }); static inline void pushalias(ident &id, identstack &stack) { if(id.type == ID_ALIAS && id.index >= MAXARGS) { pusharg(id, nullval, stack); id.flags &= ~IDF_UNKNOWN; } } static inline void popalias(ident &id) { if(id.type == ID_ALIAS && id.index >= MAXARGS) poparg(id); } KEYWORD(local, ID_LOCAL); static inline bool checknumber(const char *s) { if(isdigit(s[0])) return true; else switch(s[0]) { case '+': case '-': return isdigit(s[1]) || (s[1] == '.' && isdigit(s[2])); case '.': return isdigit(s[1]) != 0; default: return false; } } ident *newident(const char *name, int flags) { ident *id = idents.access(name); if(!id) { if(checknumber(name)) { debugcode("number %s is not a valid identifier name", name); return dummyident; } id = addident(ident(ID_ALIAS, newstring(name), flags)); } return id; } ident *writeident(const char *name, int flags) { ident *id = newident(name, flags); if(id->index < MAXARGS && !(aliasstack->usedargs&(1<index))) { pusharg(*id, nullval, aliasstack->argstack[id->index]); aliasstack->usedargs |= 1<index; } return id; } ident *readident(const char *name) { ident *id = idents.access(name); if(id && id->index < MAXARGS && !(aliasstack->usedargs&(1<index))) return NULL; return id; } void resetvar(char *name) { ident *id = idents.access(name); if(!id) return; if(id->flags&IDF_READONLY) debugcode("variable %s is read-only", id->name); else clearoverride(*id); } COMMAND(resetvar, "s"); static inline void setarg(ident &id, tagval &v) { if(aliasstack->usedargs&(1<argstack[id.index]); aliasstack->usedargs |= 1<type == ID_ALIAS) { if(id->index < MAXARGS) setarg(*id, v); else setalias(*id, v); } else { debugcode("cannot redefine builtin %s with an alias", id->name); freearg(v); } } else if(checknumber(name)) { debugcode("cannot alias number %s", name); freearg(v); } else { addident(ident(ID_ALIAS, newstring(name), v, identflags)); } } void alias(const char *name, const char *str) { tagval v; v.setstr(newstring(str)); setalias(name, v); } void alias(const char *name, tagval &v) { setalias(name, v); } ICOMMAND(alias, "st", (const char *name, tagval *v), { setalias(name, *v); v->type = VAL_NULL; }); // variable's and commands are registered through globals, see cube.h int variable(const char *name, int min, int cur, int max, int *storage, identfun fun, int flags) { addident(ident(ID_VAR, name, min, max, storage, (void *)fun, flags)); return cur; } float fvariable(const char *name, float min, float cur, float max, float *storage, identfun fun, int flags) { addident(ident(ID_FVAR, name, min, max, storage, (void *)fun, flags)); return cur; } char *svariable(const char *name, const char *cur, char **storage, identfun fun, int flags) { addident(ident(ID_SVAR, name, storage, (void *)fun, flags)); return newstring(cur); } #define _GETVAR(id, vartype, name, retval) \ ident *id = idents.access(name); \ if(!id || id->type!=vartype) return retval; #define GETVAR(id, name, retval) _GETVAR(id, ID_VAR, name, retval) #define OVERRIDEVAR(errorval, saveval, resetval, clearval) \ if(identflags&IDF_OVERRIDDEN || id->flags&IDF_OVERRIDE) \ { \ if(id->flags&IDF_PERSIST) \ { \ debugcode("cannot override persistent variable %s", id->name); \ errorval; \ } \ if(!(id->flags&IDF_OVERRIDDEN)) { saveval; id->flags |= IDF_OVERRIDDEN; } \ else { clearval; } \ } \ else \ { \ if(id->flags&IDF_OVERRIDDEN) { resetval; id->flags &= ~IDF_OVERRIDDEN; } \ clearval; \ } void setvar(const char *name, int i, bool dofunc, bool doclamp) { GETVAR(id, name, ); OVERRIDEVAR(return, id->overrideval.i = *id->storage.i, , ) if(doclamp) *id->storage.i = clamp(i, id->minval, id->maxval); else *id->storage.i = i; if(dofunc) id->changed(); } void setfvar(const char *name, float f, bool dofunc, bool doclamp) { _GETVAR(id, ID_FVAR, name, ); OVERRIDEVAR(return, id->overrideval.f = *id->storage.f, , ); if(doclamp) *id->storage.f = clamp(f, id->minvalf, id->maxvalf); else *id->storage.f = f; if(dofunc) id->changed(); } void setsvar(const char *name, const char *str, bool dofunc) { _GETVAR(id, ID_SVAR, name, ); OVERRIDEVAR(return, id->overrideval.s = *id->storage.s, delete[] id->overrideval.s, delete[] *id->storage.s); *id->storage.s = newstring(str); if(dofunc) id->changed(); } int getvar(const char *name) { GETVAR(id, name, 0); return *id->storage.i; } int getvarmin(const char *name) { GETVAR(id, name, 0); return id->minval; } int getvarmax(const char *name) { GETVAR(id, name, 0); return id->maxval; } float getfvarmin(const char *name) { _GETVAR(id, ID_FVAR, name, 0); return id->minvalf; } float getfvarmax(const char *name) { _GETVAR(id, ID_FVAR, name, 0); return id->maxvalf; } bool identexists(const char *name) { return idents.access(name)!=NULL; } ident *getident(const char *name) { return idents.access(name); } void touchvar(const char *name) { ident *id = idents.access(name); if(id) switch(id->type) { case ID_VAR: case ID_FVAR: case ID_SVAR: id->changed(); break; } } const char *getalias(const char *name) { ident *i = idents.access(name); return i && i->type==ID_ALIAS && (i->index >= MAXARGS || aliasstack->usedargs&(1<index)) ? i->getstr() : ""; } int clampvar(ident *id, int val, int minval, int maxval) { if(val < minval) val = minval; else if(val > maxval) val = maxval; else return val; debugcode(id->flags&IDF_HEX ? (minval <= 255 ? "valid range for %s is %d..0x%X" : "valid range for %s is 0x%X..0x%X") : "valid range for %s is %d..%d", id->name, minval, maxval); return val; } void setvarchecked(ident *id, int val) { if(id->flags&IDF_READONLY) debugcode("variable %s is read-only", id->name); #ifndef STANDALONE else if(!(id->flags&IDF_OVERRIDE) || identflags&IDF_OVERRIDDEN || game::allowedittoggle()) #else else #endif { OVERRIDEVAR(return, id->overrideval.i = *id->storage.i, , ) if(val < id->minval || val > id->maxval) val = clampvar(id, val, id->minval, id->maxval); *id->storage.i = val; id->changed(); // call trigger function if available #ifndef STANDALONE if(id->flags&IDF_OVERRIDE && !(identflags&IDF_OVERRIDDEN)) game::vartrigger(id); #endif } } float clampfvar(ident *id, float val, float minval, float maxval) { if(val < minval) val = minval; else if(val > maxval) val = maxval; else return val; debugcode("valid range for %s is %s..%s", id->name, floatstr(minval), floatstr(maxval)); return val; } void setfvarchecked(ident *id, float val) { if(id->flags&IDF_READONLY) debugcode("variable %s is read-only", id->name); #ifndef STANDALONE else if(!(id->flags&IDF_OVERRIDE) || identflags&IDF_OVERRIDDEN || game::allowedittoggle()) #else else #endif { OVERRIDEVAR(return, id->overrideval.f = *id->storage.f, , ); if(val < id->minvalf || val > id->maxvalf) val = clampfvar(id, val, id->minvalf, id->maxvalf); *id->storage.f = val; id->changed(); #ifndef STANDALONE if(id->flags&IDF_OVERRIDE && !(identflags&IDF_OVERRIDDEN)) game::vartrigger(id); #endif } } void setsvarchecked(ident *id, const char *val) { if(id->flags&IDF_READONLY) debugcode("variable %s is read-only", id->name); #ifndef STANDALONE else if(!(id->flags&IDF_OVERRIDE) || identflags&IDF_OVERRIDDEN || game::allowedittoggle()) #else else #endif { OVERRIDEVAR(return, id->overrideval.s = *id->storage.s, delete[] id->overrideval.s, delete[] *id->storage.s); *id->storage.s = newstring(val); id->changed(); #ifndef STANDALONE if(id->flags&IDF_OVERRIDE && !(identflags&IDF_OVERRIDDEN)) game::vartrigger(id); #endif } } bool addcommand(const char *name, identfun fun, const char *args) { uint argmask = 0; int numargs = 0; bool limit = true; for(const char *fmt = args; *fmt; fmt++) switch(*fmt) { case 'i': case 'b': case 'f': case 't': case 'N': case 'D': if(numargs < MAXARGS) numargs++; break; case 's': case 'e': case 'r': case '$': if(numargs < MAXARGS) { argmask |= 1< 8) fatal("builtin %s declared with too many args: %d", name, numargs); addident(ident(ID_COMMAND, name, args, argmask, (void *)fun)); return false; } bool addkeyword(int type, const char *name) { addident(ident(type, name, "", 0, NULL)); return true; } const char *parsestring(const char *p) { for(; *p; p++) switch(*p) { case '\r': case '\n': case '\"': return p; case '^': if(*++p) break; return p; } return p; } int unescapestring(char *dst, const char *src, const char *end) { char *start = dst; while(src < end) { int c = *src++; if(c == '^') { if(src >= end) break; int e = *src++; switch(e) { case 'n': *dst++ = '\n'; break; case 't': *dst++ = '\t'; break; case 'f': *dst++ = '\f'; break; default: *dst++ = e; break; } } else *dst++ = c; } return dst - start; } static char *conc(vector &buf, tagval *v, int n, bool space, const char *prefix = NULL, int prefixlen = 0) { if(prefix) { buf.put(prefix, prefixlen); if(space && n) buf.add(' '); } loopi(n) { const char *s = ""; int len = 0; switch(v[i].type) { case VAL_INT: s = intstr(v[i].i); break; case VAL_FLOAT: s = floatstr(v[i].f); break; case VAL_STR: s = v[i].s; break; case VAL_MACRO: s = v[i].s; len = v[i].code[-1]>>8; goto haslen; } len = int(strlen(s)); haslen: buf.put(s, len); if(i == n-1) break; if(space) buf.add(' '); } buf.add('\0'); return buf.getbuf(); } char *conc(tagval *v, int n, bool space, const char *prefix = NULL) { int len = space ? max(prefix ? n : n-1, 0) : 0, prefixlen = 0; if(prefix) { prefixlen = strlen(prefix); len += prefixlen; } loopi(n) switch(v[i].type) { case VAL_MACRO: len += v[i].code[-1]>>8; break; case VAL_STR: len += int(strlen(v[i].s)); break; default: { vector buf; buf.reserve(len); conc(buf, v, n, space, prefix, prefixlen); return newstring(buf.getbuf(), buf.length()-1); } } char *buf = newstring(prefix ? prefix : "", len); if(prefix && space && n) { buf[prefixlen] = ' '; buf[prefixlen] = '\0'; } loopi(n) { strcat(buf, v[i].s); if(i==n-1) break; if(space) strcat(buf, " "); } return buf; } static inline void skipcomments(const char *&p) { for(;;) { p += strspn(p, " \t\r"); if(p[0]!='/' || p[1]!='/') break; p += strcspn(p, "\n\0"); } } static inline char *cutstring(const char *&p, int &len) { p++; const char *end = parsestring(p); char *s = newstring(end - p); len = unescapestring(s, p, end); s[len] = '\0'; p = end; if(*p=='\"') p++; return s; } static inline const char *parseword(const char *p) { const int maxbrak = 100; static char brakstack[maxbrak]; int brakdepth = 0; for(;; p++) { p += strcspn(p, "\"/;()[] \t\r\n\0"); switch(p[0]) { case '"': case ';': case ' ': case '\t': case '\r': case '\n': case '\0': return p; case '/': if(p[1] == '/') return p; break; case '[': case '(': if(brakdepth >= maxbrak) return p; brakstack[brakdepth++] = p[0]; break; case ']': if(brakdepth <= 0 || brakstack[--brakdepth] != '[') return p; break; case ')': if(brakdepth <= 0 || brakstack[--brakdepth] != '(') return p; break; } } return p; } static inline char *cutword(const char *&p, int &len) { const char *word = p; p = parseword(p); len = p-word; if(!len) return NULL; return newstring(word, len); } static inline void compilestr(vector &code, const char *word, int len, bool macro = false) { if(len <= 3 && !macro) { uint op = CODE_VALI|RET_STR; for(int i = 0; i < len; i++) op |= uint(uchar(word[i]))<<((i+1)*8); code.add(op); return; } code.add((macro ? CODE_MACRO : CODE_VAL|RET_STR)|(len<<8)); code.put((const uint *)word, len/sizeof(uint)); size_t endlen = len%sizeof(uint); union { char c[sizeof(uint)]; uint u; } end; end.u = 0; memcpy(end.c, word + len - endlen, endlen); code.add(end.u); } static inline void compilestr(vector &code, const char *word = NULL) { if(!word) { code.add(CODE_VALI|RET_STR); return; } compilestr(code, word, int(strlen(word))); } static inline void compileint(vector &code, int i) { if(i >= -0x800000 && i <= 0x7FFFFF) code.add(CODE_VALI|RET_INT|(i<<8)); else { code.add(CODE_VAL|RET_INT); code.add(i); } } static inline void compilenull(vector &code) { code.add(CODE_VALI|RET_NULL); } static inline void compileblock(vector &code) { int start = code.length(); code.add(CODE_BLOCK); code.add(CODE_OFFSET|((start+2)<<8)); code.add(CODE_EXIT); code[start] |= uint(code.length() - (start + 1))<<8; } static inline void compileident(vector &code, ident *id) { code.add((id->index < MAXARGS ? CODE_IDENTARG : CODE_IDENT)|(id->index<<8)); } static inline void compileident(vector &code, const char *word = NULL) { compileident(code, word ? newident(word, IDF_UNKNOWN) : dummyident); } static inline void compileint(vector &code, const char *word = NULL) { return compileint(code, word ? parseint(word) : 0); } static inline void compilefloat(vector &code, float f) { if(int(f) == f && f >= -0x800000 && f <= 0x7FFFFF) code.add(CODE_VALI|RET_FLOAT|(int(f)<<8)); else { union { float f; uint u; } conv; conv.f = f; code.add(CODE_VAL|RET_FLOAT); code.add(conv.u); } } static inline void compilefloat(vector &code, const char *word = NULL) { return compilefloat(code, word ? parsefloat(word) : 0.0f); } static bool compilearg(vector &code, const char *&p, int wordtype); static void compilestatements(vector &code, const char *&p, int rettype, int brak = '\0'); static inline void compileval(vector &code, int wordtype, char *word, int wordlen) { switch(wordtype) { case VAL_STR: compilestr(code, word, wordlen, true); break; case VAL_ANY: compilestr(code, word, wordlen); break; case VAL_FLOAT: compilefloat(code, word); break; case VAL_INT: compileint(code, word); break; case VAL_CODE: { int start = code.length(); code.add(CODE_BLOCK); code.add(CODE_OFFSET|((start+2)<<8)); const char *p = word; compilestatements(code, p, VAL_ANY); code.add(CODE_EXIT|RET_STR); code[start] |= uint(code.length() - (start + 1))<<8; break; } case VAL_IDENT: compileident(code, word); break; default: break; } } static bool compileword(vector &code, const char *&p, int wordtype, char *&word, int &wordlen); static void compilelookup(vector &code, const char *&p, int ltype) { char *lookup = NULL; int lookuplen = 0; switch(*++p) { case '(': case '[': if(!compileword(code, p, VAL_STR, lookup, lookuplen)) goto invalid; break; case '$': compilelookup(code, p, VAL_STR); break; case '\"': lookup = cutstring(p, lookuplen); goto lookupid; default: { lookup = cutword(p, lookuplen); if(!lookup) goto invalid; lookupid: ident *id = newident(lookup, IDF_UNKNOWN); if(id) switch(id->type) { case ID_VAR: code.add(CODE_IVAR|((ltype >= VAL_ANY ? VAL_INT : ltype)<index<<8)); goto done; case ID_FVAR: code.add(CODE_FVAR|((ltype >= VAL_ANY ? VAL_FLOAT : ltype)<index<<8)); goto done; case ID_SVAR: code.add(CODE_SVAR|((ltype >= VAL_ANY ? VAL_STR : ltype)<index<<8)); goto done; case ID_ALIAS: code.add((id->index < MAXARGS ? CODE_LOOKUPARG : CODE_LOOKUP)|((ltype >= VAL_ANY ? VAL_STR : ltype)<index<<8)); goto done; case ID_COMMAND: { int comtype = CODE_COM, numargs = 0; code.add(CODE_ENTER); for(const char *fmt = id->args; *fmt; fmt++) switch(*fmt) { case 's': compilestr(code, NULL, 0, true); numargs++; break; case 'i': compileint(code); numargs++; break; case 'b': compileint(code, INT_MIN); numargs++; break; case 'f': compilefloat(code); numargs++; break; case 't': compilenull(code); numargs++; break; case 'e': compileblock(code); numargs++; break; case 'r': compileident(code); numargs++; break; case '$': compileident(code, id); numargs++; break; case 'N': compileint(code, -1); numargs++; break; #ifndef STANDALONE case 'D': comtype = CODE_COMD; numargs++; break; #endif case 'C': comtype = CODE_COMC; numargs = 1; goto endfmt; case 'V': comtype = CODE_COMV; numargs = 2; goto endfmt; case '1': case '2': case '3': case '4': break; } endfmt: code.add(comtype|(ltype < VAL_ANY ? ltype<index<<8)); code.add(CODE_EXIT|(ltype < VAL_ANY ? ltype< &code, const char *str, const char *end, bool macro) { int start = code.length(); code.add(macro ? CODE_MACRO : CODE_VAL|RET_STR); char *buf = (char *)code.reserve((end-str)/sizeof(uint)+1).buf; int len = 0; while(str < end) { int n = strcspn(str, "\r/\"@]\0"); memcpy(&buf[len], str, n); len += n; str += n; switch(*str) { case '\r': str++; break; case '\"': { const char *start = str; str = parsestring(str+1); if(*str=='\"') str++; memcpy(&buf[len], start, str-start); len += str-start; break; } case '/': if(str[1] == '/') str += strcspn(str, "\n\0"); else buf[len++] = *str++; break; case '@': case ']': if(str < end) { buf[len++] = *str++; break; } case '\0': goto done; } } done: memset(&buf[len], '\0', sizeof(uint)-len%sizeof(uint)); code.advance(len/sizeof(uint)+1); code[start] |= len<<8; return true; } static bool compileblocksub(vector &code, const char *&p) { char *lookup = NULL; int lookuplen = 0; switch(*p) { case '(': if(!compilearg(code, p, VAL_STR)) return false; break; case '[': if(!compilearg(code, p, VAL_STR)) return false; code.add(CODE_LOOKUPU|RET_STR); break; case '\"': lookup = cutstring(p, lookuplen); goto lookupid; default: { { const char *start = p; while(iscubealnum(*p) || *p=='_') p++; lookuplen = p-start; if(!lookuplen) return false; lookup = newstring(start, lookuplen); } lookupid: ident *id = newident(lookup, IDF_UNKNOWN); if(id) switch(id->type) { case ID_VAR: code.add(CODE_IVAR|RET_STR|(id->index<<8)); goto done; case ID_FVAR: code.add(CODE_FVAR|RET_STR|(id->index<<8)); goto done; case ID_SVAR: code.add(CODE_SVAR|RET_STR|(id->index<<8)); goto done; case ID_ALIAS: code.add((id->index < MAXARGS ? CODE_LOOKUPARG : CODE_LOOKUP)|RET_STR|(id->index<<8)); goto done; } compilestr(code, lookup, lookuplen, true); code.add(CODE_LOOKUPU|RET_STR); done: delete[] lookup; break; } } return true; } static void compileblock(vector &code, const char *&p, int wordtype) { const char *line = p, *start = p; int concs = 0; for(int brak = 1; brak;) { p += strcspn(p, "@\"/[]\0"); int c = *p++; switch(c) { case '\0': debugcodeline(line, "missing \"]\""); p--; goto done; case '\"': p = parsestring(p); if(*p=='\"') p++; break; case '/': if(*p=='/') p += strcspn(p, "\n\0"); break; case '[': brak++; break; case ']': brak--; break; case '@': { const char *esc = p; while(*p == '@') p++; int level = p - (esc - 1); if(brak > level) continue; else if(brak < level) debugcodeline(line, "too many @s"); if(!concs) code.add(CODE_ENTER); if(concs + 2 > MAXARGS) { code.add(CODE_CONCW|RET_STR|(concs<<8)); concs = 1; } if(compileblockstr(code, start, esc-1, true)) concs++; if(compileblocksub(code, p)) concs++; if(!concs) code.pop(); else start = p; break; } } } done: if(p-1 > start) { if(!concs) switch(wordtype) { case VAL_CODE: { p = start; int inst = code.length(); code.add(CODE_BLOCK); code.add(CODE_OFFSET|((inst+2)<<8)); compilestatements(code, p, VAL_ANY, ']'); code.add(CODE_EXIT); code[inst] |= uint(code.length() - (inst + 1))<<8; return; } case VAL_IDENT: { char *name = newstring(start, p-1-start); compileident(code, name); delete[] name; return; } } compileblockstr(code, start, p-1, concs > 0); if(concs > 1) concs++; } if(concs) { code.add(CODE_CONCM|(wordtype < VAL_ANY ? wordtype< &code, const char *&p, int wordtype, char *&word, int &wordlen) { skipcomments(p); switch(*p) { case '\"': word = cutstring(p, wordlen); break; case '$': compilelookup(code, p, wordtype); return true; case '(': p++; code.add(CODE_ENTER); compilestatements(code, p, VAL_ANY, ')'); code.add(CODE_EXIT|(wordtype < VAL_ANY ? wordtype< &code, const char *&p, int wordtype) { char *word = NULL; int wordlen = 0; bool more = compileword(code, p, wordtype, word, wordlen); if(!more) return false; if(word) { compileval(code, wordtype, word, wordlen); delete[] word; } return true; } static void compilestatements(vector &code, const char *&p, int rettype, int brak) { const char *line = p; char *idname = NULL; int idlen = 0; ident *id = NULL; int numargs = 0; for(;;) { skipcomments(p); idname = NULL; bool more = compileword(code, p, VAL_ANY, idname, idlen); if(!more) goto endstatement; skipcomments(p); if(p[0] == '=') switch(p[1]) { case '/': if(p[2] != '/') break; case ';': case ' ': case '\t': case '\r': case '\n': case '\0': p++; if(idname) { id = newident(idname, IDF_UNKNOWN); if(!id || id->type != ID_ALIAS) { compilestr(code, idname, idlen, true); id = NULL; } delete[] idname; } if(!(more = compilearg(code, p, VAL_ANY))) compilestr(code); code.add(id && idname ? (id->index < MAXARGS ? CODE_ALIASARG : CODE_ALIAS)|(id->index<<8) : CODE_ALIASU); goto endstatement; } numargs = 0; if(!idname) { noid: while(numargs < MAXARGS && (more = compilearg(code, p, VAL_ANY))) numargs++; code.add(CODE_CALLU); } else { id = idents.access(idname); if(!id) { if(!checknumber(idname)) { compilestr(code, idname, idlen); delete[] idname; goto noid; } char *end = idname; int val = int(strtol(idname, &end, 0)); if(*end) compilestr(code, idname, idlen); else compileint(code, val); code.add(CODE_RESULT); } else switch(id->type) { case ID_ALIAS: while(numargs < MAXARGS && (more = compilearg(code, p, VAL_ANY))) numargs++; code.add(CODE_CALL|(id->index<<8)); break; case ID_COMMAND: { int comtype = CODE_COM, fakeargs = 0; bool rep = false; for(const char *fmt = id->args; *fmt; fmt++) switch(*fmt) { case 's': if(more) more = compilearg(code, p, VAL_STR); if(!more) { if(rep) break; compilestr(code, NULL, 0, true); fakeargs++; } else if(!fmt[1]) { int numconc = 0; while(numargs + numconc < MAXARGS && (more = compilearg(code, p, VAL_STR))) numconc++; if(numconc > 0) code.add(CODE_CONC|RET_STR|((numconc+1)<<8)); } numargs++; break; case 'i': if(more) more = compilearg(code, p, VAL_INT); if(!more) { if(rep) break; compileint(code); fakeargs++; } numargs++; break; case 'b': if(more) more = compilearg(code, p, VAL_INT); if(!more) { if(rep) break; compileint(code, INT_MIN); fakeargs++; } numargs++; break; case 'f': if(more) more = compilearg(code, p, VAL_FLOAT); if(!more) { if(rep) break; compilefloat(code); fakeargs++; } numargs++; break; case 't': if(more) more = compilearg(code, p, VAL_ANY); if(!more) { if(rep) break; compilenull(code); fakeargs++; } numargs++; break; case 'e': if(more) more = compilearg(code, p, VAL_CODE); if(!more) { if(rep) break; compileblock(code); fakeargs++; } numargs++; break; case 'r': if(more) more = compilearg(code, p, VAL_IDENT); if(!more) { if(rep) break; compileident(code); fakeargs++; } numargs++; break; case '$': compileident(code, id); numargs++; break; case 'N': compileint(code, numargs-fakeargs); numargs++; break; #ifndef STANDALONE case 'D': comtype = CODE_COMD; numargs++; break; #endif case 'C': comtype = CODE_COMC; if(more) while(numargs < MAXARGS && (more = compilearg(code, p, VAL_ANY))) numargs++; numargs = 1; goto endfmt; case 'V': comtype = CODE_COMV; if(more) while(numargs < MAXARGS && (more = compilearg(code, p, VAL_ANY))) numargs++; numargs = 2; goto endfmt; case '1': case '2': case '3': case '4': if(more) { fmt -= *fmt-'0'+1; rep = true; } break; } endfmt: code.add(comtype|(rettype < VAL_ANY ? rettype<index<<8)); break; } case ID_LOCAL: if(more) while(numargs < MAXARGS && (more = compilearg(code, p, VAL_IDENT))) numargs++; if(more) while((more = compilearg(code, p, VAL_ANY))) code.add(CODE_POP); code.add(CODE_LOCAL); break; case ID_VAR: if(!(more = compilearg(code, p, VAL_INT))) code.add(CODE_PRINT|(id->index<<8)); else if(!(id->flags&IDF_HEX) || !(more = compilearg(code, p, VAL_INT))) code.add(CODE_IVAR1|(id->index<<8)); else if(!(more = compilearg(code, p, VAL_INT))) code.add(CODE_IVAR2|(id->index<<8)); else code.add(CODE_IVAR3|(id->index<<8)); break; case ID_FVAR: if(!(more = compilearg(code, p, VAL_FLOAT))) code.add(CODE_PRINT|(id->index<<8)); else code.add(CODE_FVAR1|(id->index<<8)); break; case ID_SVAR: if(!(more = compilearg(code, p, VAL_STR))) code.add(CODE_PRINT|(id->index<<8)); else { int numconc = 0; while(numconc+1 < MAXARGS && (more = compilearg(code, p, VAL_ANY))) numconc++; if(numconc > 0) code.add(CODE_CONC|RET_STR|((numconc+1)<<8)); code.add(CODE_SVAR1|(id->index<<8)); } break; } delete[] idname; } endstatement: if(more) while(compilearg(code, p, VAL_ANY)) code.add(CODE_POP); p += strcspn(p, ")];/\n\0"); int c = *p++; switch(c) { case '\0': if(c != brak) debugcodeline(line, "missing \"%c\"", brak); p--; return; case ')': case ']': if(c == brak) return; debugcodeline(line, "unexpected \"%c\"", c); break; case '/': if(*p == '/') p += strcspn(p, "\n\0"); goto endstatement; } } } static void compilemain(vector &code, const char *p, int rettype = VAL_ANY) { code.add(CODE_START); compilestatements(code, p, VAL_ANY); code.add(CODE_EXIT|(rettype < VAL_ANY ? rettype< buf; buf.reserve(64); compilemain(buf, p); uint *code = new uint[buf.length()]; memcpy(code, buf.getbuf(), buf.length()*sizeof(uint)); code[0] += 0x100; return code; } void keepcode(uint *code) { if(!code) return; switch(*code&CODE_OP_MASK) { case CODE_START: *code += 0x100; return; } switch(code[-1]&CODE_OP_MASK) { case CODE_START: code[-1] += 0x100; break; case CODE_OFFSET: code -= int(code[-1]>>8); *code += 0x100; break; } } void freecode(uint *code) { if(!code) return; switch(*code&CODE_OP_MASK) { case CODE_START: *code -= 0x100; if(int(*code) < 0x100) delete[] code; return; } switch(code[-1]&CODE_OP_MASK) { case CODE_START: code[-1] -= 0x100; if(int(code[-1]) < 0x100) delete[] &code[-1]; break; case CODE_OFFSET: code -= int(code[-1]>>8); *code -= 0x100; if(int(*code) < 0x100) delete[] code; break; } } void printvar(ident *id, int i) { if(i < 0) conoutf("%s = %d", id->name, i); else if(id->flags&IDF_HEX && id->maxval==0xFFFFFF) conoutf("%s = 0x%.6X (%d, %d, %d)", id->name, i, (i>>16)&0xFF, (i>>8)&0xFF, i&0xFF); else conoutf(id->flags&IDF_HEX ? "%s = 0x%X" : "%s = %d", id->name, i); } void printfvar(ident *id, float f) { conoutf("%s = %s", id->name, floatstr(f)); } void printsvar(ident *id, const char *s) { conoutf(strchr(s, '"') ? "%s = [%s]" : "%s = \"%s\"", id->name, s); } void printvar(ident *id) { switch(id->type) { case ID_VAR: printvar(id, *id->storage.i); break; case ID_FVAR: printfvar(id, *id->storage.f); break; case ID_SVAR: printsvar(id, *id->storage.s); break; } } typedef void (__cdecl *comfun)(); typedef void (__cdecl *comfun1)(void *); typedef void (__cdecl *comfun2)(void *, void *); typedef void (__cdecl *comfun3)(void *, void *, void *); typedef void (__cdecl *comfun4)(void *, void *, void *, void *); typedef void (__cdecl *comfun5)(void *, void *, void *, void *, void *); typedef void (__cdecl *comfun6)(void *, void *, void *, void *, void *, void *); typedef void (__cdecl *comfun7)(void *, void *, void *, void *, void *, void *, void *); typedef void (__cdecl *comfun8)(void *, void *, void *, void *, void *, void *, void *, void *); typedef void (__cdecl *comfunv)(tagval *, int); static const uint *skipcode(const uint *code, tagval &result) { int depth = 0; for(;;) { uint op = *code++; switch(op&0xFF) { case CODE_MACRO: case CODE_VAL|RET_STR: { uint len = op>>8; code += len/sizeof(uint) + 1; continue; } case CODE_BLOCK: { uint len = op>>8; code += len; continue; } case CODE_ENTER: ++depth; continue; case CODE_EXIT|RET_NULL: case CODE_EXIT|RET_STR: case CODE_EXIT|RET_INT: case CODE_EXIT|RET_FLOAT: if(depth <= 0) { forcearg(result, op&CODE_RET_MASK); return code; } --depth; continue; } } } static inline void callcommand(ident *id, tagval *args, int numargs, bool lookup = false) { int i = -1, fakeargs = 0; bool rep = false; for(const char *fmt = id->args; *fmt; fmt++) switch(*fmt) { case 'i': if(++i >= numargs) { if(rep) break; args[i].setint(0); fakeargs++; } else forceint(args[i]); break; case 'b': if(++i >= numargs) { if(rep) break; args[i].setint(INT_MIN); fakeargs++; } else forceint(args[i]); break; case 'f': if(++i >= numargs) { if(rep) break; args[i].setfloat(0.0f); fakeargs++; } else forcefloat(args[i]); break; case 's': if(++i >= numargs) { if(rep) break; args[i].setstr(newstring("")); fakeargs++; } else forcestr(args[i]); break; case 't': if(++i >= numargs) { if(rep) break; args[i].setnull(); fakeargs++; } break; case 'e': if(++i >= numargs) { if(rep) break; static uint buf[2] = { CODE_START + 0x100, CODE_EXIT }; args[i].setcode(buf); fakeargs++; } else { vector buf; buf.reserve(64); compilemain(buf, numargs <= i ? "" : args[i].getstr()); freearg(args[i]); args[i].setcode(buf.getbuf()+1); buf.disown(); } break; case 'r': if(++i >= numargs) { if(rep) break; args[i].setident(dummyident); fakeargs++; } else forceident(args[i]); break; case '$': if(++i < numargs) freearg(args[i]); args[i].setident(id); break; case 'N': if(++i < numargs) freearg(args[i]); args[i].setint(lookup ? -1 : i-fakeargs); break; #ifndef STANDALONE case 'D': if(++i < numargs) freearg(args[i]); args[i].setint(addreleaseaction(conc(args, i, true, id->name)) ? 1 : 0); fakeargs++; break; #endif case 'C': { i = max(i+1, numargs); vector buf; ((comfun1)id->fun)(conc(buf, args, i, true)); goto cleanup; } case 'V': i = max(i+1, numargs); ((comfunv)id->fun)(args, i); goto cleanup; case '1': case '2': case '3': case '4': if(i+1 < numargs) { fmt -= *fmt-'0'+1; rep = true; } break; } #define ARG(n) (id->argmask&(1<fun)(); break; \ case 1: ((comfun1)id->fun)(ARG(0)); break; \ case 2: ((comfun2)id->fun)(ARG(0), ARG(1)); break; \ case 3: ((comfun3)id->fun)(ARG(0), ARG(1), ARG(2)); break; \ case 4: ((comfun4)id->fun)(ARG(0), ARG(1), ARG(2), ARG(3)); break; \ case 5: ((comfun5)id->fun)(ARG(0), ARG(1), ARG(2), ARG(3), ARG(4)); break; \ case 6: ((comfun6)id->fun)(ARG(0), ARG(1), ARG(2), ARG(3), ARG(4), ARG(5)); break; \ case 7: ((comfun7)id->fun)(ARG(0), ARG(1), ARG(2), ARG(3), ARG(4), ARG(5), ARG(6)); break; \ case 8: ((comfun8)id->fun)(ARG(0), ARG(1), ARG(2), ARG(3), ARG(4), ARG(5), ARG(6), ARG(7)); break; \ } ++i; CALLCOM(i) cleanup: loopk(i) freearg(args[k]); for(; i < numargs; i++) freearg(args[i]); } #define MAXRUNDEPTH 255 static int rundepth = 0; static const uint *runcode(const uint *code, tagval &result) { result.setnull(); if(rundepth >= MAXRUNDEPTH) { debugcode("exceeded recursion limit"); return skipcode(code, result); } ++rundepth; ident *id = NULL; int numargs = 0; tagval args[MAXARGS+1], *prevret = commandret; commandret = &result; for(;;) { uint op = *code++; switch(op&0xFF) { case CODE_START: case CODE_OFFSET: continue; case CODE_POP: freearg(args[--numargs]); continue; case CODE_ENTER: code = runcode(code, args[numargs++]); continue; case CODE_EXIT|RET_NULL: case CODE_EXIT|RET_STR: case CODE_EXIT|RET_INT: case CODE_EXIT|RET_FLOAT: forcearg(result, op&CODE_RET_MASK); goto exit; case CODE_PRINT: printvar(identmap[op>>8]); continue; case CODE_LOCAL: { identstack locals[MAXARGS]; freearg(result); loopi(numargs) pushalias(*args[i].id, locals[i]); code = runcode(code, result); loopi(numargs) popalias(*args[i].id); goto exit; } case CODE_MACRO: { uint len = op>>8; args[numargs++].setmacro(code); code += len/sizeof(uint) + 1; continue; } case CODE_VAL|RET_STR: { uint len = op>>8; args[numargs++].setstr(newstring((const char *)code, len)); code += len/sizeof(uint) + 1; continue; } case CODE_VALI|RET_STR: { char s[4] = { char((op>>8)&0xFF), char((op>>16)&0xFF), char((op>>24)&0xFF), '\0' }; args[numargs++].setstr(newstring(s)); continue; } case CODE_VAL|RET_NULL: case CODE_VALI|RET_NULL: args[numargs++].setnull(); continue; case CODE_VAL|RET_INT: args[numargs++].setint(int(*code++)); continue; case CODE_VALI|RET_INT: args[numargs++].setint(int(op)>>8); continue; case CODE_VAL|RET_FLOAT: args[numargs++].setfloat(*(const float *)code++); continue; case CODE_VALI|RET_FLOAT: args[numargs++].setfloat(float(int(op)>>8)); continue; case CODE_FORCE|RET_STR: forcestr(args[numargs-1]); continue; case CODE_FORCE|RET_INT: forceint(args[numargs-1]); continue; case CODE_FORCE|RET_FLOAT: forcefloat(args[numargs-1]); continue; case CODE_RESULT|RET_NULL: case CODE_RESULT|RET_STR: case CODE_RESULT|RET_INT: case CODE_RESULT|RET_FLOAT: litval: freearg(result); result = args[0]; forcearg(result, op&CODE_RET_MASK); args[0].setnull(); freeargs(args, numargs, 0); continue; case CODE_BLOCK: { uint len = op>>8; args[numargs++].setcode(code+1); code += len; continue; } case CODE_COMPILE: { tagval &arg = args[numargs-1]; vector buf; switch(arg.type) { case VAL_INT: buf.reserve(8); buf.add(CODE_START); compileint(buf, arg.i); buf.add(CODE_RESULT); buf.add(CODE_EXIT); break; case VAL_FLOAT: buf.reserve(8); buf.add(CODE_START); compilefloat(buf, arg.f); buf.add(CODE_RESULT); buf.add(CODE_EXIT); break; case VAL_STR: case VAL_MACRO: buf.reserve(64); compilemain(buf, arg.s); freearg(arg); break; default: buf.reserve(8); buf.add(CODE_START); compilenull(buf); buf.add(CODE_RESULT); buf.add(CODE_EXIT); break; } arg.setcode(buf.getbuf()+1); buf.disown(); continue; } case CODE_IDENT: args[numargs++].setident(identmap[op>>8]); continue; case CODE_IDENTARG: { ident *id = identmap[op>>8]; if(!(aliasstack->usedargs&(1<index))) { pusharg(*id, nullval, aliasstack->argstack[id->index]); aliasstack->usedargs |= 1<index; } args[numargs++].setident(id); continue; } case CODE_IDENTU: { tagval &arg = args[numargs-1]; ident *id = arg.type == VAL_STR || arg.type == VAL_MACRO ? newident(arg.s, IDF_UNKNOWN) : dummyident; if(id->index < MAXARGS && !(aliasstack->usedargs&(1<index))) { pusharg(*id, nullval, aliasstack->argstack[id->index]); aliasstack->usedargs |= 1<index; } freearg(arg); arg.setident(id); continue; } case CODE_LOOKUPU|RET_STR: #define LOOKUPU(aval, sval, ival, fval, nval) { \ tagval &arg = args[numargs-1]; \ if(arg.type != VAL_STR && arg.type != VAL_MACRO) continue; \ id = idents.access(arg.s); \ if(id) switch(id->type) \ { \ case ID_ALIAS: \ if(id->flags&IDF_UNKNOWN) break; \ freearg(arg); \ if(id->index < MAXARGS && !(aliasstack->usedargs&(1<index))) { nval; continue; } \ aval; \ continue; \ case ID_SVAR: freearg(arg); sval; continue; \ case ID_VAR: freearg(arg); ival; continue; \ case ID_FVAR: freearg(arg); fval; continue; \ case ID_COMMAND: \ { \ freearg(arg); \ arg.setnull(); \ commandret = &arg; \ tagval buf[MAXARGS]; \ callcommand(id, buf, 0, true); \ forcearg(arg, op&CODE_RET_MASK); \ commandret = &result; \ continue; \ } \ default: freearg(arg); nval; continue; \ } \ debugcode("unknown alias lookup: %s", arg.s); \ freearg(arg); \ nval; \ continue; \ } LOOKUPU(arg.setstr(newstring(id->getstr())), arg.setstr(newstring(*id->storage.s)), arg.setstr(newstring(intstr(*id->storage.i))), arg.setstr(newstring(floatstr(*id->storage.f))), arg.setstr(newstring(""))); case CODE_LOOKUP|RET_STR: #define LOOKUP(aval) { \ id = identmap[op>>8]; \ if(id->flags&IDF_UNKNOWN) debugcode("unknown alias lookup: %s", id->name); \ aval; \ continue; \ } LOOKUP(args[numargs++].setstr(newstring(id->getstr()))); case CODE_LOOKUPARG|RET_STR: #define LOOKUPARG(aval, nval) { \ id = identmap[op>>8]; \ if(!(aliasstack->usedargs&(1<index))) { nval; continue; } \ aval; \ continue; \ } LOOKUPARG(args[numargs++].setstr(newstring(id->getstr())), args[numargs++].setstr(newstring(""))); case CODE_LOOKUPU|RET_INT: LOOKUPU(arg.setint(id->getint()), arg.setint(parseint(*id->storage.s)), arg.setint(*id->storage.i), arg.setint(int(*id->storage.f)), arg.setint(0)); case CODE_LOOKUP|RET_INT: LOOKUP(args[numargs++].setint(id->getint())); case CODE_LOOKUPARG|RET_INT: LOOKUPARG(args[numargs++].setint(id->getint()), args[numargs++].setint(0)); case CODE_LOOKUPU|RET_FLOAT: LOOKUPU(arg.setfloat(id->getfloat()), arg.setfloat(parsefloat(*id->storage.s)), arg.setfloat(float(*id->storage.i)), arg.setfloat(*id->storage.f), arg.setfloat(0.0f)); case CODE_LOOKUP|RET_FLOAT: LOOKUP(args[numargs++].setfloat(id->getfloat())); case CODE_LOOKUPARG|RET_FLOAT: LOOKUPARG(args[numargs++].setfloat(id->getfloat()), args[numargs++].setfloat(0.0f)); case CODE_LOOKUPU|RET_NULL: LOOKUPU(id->getval(arg), arg.setstr(newstring(*id->storage.s)), arg.setint(*id->storage.i), arg.setfloat(*id->storage.f), arg.setnull()); case CODE_LOOKUP|RET_NULL: LOOKUP(id->getval(args[numargs++])); case CODE_LOOKUPARG|RET_NULL: LOOKUPARG(id->getval(args[numargs++]), args[numargs++].setnull()); case CODE_SVAR|RET_STR: case CODE_SVAR|RET_NULL: args[numargs++].setstr(newstring(*identmap[op>>8]->storage.s)); continue; case CODE_SVAR|RET_INT: args[numargs++].setint(parseint(*identmap[op>>8]->storage.s)); continue; case CODE_SVAR|RET_FLOAT: args[numargs++].setfloat(parsefloat(*identmap[op>>8]->storage.s)); continue; case CODE_SVAR1: setsvarchecked(identmap[op>>8], args[0].s); freeargs(args, numargs, 0); continue; case CODE_IVAR|RET_INT: case CODE_IVAR|RET_NULL: args[numargs++].setint(*identmap[op>>8]->storage.i); continue; case CODE_IVAR|RET_STR: args[numargs++].setstr(newstring(intstr(*identmap[op>>8]->storage.i))); continue; case CODE_IVAR|RET_FLOAT: args[numargs++].setfloat(float(*identmap[op>>8]->storage.i)); continue; case CODE_IVAR1: setvarchecked(identmap[op>>8], args[0].i); numargs = 0; continue; case CODE_IVAR2: setvarchecked(identmap[op>>8], (args[0].i<<16)|(args[1].i<<8)); numargs = 0; continue; case CODE_IVAR3: setvarchecked(identmap[op>>8], (args[0].i<<16)|(args[1].i<<8)|args[2].i); numargs = 0; continue; case CODE_FVAR|RET_FLOAT: case CODE_FVAR|RET_NULL: args[numargs++].setfloat(*identmap[op>>8]->storage.f); continue; case CODE_FVAR|RET_STR: args[numargs++].setstr(newstring(floatstr(*identmap[op>>8]->storage.f))); continue; case CODE_FVAR|RET_INT: args[numargs++].setint(int(*identmap[op>>8]->storage.f)); continue; case CODE_FVAR1: setfvarchecked(identmap[op>>8], args[0].f); numargs = 0; continue; case CODE_COM|RET_NULL: case CODE_COM|RET_STR: case CODE_COM|RET_FLOAT: case CODE_COM|RET_INT: id = identmap[op>>8]; #ifndef STANDALONE callcom: #endif forcenull(result); CALLCOM(numargs) forceresult: freeargs(args, numargs, 0); forcearg(result, op&CODE_RET_MASK); continue; #ifndef STANDALONE case CODE_COMD|RET_NULL: case CODE_COMD|RET_STR: case CODE_COMD|RET_FLOAT: case CODE_COMD|RET_INT: id = identmap[op>>8]; args[numargs].setint(addreleaseaction(conc(args, numargs, true, id->name)) ? 1 : 0); numargs++; goto callcom; #endif case CODE_COMV|RET_NULL: case CODE_COMV|RET_STR: case CODE_COMV|RET_FLOAT: case CODE_COMV|RET_INT: id = identmap[op>>8]; forcenull(result); ((comfunv)id->fun)(args, numargs); goto forceresult; case CODE_COMC|RET_NULL: case CODE_COMC|RET_STR: case CODE_COMC|RET_FLOAT: case CODE_COMC|RET_INT: id = identmap[op>>8]; forcenull(result); { vector buf; ((comfun1)id->fun)(conc(buf, args, numargs, true)); } goto forceresult; case CODE_CONC|RET_NULL: case CODE_CONC|RET_STR: case CODE_CONC|RET_FLOAT: case CODE_CONC|RET_INT: case CODE_CONCW|RET_NULL: case CODE_CONCW|RET_STR: case CODE_CONCW|RET_FLOAT: case CODE_CONCW|RET_INT: { int numconc = op>>8; char *s = conc(&args[numargs-numconc], numconc, (op&CODE_OP_MASK)==CODE_CONC); freeargs(args, numargs, numargs-numconc); args[numargs++].setstr(s); forcearg(args[numargs-1], op&CODE_RET_MASK); continue; } case CODE_CONCM|RET_NULL: case CODE_CONCM|RET_STR: case CODE_CONCM|RET_FLOAT: case CODE_CONCM|RET_INT: { int numconc = op>>8; char *s = conc(&args[numargs-numconc], numconc, false); freeargs(args, numargs, numargs-numconc); result.setstr(s); forcearg(result, op&CODE_RET_MASK); continue; } case CODE_ALIAS: setalias(*identmap[op>>8], args[--numargs]); freeargs(args, numargs, 0); continue; case CODE_ALIASARG: setarg(*identmap[op>>8], args[--numargs]); freeargs(args, numargs, 0); continue; case CODE_ALIASU: forcestr(args[0]); setalias(args[0].s, args[--numargs]); freeargs(args, numargs, 0); continue; case CODE_CALL|RET_NULL: case CODE_CALL|RET_STR: case CODE_CALL|RET_FLOAT: case CODE_CALL|RET_INT: #define CALLALIAS(offset) { \ identstack argstack[MAXARGS]; \ for(int i = 0; i < numargs-offset; i++) \ pusharg(*identmap[i], args[i+offset], argstack[i]); \ int oldargs = _numargs, newargs = numargs-offset; \ _numargs = newargs; \ int oldflags = identflags; \ identflags |= id->flags&IDF_OVERRIDDEN; \ identlink aliaslink = { id, aliasstack, (1<code) id->code = compilecode(id->getstr()); \ uint *code = id->code; \ code[0] += 0x100; \ runcode(code+1, result); \ code[0] -= 0x100; \ if(int(code[0]) < 0x100) delete[] code; \ aliasstack = aliaslink.next; \ identflags = oldflags; \ for(int i = 0; i < newargs; i++) \ poparg(*identmap[i]); \ for(int argmask = aliaslink.usedargs&(~0<>8]; if(id->flags&IDF_UNKNOWN) { debugcode("unknown command: %s", id->name); goto forceresult; } CALLALIAS(0); continue; case CODE_CALLARG|RET_NULL: case CODE_CALLARG|RET_STR: case CODE_CALLARG|RET_FLOAT: case CODE_CALLARG|RET_INT: forcenull(result); id = identmap[op>>8]; if(!(aliasstack->usedargs&(1<index))) goto forceresult; CALLALIAS(0); continue; case CODE_CALLU|RET_NULL: case CODE_CALLU|RET_STR: case CODE_CALLU|RET_FLOAT: case CODE_CALLU|RET_INT: if(args[0].type != VAL_STR) goto litval; id = idents.access(args[0].s); if(!id) { noid: if(checknumber(args[0].s)) goto litval; debugcode("unknown command: %s", args[0].s); forcenull(result); goto forceresult; } forcenull(result); switch(id->type) { case ID_COMMAND: freearg(args[0]); callcommand(id, args+1, numargs-1); forcearg(result, op&CODE_RET_MASK); numargs = 0; continue; case ID_LOCAL: { identstack locals[MAXARGS]; freearg(args[0]); loopj(numargs-1) pushalias(*forceident(args[j+1]), locals[j]); code = runcode(code, result); loopj(numargs-1) popalias(*args[j+1].id); goto exit; } case ID_VAR: if(numargs <= 1) printvar(id); else { int val = forceint(args[1]); if(id->flags&IDF_HEX && numargs > 2) { val = (val << 16) | (forceint(args[2])<<8); if(numargs > 3) val |= forceint(args[3]); } setvarchecked(id, val); } goto forceresult; case ID_FVAR: if(numargs <= 1) printvar(id); else setfvarchecked(id, forcefloat(args[1])); goto forceresult; case ID_SVAR: if(numargs <= 1) printvar(id); else setsvarchecked(id, forcestr(args[1])); goto forceresult; case ID_ALIAS: if(id->index < MAXARGS && !(aliasstack->usedargs&(1<index))) goto forceresult; if(id->valtype==VAL_NULL) goto noid; freearg(args[0]); CALLALIAS(1); continue; default: goto forceresult; } } } exit: commandret = prevret; --rundepth; return code; } void executeret(const uint *code, tagval &result) { runcode(code, result); } void executeret(const char *p, tagval &result) { vector code; code.reserve(64); compilemain(code, p, VAL_ANY); runcode(code.getbuf()+1, result); if(int(code[0]) >= 0x100) code.disown(); } char *executestr(const uint *code) { tagval result; runcode(code, result); if(result.type == VAL_NULL) return NULL; forcestr(result); return result.s; } char *executestr(const char *p) { tagval result; executeret(p, result); if(result.type == VAL_NULL) return NULL; forcestr(result); return result.s; } int execute(const uint *code) { tagval result; runcode(code, result); int i = result.getint(); freearg(result); return i; } int execute(const char *p) { vector code; code.reserve(64); compilemain(code, p, VAL_INT); tagval result; runcode(code.getbuf()+1, result); if(int(code[0]) >= 0x100) code.disown(); int i = result.getint(); freearg(result); return i; } static inline bool getbool(const char *s) { switch(s[0]) { case '+': case '-': switch(s[1]) { case '0': break; case '.': return !isdigit(s[2]) || parsefloat(s) != 0; default: return true; } // fall through case '0': { char *end; int val = strtol((char *)s, &end, 0); if(val) return true; switch(*end) { case 'e': case '.': return parsefloat(s) != 0; default: return false; } } case '.': return !isdigit(s[1]) || parsefloat(s) != 0; case '\0': return false; default: return true; } } static inline bool getbool(const tagval &v) { switch(v.type) { case VAL_FLOAT: return v.f!=0; case VAL_INT: return v.i!=0; case VAL_STR: case VAL_MACRO: return getbool(v.s); default: return false; } } bool executebool(const uint *code) { tagval result; runcode(code, result); bool b = getbool(result); freearg(result); return b; } bool executebool(const char *p) { tagval result; executeret(p, result); bool b = getbool(result); freearg(result); return b; } bool execfile(const char *cfgfile, bool msg) { string s; copystring(s, cfgfile); char *buf = loadfile(path(s), NULL); if(!buf) { if(msg) conoutf(CON_ERROR, "could not read \"%s\"", cfgfile); return false; } const char *oldsourcefile = sourcefile, *oldsourcestr = sourcestr; sourcefile = cfgfile; sourcestr = buf; execute(buf); sourcefile = oldsourcefile; sourcestr = oldsourcestr; delete[] buf; return true; } const char *escapestring(const char *s) { static vector strbuf[3]; static int stridx = 0; stridx = (stridx + 1)%3; vector &buf = strbuf[stridx]; buf.setsize(0); buf.add('"'); for(; *s; s++) switch(*s) { case '\n': buf.put("^n", 2); break; case '\t': buf.put("^t", 2); break; case '\f': buf.put("^f", 2); break; case '"': buf.put("^\"", 2); break; case '^': buf.put("^^", 2); break; default: buf.add(*s); break; } buf.put("\"\0", 2); return buf.getbuf(); } const char *escapeid(const char *s) { const char *end = s + strcspn(s, "\"/;()[]@ \f\t\r\n\0"); return *end ? escapestring(s) : s; } bool validateblock(const char *s) { const int maxbrak = 100; static char brakstack[maxbrak]; int brakdepth = 0; for(; *s; s++) switch(*s) { case '[': case '(': if(brakdepth >= maxbrak) return false; brakstack[brakdepth++] = *s; break; case ']': if(brakdepth <= 0 || brakstack[--brakdepth] != '[') return false; break; case ')': if(brakdepth <= 0 || brakstack[--brakdepth] != '(') return false; break; case '"': s = parsestring(s + 1); if(*s != '"') return false; break; case '/': if(s[1] == '/') return false; break; case '@': case '\f': return false; } return brakdepth == 0; } #ifndef STANDALONE static inline bool sortidents(ident *x, ident *y) { return strcmp(x->name, y->name) < 0; } void writecfg(const char *name) { stream *f = openutf8file(path(name && name[0] ? name : game::savedconfig(), true), "w"); if(!f) return; f->printf("// automatically written on exit, DO NOT MODIFY\n// delete this file to have %s overwrite these settings\n// modify settings in game, or put settings in %s to override anything\n\n", game::defaultconfig(), game::autoexec()); game::writeclientinfo(f); f->printf("\n"); writecrosshairs(f); vector ids; enumerate(idents, ident, id, ids.add(&id)); ids.sort(sortidents); loopv(ids) { ident &id = *ids[i]; if(id.flags&IDF_PERSIST) switch(id.type) { case ID_VAR: f->printf("%s %d\n", escapeid(id), *id.storage.i); break; case ID_FVAR: f->printf("%s %s\n", escapeid(id), floatstr(*id.storage.f)); break; case ID_SVAR: f->printf("%s %s\n", escapeid(id), escapestring(*id.storage.s)); break; } } f->printf("\n"); writebinds(f); f->printf("\n"); loopv(ids) { ident &id = *ids[i]; if(id.type==ID_ALIAS && id.flags&IDF_PERSIST && !(id.flags&IDF_OVERRIDDEN)) switch(id.valtype) { case VAL_STR: if(!id.val.s[0]) break; if(!validateblock(id.val.s)) { f->printf("%s = %s\n", escapeid(id), escapestring(id.val.s)); break; } case VAL_FLOAT: case VAL_INT: f->printf("%s = [%s]\n", escapeid(id), id.getstr()); break; } } f->printf("\n"); writecompletions(f); delete f; } COMMAND(writecfg, "s"); #endif // below the commands that implement a small imperative language. thanks to the semantics of // () and [] expressions, any control construct can be defined trivially. static string retbuf[3]; static int retidx = 0; const char *intstr(int v) { retidx = (retidx + 1)%3; formatstring(retbuf[retidx])("%d", v); return retbuf[retidx]; } void intret(int v) { commandret->setint(v); } const char *floatstr(float v) { retidx = (retidx + 1)%3; formatstring(retbuf[retidx])(v==int(v) ? "%.1f" : "%.7g", v); return retbuf[retidx]; } void floatret(float v) { commandret->setfloat(v); } #undef ICOMMANDNAME #define ICOMMANDNAME(name) _stdcmd ICOMMAND(do, "e", (uint *body), executeret(body, *commandret)); ICOMMAND(if, "tee", (tagval *cond, uint *t, uint *f), executeret(getbool(*cond) ? t : f, *commandret)); ICOMMAND(?, "ttt", (tagval *cond, tagval *t, tagval *f), result(*(getbool(*cond) ? t : f))); static inline void setiter(ident &id, int i, identstack &stack) { if(i) { if(id.valtype != VAL_INT) { if(id.valtype == VAL_STR) delete[] id.val.s; cleancode(id); id.valtype = VAL_INT; } id.val.i = i; } else { tagval zero; zero.setint(0); pusharg(id, zero, stack); id.flags &= ~IDF_UNKNOWN; } } ICOMMAND(loop, "rie", (ident *id, int *n, uint *body), { if(*n <= 0 || id->type!=ID_ALIAS) return; identstack stack; loopi(*n) { setiter(*id, i, stack); execute(body); } poparg(*id); }); ICOMMAND(loopwhile, "riee", (ident *id, int *n, uint *cond, uint *body), { if(*n <= 0 || id->type!=ID_ALIAS) return; identstack stack; loopi(*n) { setiter(*id, i, stack); if(!executebool(cond)) break; execute(body); } poparg(*id); }); ICOMMAND(while, "ee", (uint *cond, uint *body), while(executebool(cond)) execute(body)); char *loopconc(ident *id, int n, uint *body, bool space) { identstack stack; vector s; loopi(n) { setiter(*id, i, stack); tagval v; executeret(body, v); const char *vstr = v.getstr(); int len = strlen(vstr); if(space && i) s.add(' '); s.put(vstr, len); freearg(v); } poparg(*id); s.add('\0'); return newstring(s.getbuf(), s.length()-1); } ICOMMAND(loopconcat, "rie", (ident *id, int *n, uint *body), { if(*n > 0 && id->type==ID_ALIAS) commandret->setstr(loopconc(id, *n, body, true)); }); ICOMMAND(loopconcatword, "rie", (ident *id, int *n, uint *body), { if(*n > 0 && id->type==ID_ALIAS) commandret->setstr(loopconc(id, *n, body, false)); }); void concat(tagval *v, int n) { commandret->setstr(conc(v, n, true)); } void concatword(tagval *v, int n) { commandret->setstr(conc(v, n, false)); } void result(tagval &v) { *commandret = v; v.type = VAL_NULL; } void stringret(char *s) { commandret->setstr(s); } void result(const char *s) { commandret->setstr(newstring(s)); } void format(tagval *args, int numargs) { vector s; const char *f = args[0].getstr(); while(*f) { int c = *f++; if(c == '%') { int i = *f++; if(i >= '1' && i <= '9') { i -= '0'; const char *sub = i < numargs ? args[i].getstr() : ""; while(*sub) s.add(*sub++); } else s.add(i); } else s.add(c); } s.add('\0'); result(s.getbuf()); } static const char *liststart = NULL, *listend = NULL, *listquotestart = NULL, *listquoteend = NULL; static inline void skiplist(const char *&p) { for(;;) { p += strspn(p, " \t\r\n"); if(p[0]!='/' || p[1]!='/') break; p += strcspn(p, "\n\0"); } } static bool parselist(const char *&s, const char *&start = liststart, const char *&end = listend, const char *"estart = listquotestart, const char *"eend = listquoteend) { skiplist(s); switch(*s) { case '"': quotestart = s++; start = s; s = parsestring(s); end = s; if(*s == '"') s++; quoteend = s; break; case '(': case '[': quotestart = s; start = s+1; for(int braktype = *s++, brak = 1;;) { s += strcspn(s, "\"/;()[]\0"); int c = *s++; switch(c) { case '\0': s--; quoteend = end = s; return true; case '"': s = parsestring(s); if(*s == '"') s++; break; case '/': if(*s == '/') s += strcspn(s, "\n\0"); break; case '(': case '[': if(c == braktype) brak++; break; case ')': if(braktype == '(' && --brak <= 0) goto endblock; break; case ']': if(braktype == '[' && --brak <= 0) goto endblock; break; } } endblock: end = s-1; quoteend = s; break; case '\0': case ')': case ']': return false; default: quotestart = start = s; s = parseword(s); quoteend = end = s; break; } skiplist(s); if(*s == ';') s++; return true; } void explodelist(const char *s, vector &elems, int limit) { const char *start, *end; while((limit < 0 || elems.length() < limit) && parselist(s, start, end)) elems.add(newstring(start, end-start)); } char *indexlist(const char *s, int pos) { loopi(pos) if(!parselist(s)) return newstring(""); const char *start, *end; return parselist(s, start, end) ? newstring(start, end-start) : newstring(""); } int listlen(const char *s) { int n = 0; while(parselist(s)) n++; return n; } void at(tagval *args, int numargs) { if(!numargs) return; const char *start = args[0].getstr(), *end = start + strlen(start); for(int i = 1; i < numargs; i++) { const char *list = start; int pos = args[i].getint(); for(; pos > 0; pos--) if(!parselist(list)) break; if(pos > 0 || !parselist(list, start, end)) start = end = ""; } commandret->setstr(newstring(start, end-start)); } void substr(char *s, int *start, int *count, int *numargs) { int len = strlen(s), offset = clamp(*start, 0, len); commandret->setstr(newstring(&s[offset], *numargs >= 3 ? clamp(*count, 0, len - offset) : len - offset)); } void sublist(const char *s, int *skip, int *count, int *numargs) { int offset = max(*skip, 0), len = *numargs >= 3 ? max(*count, 0) : -1; loopi(offset) if(!parselist(s)) break; if(len < 0) { if(offset > 0) skiplist(s); commandret->setstr(newstring(s)); return; } const char *list = s, *start, *end, *qstart, *qend = s; if(len > 0 && parselist(s, start, end, list, qend)) while(--len > 0 && parselist(s, start, end, qstart, qend)); commandret->setstr(newstring(list, qend - list)); } void getalias_(char *s) { result(getalias(s)); } ICOMMAND(exec, "s", (char *file), execfile(file)); ICOMMAND(result, "t", (tagval *v), { *commandret = *v; v->type = VAL_NULL; }); COMMAND(concat, "V"); COMMAND(concatword, "V"); COMMAND(format, "V"); COMMAND(at, "si1V"); ICOMMAND(escape, "s", (char *s), result(escapestring(s))); ICOMMAND(unescape, "s", (char *s), { int len = strlen(s); char *d = newstring(len); d[unescapestring(d, s, &s[len])] = '\0'; stringret(d); }); ICOMMAND(stripcolors, "s", (char *s), { int len = strlen(s); char *d = newstring(len); filtertext(d, s, true, len); stringret(d); }); COMMAND(substr, "siiN"); COMMAND(sublist, "siiN"); ICOMMAND(listlen, "s", (char *s), intret(listlen(s))); COMMANDN(getalias, getalias_, "s"); ICOMMAND(getvarmin, "s", (char *s), intret(getvarmin(s))); ICOMMAND(getvarmax, "s", (char *s), intret(getvarmax(s))); ICOMMAND(getfvarmin, "s", (char *s), floatret(getfvarmin(s))); ICOMMAND(getfvarmax, "s", (char *s), floatret(getfvarmax(s))); void looplist(ident *id, const char *list, const uint *body, bool search) { if(id->type!=ID_ALIAS) { if(search) intret(-1); return; } identstack stack; int n = 0; for(const char *s = list, *start, *end; parselist(s, start, end);) { char *val = newstring(start, end-start); if(n++) { if(id->valtype == VAL_STR) delete[] id->val.s; else id->valtype = VAL_STR; cleancode(*id); id->val.s = val; } else { tagval t; t.setstr(val); pusharg(*id, t, stack); id->flags &= ~IDF_UNKNOWN; } if(executebool(body) && search) { intret(n-1); search = false; break; } } if(search) intret(-1); if(n) poparg(*id); } void prettylist(const char *s, const char *conj) { vector p; const char *start, *end; for(int len = listlen(s), n = 0; parselist(s, start, end); n++) { p.put(start, end - start); if(n+1 < len) { if(len > 2 || !conj[0]) p.add(','); if(n+2 == len && conj[0]) { p.add(' '); p.put(conj, strlen(conj)); } p.add(' '); } } p.add('\0'); result(p.getbuf()); } COMMAND(prettylist, "ss"); int listincludes(const char *list, const char *needle, int needlelen) { int offset = 0; for(const char *s = list, *start, *end; parselist(s, start, end);) { int len = end - start; if(needlelen == len && !strncmp(needle, start, len)) return offset; offset++; } return -1; } char *listdel(const char *s, const char *del) { vector p; for(const char *start, *end, *qstart, *qend; parselist(s, start, end, qstart, qend);) { if(listincludes(del, start, end-start) < 0) { if(!p.empty()) p.add(' '); p.put(qstart, qend-qstart); } } p.add('\0'); return newstring(p.getbuf(), p.length()-1); } void listsplice(const char *s, const char *vals, int *skip, int *count, int *numargs) { int offset = max(*skip, 0), len = *numargs >= 4 ? max(*count, 0) : -1; const char *list = s, *start, *end, *qstart, *qend = s; loopi(offset) if(!parselist(s, start, end, qstart, qend)) break; vector p; if(qend > list) p.put(list, qend-list); if(*vals) { if(!p.empty()) p.add(' '); p.put(vals, strlen(vals)); } while(len-- > 0) if(!parselist(s)) break; skiplist(s); switch(*s) { case '\0': case ')': case ']': break; default: if(!p.empty()) p.add(' '); p.put(s, strlen(s)); break; } p.add('\0'); commandret->setstr(newstring(p.getbuf(), p.length()-1)); } COMMAND(listsplice, "ssiiN"); ICOMMAND(listdel, "ss", (char *list, char *del), commandret->setstr(listdel(list, del))); ICOMMAND(indexof, "ss", (char *list, char *elem), intret(listincludes(list, elem, strlen(elem)))); ICOMMAND(listfind, "rse", (ident *id, char *list, uint *body), looplist(id, list, body, true)); ICOMMAND(looplist, "rse", (ident *id, char *list, uint *body), looplist(id, list, body, false)); ICOMMAND(loopfiles, "rsse", (ident *id, char *dir, char *ext, uint *body), { if(id->type!=ID_ALIAS) return; identstack stack; vector files; listfiles(dir, ext[0] ? ext : NULL, files); loopv(files) { char *file = files[i]; bool redundant = false; loopj(i) if(!strcmp(files[j], file)) { redundant = true; break; } if(redundant) { delete[] file; continue; } if(i) { if(id->valtype == VAL_STR) delete[] id->val.s; else id->valtype = VAL_STR; id->val.s = file; } else { tagval t; t.setstr(file); pusharg(*id, t, stack); id->flags &= ~IDF_UNKNOWN; } execute(body); } if(files.length()) poparg(*id); }); struct sortitem { const char *str, *quotestart, *quoteend; }; struct sortfun { ident *x, *y; uint *body; bool operator()(const sortitem &xval, const sortitem &yval) { if(x->valtype != VAL_MACRO) x->valtype = VAL_MACRO; cleancode(*x); x->val.code = (const uint *)xval.str; if(y->valtype != VAL_MACRO) y->valtype = VAL_MACRO; cleancode(*y); y->val.code = (const uint *)yval.str; return executebool(body); } }; void sortlist(char *list, ident *x, ident *y, uint *body) { if(x == y || x->type != ID_ALIAS || y->type != ID_ALIAS) return; vector items; int macrolen = strlen(list), total = 0; char *macros = newstring(list, macrolen); const char *curlist = list, *start, *end, *quotestart, *quoteend; while(parselist(curlist, start, end, quotestart, quoteend)) { macros[end - list] = '\0'; sortitem item = { ¯os[start - list], quotestart, quoteend }; items.add(item); total += int(quoteend - quotestart); } identstack xstack, ystack; pusharg(*x, nullval, xstack); x->flags &= ~IDF_UNKNOWN; pusharg(*y, nullval, ystack); y->flags &= ~IDF_UNKNOWN; sortfun f = { x, y, body }; items.sort(f); poparg(*x); poparg(*y); char *sorted = macros; int sortedlen = total + max(items.length() - 1, 0); if(macrolen < sortedlen) { delete[] macros; sorted = newstring(sortedlen); } int offset = 0; loopv(items) { sortitem &item = items[i]; int len = int(item.quoteend - item.quotestart); if(i) sorted[offset++] = ' '; memcpy(&sorted[offset], item.quotestart, len); offset += len; } sorted[offset] = '\0'; commandret->setstr(sorted); } COMMAND(sortlist, "srre"); ICOMMAND(+, "ii", (int *a, int *b), intret(*a + *b)); ICOMMAND(*, "ii", (int *a, int *b), intret(*a * *b)); ICOMMAND(-, "ii", (int *a, int *b), intret(*a - *b)); ICOMMAND(+f, "ff", (float *a, float *b), floatret(*a + *b)); ICOMMAND(*f, "ff", (float *a, float *b), floatret(*a * *b)); ICOMMAND(-f, "ff", (float *a, float *b), floatret(*a - *b)); ICOMMAND(=, "ii", (int *a, int *b), intret((int)(*a == *b))); ICOMMAND(!=, "ii", (int *a, int *b), intret((int)(*a != *b))); ICOMMAND(<, "ii", (int *a, int *b), intret((int)(*a < *b))); ICOMMAND(>, "ii", (int *a, int *b), intret((int)(*a > *b))); ICOMMAND(<=, "ii", (int *a, int *b), intret((int)(*a <= *b))); ICOMMAND(>=, "ii", (int *a, int *b), intret((int)(*a >= *b))); ICOMMAND(=f, "ff", (float *a, float *b), intret((int)(*a == *b))); ICOMMAND(!=f, "ff", (float *a, float *b), intret((int)(*a != *b))); ICOMMAND(f, "ff", (float *a, float *b), intret((int)(*a > *b))); ICOMMAND(<=f, "ff", (float *a, float *b), intret((int)(*a <= *b))); ICOMMAND(>=f, "ff", (float *a, float *b), intret((int)(*a >= *b))); ICOMMAND(^, "ii", (int *a, int *b), intret(*a ^ *b)); ICOMMAND(!, "t", (tagval *a), intret(!getbool(*a))); ICOMMAND(&, "ii", (int *a, int *b), intret(*a & *b)); ICOMMAND(|, "ii", (int *a, int *b), intret(*a | *b)); ICOMMAND(~, "i", (int *a), intret(~*a)); ICOMMAND(^~, "ii", (int *a, int *b), intret(*a ^ ~*b)); ICOMMAND(&~, "ii", (int *a, int *b), intret(*a & ~*b)); ICOMMAND(|~, "ii", (int *a, int *b), intret(*a | ~*b)); ICOMMAND(<<, "ii", (int *a, int *b), intret(*a << *b)); ICOMMAND(>>, "ii", (int *a, int *b), intret(*a >> *b)); ICOMMAND(&&, "e1V", (tagval *args, int numargs), { if(!numargs) intret(1); else loopi(numargs) { if(i) freearg(*commandret); executeret(args[i].code, *commandret); if(!getbool(*commandret)) break; } }); ICOMMAND(||, "e1V", (tagval *args, int numargs), { if(!numargs) intret(0); else loopi(numargs) { if(i) freearg(*commandret); executeret(args[i].code, *commandret); if(getbool(*commandret)) break; } }); ICOMMAND(div, "ii", (int *a, int *b), intret(*b ? *a / *b : 0)); ICOMMAND(mod, "ii", (int *a, int *b), intret(*b ? *a % *b : 0)); ICOMMAND(divf, "ff", (float *a, float *b), floatret(*b ? *a / *b : 0)); ICOMMAND(modf, "ff", (float *a, float *b), floatret(*b ? fmod(*a, *b) : 0)); ICOMMAND(sin, "f", (float *a), floatret(sin(*a*RAD))); ICOMMAND(cos, "f", (float *a), floatret(cos(*a*RAD))); ICOMMAND(tan, "f", (float *a), floatret(tan(*a*RAD))); ICOMMAND(asin, "f", (float *a), floatret(asin(*a)/RAD)); ICOMMAND(acos, "f", (float *a), floatret(acos(*a)/RAD)); ICOMMAND(atan, "f", (float *a), floatret(atan(*a)/RAD)); ICOMMAND(sqrt, "f", (float *a), floatret(sqrt(*a))); ICOMMAND(pow, "ff", (float *a, float *b), floatret(pow(*a, *b))); ICOMMAND(loge, "f", (float *a), floatret(log(*a))); ICOMMAND(log2, "f", (float *a), floatret(log(*a)/M_LN2)); ICOMMAND(log10, "f", (float *a), floatret(log10(*a))); ICOMMAND(exp, "f", (float *a), floatret(exp(*a))); ICOMMAND(min, "V", (tagval *args, int numargs), { int val = numargs > 0 ? args[numargs - 1].getint() : 0; loopi(numargs - 1) val = min(val, args[i].getint()); intret(val); }); ICOMMAND(max, "V", (tagval *args, int numargs), { int val = numargs > 0 ? args[numargs - 1].getint() : 0; loopi(numargs - 1) val = max(val, args[i].getint()); intret(val); }); ICOMMAND(minf, "V", (tagval *args, int numargs), { float val = numargs > 0 ? args[numargs - 1].getfloat() : 0.0f; loopi(numargs - 1) val = min(val, args[i].getfloat()); floatret(val); }); ICOMMAND(maxf, "V", (tagval *args, int numargs), { float val = numargs > 0 ? args[numargs - 1].getfloat() : 0.0f; loopi(numargs - 1) val = max(val, args[i].getfloat()); floatret(val); }); ICOMMAND(abs, "i", (int *n), intret(abs(*n))); ICOMMAND(absf, "f", (float *n), floatret(fabs(*n))); ICOMMAND(cond, "ee2V", (tagval *args, int numargs), { for(int i = 0; i < numargs; i += 2) { if(i+1 < numargs) { if(executebool(args[i].code)) { executeret(args[i+1].code, *commandret); break; } } else { executeret(args[i].code, *commandret); break; } } }); #define CASECOMMAND(name, fmt, type, acc, compare) \ ICOMMAND(name, fmt "te2V", (tagval *args, int numargs), \ { \ type val = acc; \ int i; \ for(i = 1; i+1 < numargs; i += 2) \ { \ if(compare) \ { \ executeret(args[i+1].code, *commandret); \ return; \ } \ } \ }) CASECOMMAND(case, "i", int, args[0].getint(), args[i].type == VAL_NULL || args[i].getint() == val); CASECOMMAND(casef, "f", float, args[0].getfloat(), args[i].type == VAL_NULL || args[i].getfloat() == val); CASECOMMAND(cases, "s", const char *, args[0].getstr(), args[i].type == VAL_NULL || !strcmp(args[i].getstr(), val)); ICOMMAND(rnd, "ii", (int *a, int *b), intret(*a - *b > 0 ? rnd(*a - *b) + *b : *b)); ICOMMAND(strcmp, "ss", (char *a, char *b), intret(strcmp(a,b)==0)); ICOMMAND(=s, "ss", (char *a, char *b), intret(strcmp(a,b)==0)); ICOMMAND(!=s, "ss", (char *a, char *b), intret(strcmp(a,b)!=0)); ICOMMAND(s, "ss", (char *a, char *b), intret(strcmp(a,b)>0)); ICOMMAND(<=s, "ss", (char *a, char *b), intret(strcmp(a,b)<=0)); ICOMMAND(>=s, "ss", (char *a, char *b), intret(strcmp(a,b)>=0)); ICOMMAND(echo, "C", (char *s), conoutf("\f1%s", s)); ICOMMAND(error, "C", (char *s), conoutf(CON_ERROR, "%s", s)); ICOMMAND(strstr, "ss", (char *a, char *b), { char *s = strstr(a, b); intret(s ? s-a : -1); }); ICOMMAND(strlen, "s", (char *s), intret(strlen(s))); char *strreplace(const char *s, const char *oldval, const char *newval) { vector buf; int oldlen = strlen(oldval); if(!oldlen) return newstring(s); for(;;) { const char *found = strstr(s, oldval); if(found) { while(s < found) buf.add(*s++); for(const char *n = newval; *n; n++) buf.add(*n); s = found + oldlen; } else { while(*s) buf.add(*s++); buf.add('\0'); return newstring(buf.getbuf(), buf.length()); } } } ICOMMAND(strreplace, "sss", (char *s, char *o, char *n), commandret->setstr(strreplace(s, o, n))); #ifndef STANDALONE ICOMMAND(getmillis, "i", (int *total), intret(*total ? totalmillis : lastmillis)); struct sleepcmd { int delay, millis, flags; char *command; }; vector sleepcmds; void addsleep(int *msec, char *cmd) { sleepcmd &s = sleepcmds.add(); s.delay = max(*msec, 1); s.millis = lastmillis; s.command = newstring(cmd); s.flags = identflags; } COMMANDN(sleep, addsleep, "is"); void checksleep(int millis) { loopv(sleepcmds) { sleepcmd &s = sleepcmds[i]; if(millis - s.millis >= s.delay) { char *cmd = s.command; // execute might create more sleep commands s.command = NULL; int oldflags = identflags; identflags = s.flags; execute(cmd); identflags = oldflags; delete[] cmd; if(sleepcmds.inrange(i) && !sleepcmds[i].command) sleepcmds.remove(i--); } } } void clearsleep(bool clearoverrides) { int len = 0; loopv(sleepcmds) if(sleepcmds[i].command) { if(clearoverrides && !(sleepcmds[i].flags&IDF_OVERRIDDEN)) sleepcmds[len++] = sleepcmds[i]; else delete[] sleepcmds[i].command; } sleepcmds.shrink(len); } void clearsleep_(int *clearoverrides) { clearsleep(*clearoverrides!=0 || identflags&IDF_OVERRIDDEN); } COMMANDN(clearsleep, clearsleep_, "i"); #endif sauerbraten-0.0.20130203.dfsg/engine/octa.h0000644000175000017500000002421612062503331017741 0ustar vincentvincent// 6-directional octree heightfield map format struct elementset { ushort texture, lmid, envmap; uchar dim, layer; ushort length[2], minvert[2], maxvert[2]; }; enum { EMID_NONE = 0, EMID_CUSTOM, EMID_SKY, EMID_RESERVED }; struct materialsurface { enum { F_EDIT = 1<<0 }; ivec o; ushort csize, rsize; ushort material, skip; uchar orient, flags; union { short index; short depth; }; union { entity *light; ushort envmap; uchar ends; }; }; struct vertinfo { ushort x, y, z, u, v, norm; void setxyz(ushort a, ushort b, ushort c) { x = a; y = b; z = c; } void setxyz(const ivec &v) { setxyz(v.x, v.y, v.z); } void set(ushort a, ushort b, ushort c, ushort s = 0, ushort t = 0, ushort n = 0) { setxyz(a, b, c); u = s; v = t; norm = n; } void set(const ivec &v, ushort s = 0, ushort t = 0, ushort n = 0) { set(v.x, v.y, v.z, s, t, n); } ivec getxyz() const { return ivec(x, y, z); } }; enum { LAYER_TOP = (1<<5), LAYER_BOTTOM = (1<<6), LAYER_DUP = (1<<7), LAYER_BLEND = LAYER_TOP|LAYER_BOTTOM, MAXFACEVERTS = 15 }; enum { LMID_AMBIENT = 0, LMID_AMBIENT1, LMID_BRIGHT, LMID_BRIGHT1, LMID_DARK, LMID_DARK1, LMID_RESERVED }; struct surfaceinfo { uchar lmid[2]; uchar verts, numverts; int totalverts() const { return numverts&LAYER_DUP ? (numverts&MAXFACEVERTS)*2 : numverts&MAXFACEVERTS; } bool used() const { return lmid[0] != LMID_AMBIENT || lmid[1] != LMID_AMBIENT || numverts&~LAYER_TOP; } void clear() { lmid[0] = LMID_AMBIENT; lmid[1] = LMID_AMBIENT; numverts = (numverts&MAXFACEVERTS) | LAYER_TOP; } void brighten() { lmid[0] = LMID_BRIGHT; lmid[1] = LMID_AMBIENT; numverts = (numverts&MAXFACEVERTS) | LAYER_TOP; } }; static const surfaceinfo ambientsurface = {{LMID_AMBIENT, LMID_AMBIENT}, 0, LAYER_TOP}; static const surfaceinfo brightsurface = {{LMID_BRIGHT, LMID_AMBIENT}, 0, LAYER_TOP}; static const surfaceinfo brightbottomsurface = {{LMID_AMBIENT, LMID_BRIGHT}, 0, LAYER_BOTTOM}; struct grasstri { vec v[4]; int numv; vec4 tcu, tcv; plane surface; vec center; float radius; float minz, maxz; ushort texture, lmid; }; struct occludequery { void *owner; GLuint id; int fragments; }; struct vtxarray; struct octaentities { vector mapmodels; vector other; occludequery *query; octaentities *next, *rnext; int distance; ivec o; int size; ivec bbmin, bbmax; octaentities(const ivec &o, int size) : query(0), o(o), size(size), bbmin(o), bbmax(o) { bbmin.add(size); } }; enum { OCCLUDE_NOTHING = 0, OCCLUDE_GEOM, OCCLUDE_BB, OCCLUDE_PARENT }; enum { MERGE_ORIGIN = 1<<0, MERGE_PART = 1<<1, MERGE_USE = 1<<2 }; struct vtxarray { vtxarray *parent; vector children; vtxarray *next, *rnext; // linked list of visible VOBs vertex *vdata; // vertex data ushort voffset; // offset into vertex data ushort *edata, *skydata; // vertex indices GLuint vbuf, ebuf, skybuf; // VBOs ushort minvert, maxvert; // DRE info elementset *eslist; // List of element indices sets (range) per texture materialsurface *matbuf; // buffer of material surfaces int verts, tris, texs, blendtris, blends, alphabacktris, alphaback, alphafronttris, alphafront, texmask, sky, explicitsky, skyfaces, skyclip, matsurfs, distance; double skyarea; ivec o; int size; // location and size of cube. ivec geommin, geommax; // BB of geom ivec shadowmapmin, shadowmapmax; // BB of shadowmapped surfaces ivec matmin, matmax; // BB of any materials ivec bbmin, bbmax; // BB of everything including children uchar curvfc, occluded; occludequery *query; vector mapmodels; vector grasstris; int hasmerges, mergelevel; uint dynlightmask; bool shadowed; }; struct cube; struct clipplanes { vec o, r, v[8]; plane p[12]; uchar side[12]; uchar size, visible; const cube *owner; int version; }; struct facebounds { ushort u1, u2, v1, v2; bool empty() const { return u1 >= u2 || v1 >= v2; } }; struct tjoint { int next; ushort offset; uchar edge; }; struct cubeext { vtxarray *va; // vertex array for children, or NULL octaentities *ents; // map entities inside cube surfaceinfo surfaces[6]; // render info for each surface int tjoints; // linked list of t-joints uchar maxverts; // allocated space for verts vertinfo *verts() { return (vertinfo *)(this+1); } }; struct cube { cube *children; // points to 8 cube structures which are its children, or NULL. -Z first, then -Y, -X cubeext *ext; // extended info for the cube union { uchar edges[12]; // edges of the cube, each uchar is 2 4bit values denoting the range. // see documentation jpgs for more info. uint faces[3]; // 4 edges of each dimension together representing 2 perpendicular faces }; ushort texture[6]; // one for each face. same order as orient. ushort material; // empty-space material uchar merged; // merged faces of the cube union { uchar escaped; // mask of which children have escaped merges uchar visible; // visibility info for faces }; }; struct block3 { ivec o, s; int grid, orient; block3() {} block3(const selinfo &sel) : o(sel.o), s(sel.s), grid(sel.grid), orient(sel.orient) {} cube *c() { return (cube *)(this+1); } int size() const { return s.x*s.y*s.z; } }; struct editinfo { block3 *copy; editinfo() : copy(NULL) {} }; struct undoent { int i; entity e; }; struct undoblock // undo header, all data sits in payload { undoblock *prev, *next; int size, timestamp, numents; // if numents is 0, is a cube undo record, otherwise an entity undo record block3 *block() { return (block3 *)(this + 1); } int *gridmap() { block3 *ub = block(); return (int *)(ub->c() + ub->size()); } undoent *ents() { return (undoent *)(this + 1); } }; extern cube *worldroot; // the world data. only a ptr to 8 cubes (ie: like cube.children above) extern int wtris, wverts, vtris, vverts, glde, gbatches, rplanes; extern int allocnodes, allocva, selchildcount, selchildmat; const uint F_EMPTY = 0; // all edges in the range (0,0) const uint F_SOLID = 0x80808080; // all edges in the range (0,8) #define isempty(c) ((c).faces[0]==F_EMPTY) #define isentirelysolid(c) ((c).faces[0]==F_SOLID && (c).faces[1]==F_SOLID && (c).faces[2]==F_SOLID) #define setfaces(c, face) { (c).faces[0] = (c).faces[1] = (c).faces[2] = face; } #define solidfaces(c) setfaces(c, F_SOLID) #define emptyfaces(c) setfaces(c, F_EMPTY) #define edgemake(a, b) ((b)<<4|a) #define edgeget(edge, coord) ((coord) ? (edge)>>4 : (edge)&0xF) #define edgeset(edge, coord, val) ((edge) = ((coord) ? ((edge)&0xF)|((val)<<4) : ((edge)&0xF0)|(val))) #define cubeedge(c, d, x, y) ((c).edges[(((d)<<2)+((y)<<1)+(x))]) #define octadim(d) (1<<(d)) // creates mask for bit of given dimension #define octacoord(d, i) (((i)&octadim(d))>>(d)) #define oppositeocta(d, i) ((i)^octadim(D[d])) #define octaindex(d,x,y,z) (((z)<>(scale))&1)<<2) | ((((y)>>(scale))&1)<<1) | (((x)>>(scale))&1)) #define loopoctabox(c, size, o, s) uchar possible = octantrectangleoverlap(c, size, o, s); loopi(8) if(possible&(1<>1) #define dimcoord(orient) ((orient)&1) #define opposite(orient) ((orient)^1) enum { VFC_FULL_VISIBLE = 0, VFC_PART_VISIBLE, VFC_FOGGED, VFC_NOT_VISIBLE, PVS_FULL_VISIBLE, PVS_PART_VISIBLE, PVS_FOGGED }; #define GENCUBEVERTS(x0,x1, y0,y1, z0,z1) \ GENCUBEVERT(0, x1, y1, z0) \ GENCUBEVERT(1, x0, y1, z0) \ GENCUBEVERT(2, x0, y1, z1) \ GENCUBEVERT(3, x1, y1, z1) \ GENCUBEVERT(4, x1, y0, z1) \ GENCUBEVERT(5, x0, y0, z1) \ GENCUBEVERT(6, x0, y0, z0) \ GENCUBEVERT(7, x1, y0, z0) #define GENFACEVERTX(o,n, x,y,z, xv,yv,zv) GENFACEVERT(o,n, x,y,z, xv,yv,zv) #define GENFACEVERTSX(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEORIENT(0, GENFACEVERTX(0,0, x0,y1,z1, d0,r1,c1), GENFACEVERTX(0,1, x0,y1,z0, d0,r1,c0), GENFACEVERTX(0,2, x0,y0,z0, d0,r0,c0), GENFACEVERTX(0,3, x0,y0,z1, d0,r0,c1)) \ GENFACEORIENT(1, GENFACEVERTX(1,0, x1,y1,z1, d1,r1,c1), GENFACEVERTX(1,1, x1,y0,z1, d1,r0,c1), GENFACEVERTX(1,2, x1,y0,z0, d1,r0,c0), GENFACEVERTX(1,3, x1,y1,z0, d1,r1,c0)) #define GENFACEVERTY(o,n, x,y,z, xv,yv,zv) GENFACEVERT(o,n, x,y,z, xv,yv,zv) #define GENFACEVERTSY(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEORIENT(2, GENFACEVERTY(2,0, x1,y0,z1, c1,d0,r1), GENFACEVERTY(2,1, x0,y0,z1, c0,d0,r1), GENFACEVERTY(2,2, x0,y0,z0, c0,d0,r0), GENFACEVERTY(2,3, x1,y0,z0, c1,d0,r0)) \ GENFACEORIENT(3, GENFACEVERTY(3,0, x0,y1,z0, c0,d1,r0), GENFACEVERTY(3,1, x0,y1,z1, c0,d1,r1), GENFACEVERTY(3,2, x1,y1,z1, c1,d1,r1), GENFACEVERTY(3,3, x1,y1,z0, c1,d1,r0)) #define GENFACEVERTZ(o,n, x,y,z, xv,yv,zv) GENFACEVERT(o,n, x,y,z, xv,yv,zv) #define GENFACEVERTSZ(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEORIENT(4, GENFACEVERTZ(4,0, x0,y0,z0, r0,c0,d0), GENFACEVERTZ(4,1, x0,y1,z0, r0,c1,d0), GENFACEVERTZ(4,2, x1,y1,z0, r1,c1,d0), GENFACEVERTZ(4,3, x1,y0,z0, r1,c0,d0)) \ GENFACEORIENT(5, GENFACEVERTZ(5,0, x0,y0,z1, r0,c0,d1), GENFACEVERTZ(5,1, x1,y0,z1, r1,c0,d1), GENFACEVERTZ(5,2, x1,y1,z1, r1,c1,d1), GENFACEVERTZ(5,3, x0,y1,z1, r0,c1,d1)) #define GENFACEVERTSXY(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEVERTSX(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEVERTSY(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) #define GENFACEVERTS(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEVERTSXY(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) \ GENFACEVERTSZ(x0,x1, y0,y1, z0,z1, c0,c1, r0,r1, d0,d1) sauerbraten-0.0.20130203.dfsg/engine/scale.h0000644000175000017500000001042611651374342020113 0ustar vincentvincentstatic void FUNCNAME(halvetexture)(uchar *src, uint sw, uint sh, uint stride, uchar *dst) { for(uchar *yend = &src[sh*stride]; src < yend;) { for(uchar *xend = &src[stride]; src < xend; src += 2*BPP, dst += BPP) { #define OP(c, n) dst[n] = (uint(src[n]) + uint(src[n+BPP]) + uint(src[stride+n]) + uint(src[stride+n+BPP]))>>2 PIXELOP #undef OP } src += stride; } } static void FUNCNAME(shifttexture)(uchar *src, uint sw, uint sh, uint stride, uchar *dst, uint dw, uint dh) { uint wfrac = sw/dw, hfrac = sh/dh, wshift = 0, hshift = 0; while(dw<>tshift PIXELOP #undef OP } src += (hfrac-1)*stride; } } static void FUNCNAME(scaletexture)(uchar *src, uint sw, uint sh, uint stride, uchar *dst, uint dw, uint dh) { uint wfrac = (sw<<12)/dw, hfrac = (sh<<12)/dh, darea = dw*dh, sarea = sw*sh; int over, under; for(over = 0; (darea>>over) > sarea; over++); for(under = 0; (darea<>12, h = (yn>>12) - yi, ylow = ((yn|(-int(h)>>24))&0xFFFU) + 1 - (y&0xFFFU), yhigh = (yn&0xFFFU) + 1; const uchar *ysrc = &src[yi*stride]; for(uint x = 0; x < dw; x += wfrac, dst += BPP) { const uint xn = x + wfrac - 1, xi = x>>12, w = (xn>>12) - xi, xlow = ((w+0xFFFU)&0x1000U) - (x&0xFFFU), xhigh = (xn&0xFFFU) + 1; const uchar *xsrc = &ysrc[xi*BPP], *xend = &xsrc[w*BPP]; #define OP(c, n) c##t = 0 DEFPIXEL #undef OP for(const uchar *xcur = &xsrc[BPP]; xcur < xend; xcur += BPP) { #define OP(c, n) c##t += xcur[n] PIXELOP #undef OP } #define OP(c, n) c##t = (ylow*(c##t + ((xsrc[n]*xlow + xend[n]*xhigh)>>12)))>>cscale PIXELOP #undef OP if(h) { xsrc += stride; xend += stride; for(uint hcur = h; --hcur; xsrc += stride, xend += stride) { #define OP(c, n) c = 0 DEFPIXEL #undef OP for(const uchar *xcur = &xsrc[BPP]; xcur < xend; xcur += BPP) { #define OP(c, n) c += xcur[n] PIXELOP #undef OP } #define OP(c, n) c##t += ((c<<12) + xsrc[n]*xlow + xend[n]*xhigh)>>cscale; PIXELOP #undef OP } #define OP(c, n) c = 0 DEFPIXEL #undef OP for(const uchar *xcur = &xsrc[BPP]; xcur < xend; xcur += BPP) { #define OP(c, n) c += xcur[n] PIXELOP #undef OP } #define OP(c, n) c##t += (yhigh*(c + ((xsrc[n]*xlow + xend[n]*xhigh)>>12)))>>cscale PIXELOP #undef OP } #define OP(c, n) dst[n] = (c##t * area)>>dscale PIXELOP #undef OP } } } #undef FUNCNAME #undef DEFPIXEL #undef PIXELOP #undef BPP sauerbraten-0.0.20130203.dfsg/engine/varray.h0000644000175000017500000001626012057647522020336 0ustar vincentvincentnamespace varray { #ifndef VARRAY_INTERNAL enum { ATTRIB_VERTEX = 1<<0, ATTRIB_COLOR = 1<<1, ATTRIB_NORMAL = 1<<2, ATTRIB_TEXCOORD0 = 1<<3, ATTRIB_TEXCOORD1 = 1<<4, MAXATTRIBS = 5 }; extern vector data; extern void enable(); extern void begin(GLenum mode); extern void defattrib(int type, int size, GLenum format); template static inline void attrib(T x) { T *buf = (T *)data.pad(sizeof(T)); buf[0] = x; } template static inline void attrib(T x, T y) { T *buf = (T *)data.pad(2*sizeof(T)); buf[0] = x; buf[1] = y; } template static inline void attrib(T x, T y, T z) { T *buf = (T *)data.pad(3*sizeof(T)); buf[0] = x; buf[1] = y; buf[2] = z; } template static inline void attrib(T x, T y, T z, T w) { T *buf = (T *)data.pad(4*sizeof(T)); buf[0] = x; buf[1] = y; buf[2] = z; buf[3] = w; } template static inline void attribv(const T *v) { data.put((const uchar *)v, N*sizeof(T)); } extern int end(); extern void disable(); #else struct attribinfo { int type, size, formatsize, offset; GLenum format; attribinfo() : type(0), size(0), formatsize(0), offset(0), format(GL_FALSE) {} bool operator==(const attribinfo &a) const { return type == a.type && size == a.size && format == a.format && offset == a.offset; } bool operator!=(const attribinfo &a) const { return type != a.type || size != a.size || format != a.format || offset != a.offset; } }; vector data; static attribinfo attribs[MAXATTRIBS], lastattribs[MAXATTRIBS]; static int enabled = 0, numattribs = 0, attribmask = 0, numlastattribs = 0, lastattribmask = 0, vertexsize = 0, lastvertexsize = 0; static GLenum primtype = GL_TRIANGLES; static uchar *lastbuf = NULL; static bool changedattribs = false; void enable() { enabled = 0; numlastattribs = lastattribmask = lastvertexsize = 0; lastbuf = NULL; } void begin(GLenum mode) { primtype = mode; } void defattrib(int type, int size, GLenum format) { if(type == ATTRIB_VERTEX) { numattribs = attribmask = 0; vertexsize = 0; } changedattribs = true; attribmask |= type; attribinfo &a = attribs[numattribs++]; a.type = type; a.size = size; a.format = format; switch(format) { case GL_UNSIGNED_BYTE: a.formatsize = 1; break; case GL_BYTE: a.formatsize = 1; break; case GL_UNSIGNED_SHORT: a.formatsize = 2; break; case GL_SHORT: a.formatsize = 2; break; case GL_UNSIGNED_INT: a.formatsize = 4; break; case GL_INT: a.formatsize = 4; break; case GL_FLOAT: a.formatsize = 4; break; case GL_DOUBLE: a.formatsize = 8; break; default: a.formatsize = 0; break; } a.formatsize *= size; a.offset = vertexsize; vertexsize += a.formatsize; } static inline void setattrib(const attribinfo &a, uchar *buf) { switch(a.type) { case ATTRIB_VERTEX: if(!(enabled&a.type)) glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(a.size, a.format, vertexsize, buf); break; case ATTRIB_COLOR: if(!(enabled&a.type)) glEnableClientState(GL_COLOR_ARRAY); glColorPointer(a.size, a.format, vertexsize, buf); break; case ATTRIB_NORMAL: if(!(enabled&a.type)) glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(a.format, vertexsize, buf); break; case ATTRIB_TEXCOORD0: if(!(enabled&a.type)) glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(a.size, a.format, vertexsize, buf); break; case ATTRIB_TEXCOORD1: glClientActiveTexture_(GL_TEXTURE1_ARB); if(!(enabled&a.type)) glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(a.size, a.format, vertexsize, buf); glClientActiveTexture_(GL_TEXTURE0_ARB); break; } enabled |= a.type; } static inline void unsetattrib(const attribinfo &a) { switch(a.type) { case ATTRIB_VERTEX: glDisableClientState(GL_VERTEX_ARRAY); break; case ATTRIB_COLOR: glDisableClientState(GL_COLOR_ARRAY); break; case ATTRIB_NORMAL: glDisableClientState(GL_NORMAL_ARRAY); break; case ATTRIB_TEXCOORD0: glDisableClientState(GL_TEXTURE_COORD_ARRAY); break; case ATTRIB_TEXCOORD1: glClientActiveTexture_(GL_TEXTURE1_ARB); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glClientActiveTexture_(GL_TEXTURE0_ARB); break; } enabled &= ~a.type; } int end() { if(data.empty()) return 0; uchar *buf = data.getbuf(); bool forceattribs = numattribs != numlastattribs || vertexsize != lastvertexsize || buf != lastbuf; if(forceattribs || changedattribs) { int diffmask = enabled & lastattribmask & ~attribmask; if(diffmask) loopi(numlastattribs) { const attribinfo &a = lastattribs[i]; if(diffmask & a.type) unsetattrib(a); } uchar *src = buf; loopi(numattribs) { const attribinfo &a = attribs[i]; if(forceattribs || a != lastattribs[i]) { setattrib(a, src); lastattribs[i] = a; } src += a.formatsize; } lastbuf = buf; numlastattribs = numattribs; lastattribmask = attribmask; lastvertexsize = vertexsize; changedattribs = false; } int numvertexes = data.length()/vertexsize; glDrawArrays(primtype, 0, numvertexes); data.setsize(0); return numvertexes; } void disable() { if(!enabled) return; if(enabled&ATTRIB_VERTEX) glDisableClientState(GL_VERTEX_ARRAY); if(enabled&ATTRIB_COLOR) glDisableClientState(GL_COLOR_ARRAY); if(enabled&ATTRIB_NORMAL) glDisableClientState(GL_NORMAL_ARRAY); if(enabled&ATTRIB_TEXCOORD0) glDisableClientState(GL_TEXTURE_COORD_ARRAY); if(enabled&ATTRIB_TEXCOORD1) { glClientActiveTexture_(GL_TEXTURE1_ARB); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glClientActiveTexture_(GL_TEXTURE0_ARB); } enabled = 0; } #endif } sauerbraten-0.0.20130203.dfsg/engine/3dgui.cpp0000644000175000017500000013526412074035705020377 0ustar vincentvincent// creates multiple gui windows that float inside the 3d world // special feature is that its mostly *modeless*: you can use this menu while playing, without turning menus on or off // implementationwise, it is *stateless*: it keeps no internal gui structure, hit tests are instant, usage & implementation is greatly simplified #include "engine.h" #include "textedit.h" static bool layoutpass, actionon = false; static int mousebuttons = 0; static struct gui *windowhit = NULL; static float firstx, firsty; enum {FIELDCOMMIT, FIELDABORT, FIELDEDIT, FIELDSHOW, FIELDKEY}; static int fieldmode = FIELDSHOW; static bool fieldsactive = false; static bool hascursor; static float cursorx = 0.5f, cursory = 0.5f; #define SHADOW 4 #define ICON_SIZE (FONTH-SHADOW) #define SKIN_W 256 #define SKIN_H 128 #define SKIN_SCALE 4 #define INSERT (3*SKIN_SCALE) #define MAXCOLUMNS 16 VARP(guiautotab, 6, 16, 40); VARP(guiclicktab, 0, 0, 1); VARP(guifadein, 0, 1, 1); struct gui : g3d_gui { struct list { int parent, w, h, springs, curspring, column; }; int firstlist, nextlist; int columns[MAXCOLUMNS]; static vector lists; static float hitx, hity; static int curdepth, curlist, xsize, ysize, curx, cury; static bool shouldmergehits, shouldautotab; static void reset() { lists.setsize(0); } static int ty, tx, tpos, *tcurrent, tcolor; //tracking tab size and position since uses different layout method... void allowautotab(bool on) { shouldautotab = on; } void autotab() { if(tcurrent) { if(layoutpass && !tpos) tcurrent = NULL; //disable tabs because you didn't start with one if(shouldautotab && !curdepth && (layoutpass ? 0 : cury) + ysize > guiautotab*FONTH) tab(NULL, tcolor); } } bool shouldtab() { if(tcurrent && shouldautotab) { if(layoutpass) { int space = guiautotab*FONTH - ysize; if(space < 0) return true; int l = lists[curlist].parent; while(l >= 0) { space -= lists[l].h; if(space < 0) return true; l = lists[l].parent; } } else { int space = guiautotab*FONTH - cury; if(ysize > space) return true; int l = lists[curlist].parent; while(l >= 0) { if(lists[l].h > space) return true; l = lists[l].parent; } } } return false; } bool visible() { return (!tcurrent || tpos==*tcurrent) && !layoutpass; } //tab is always at top of page void tab(const char *name, int color) { if(curdepth != 0) return; if(color) tcolor = color; tpos++; if(!name) name = intstr(tpos); int w = max(text_width(name) - 2*INSERT, 0); if(layoutpass) { ty = max(ty, ysize); ysize = 0; } else { cury = -ysize; int h = FONTH-2*INSERT, x1 = curx + tx, x2 = x1 + w + ((skinx[3]-skinx[2]) + (skinx[5]-skinx[4]))*SKIN_SCALE, y1 = cury - ((skiny[6]-skiny[1])-(skiny[3]-skiny[2]))*SKIN_SCALE-h, y2 = cury; bool hit = tcurrent && windowhit==this && hitx>=x1 && hity>=y1 && hitx=0) { lists[curlist].w = xsize; lists[curlist].h = ysize; } list &l = lists.add(); l.parent = curlist; l.springs = 0; l.column = -1; curlist = lists.length()-1; xsize = ysize = 0; } else { curlist = nextlist++; if(curlist >= lists.length()) // should never get here unless script code doesn't use same amount of lists in layout and render passes { list &l = lists.add(); l.parent = curlist; l.springs = 0; l.column = -1; l.w = l.h = 0; } list &l = lists[curlist]; l.curspring = 0; if(l.springs > 0) { if(ishorizontal()) xsize = l.w; else ysize = l.h; } else { xsize = l.w; ysize = l.h; } } curdepth++; } void poplist() { if(!lists.inrange(curlist)) return; list &l = lists[curlist]; if(layoutpass) { l.w = xsize; l.h = ysize; if(l.column >= 0) columns[l.column] = max(columns[l.column], ishorizontal() ? ysize : xsize); } curlist = l.parent; curdepth--; if(lists.inrange(curlist)) { int w = xsize, h = ysize; if(ishorizontal()) cury -= h; else curx -= w; list &p = lists[curlist]; xsize = p.w; ysize = p.h; if(!layoutpass && p.springs > 0) { list &s = lists[p.parent]; if(ishorizontal()) xsize = s.w; else ysize = s.h; } layout(w, h); } } int text (const char *text, int color, const char *icon) { autotab(); return button_(text, color, icon, false, false); } int button(const char *text, int color, const char *icon) { autotab(); return button_(text, color, icon, true, false); } int title (const char *text, int color, const char *icon) { autotab(); return button_(text, color, icon, false, true); } void separator() { autotab(); line_(FONTH/3); } void progress(float percent) { autotab(); line_((FONTH*4)/5, percent); } //use to set min size (useful when you have progress bars) void strut(float size) { layout(isvertical() ? int(size*FONTW) : 0, isvertical() ? 0 : int(size*FONTH)); } //add space between list items void space(float size) { layout(isvertical() ? 0 : int(size*FONTW), isvertical() ? int(size*FONTH) : 0); } void spring(int weight) { if(curlist < 0) return; list &l = lists[curlist]; if(layoutpass) { if(l.parent >= 0) l.springs += weight; return; } int nextspring = min(l.curspring + weight, l.springs); if(nextspring <= l.curspring) return; if(ishorizontal()) { int w = xsize - l.w; layout((w*nextspring)/l.springs - (w*l.curspring)/l.springs, 0); } else { int h = ysize - l.h; layout(0, (h*nextspring)/l.springs - (h*l.curspring)/l.springs); } l.curspring = nextspring; } void column(int col) { if(curlist < 0 || !layoutpass || col < 0 || col >= MAXCOLUMNS) return; list &l = lists[curlist]; l.column = col; } int layout(int w, int h) { if(layoutpass) { if(ishorizontal()) { xsize += w; ysize = max(ysize, h); } else { xsize = max(xsize, w); ysize += h; } return 0; } else { bool hit = ishit(w, h); if(ishorizontal()) curx += w; else cury += h; return (hit && visible()) ? mousebuttons|G3D_ROLLOVER : 0; } } void mergehits(bool on) { shouldmergehits = on; } bool ishit(int w, int h, int x = curx, int y = cury) { if(shouldmergehits) return windowhit==this && (ishorizontal() ? hitx>=x && hitx=y && hity=x && hity>=y && hitxset(); glColor4f(0, 0, 0, 0.75f); rect_(xi+SHADOW, yi+SHADOW, xs, ys, -1); glEnable(GL_TEXTURE_2D); defaultshader->set(); } int x1 = int(floor(screen->w*(xi*scale.x+origin.x))), y1 = int(floor(screen->h*(1 - ((yi+ys)*scale.y+origin.y)))), x2 = int(ceil(screen->w*((xi+xs)*scale.x+origin.x))), y2 = int(ceil(screen->h*(1 - (yi*scale.y+origin.y)))); glViewport(x1, y1, x2-x1, y2-y1); glScissor(x1, y1, x2-x1, y2-y1); glEnable(GL_SCISSOR_TEST); glDisable(GL_BLEND); modelpreview::start(overlaid); game::renderplayerpreview(model, team, weap); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); modelpreview::end(); glDisable(GL_SCISSOR_TEST); glViewport(0, 0, screen->w, screen->h); if(overlaid) { if(hit) { glDisable(GL_TEXTURE_2D); notextureshader->set(); glBlendFunc(GL_ZERO, GL_SRC_COLOR); glColor3f(1, 0.5f, 0.5f); rect_(xi, yi, xs, ys, -1); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); defaultshader->set(); } if(!overlaytex) overlaytex = textureload("data/guioverlay.png", 3); glColor3fv(light.v); glBindTexture(GL_TEXTURE_2D, overlaytex->id); rect_(xi, yi, xs, ys, 0); } } return layout(size+SHADOW, size+SHADOW); } int modelpreview(const char *name, int anim, float sizescale, bool overlaid) { autotab(); if(sizescale==0) sizescale = 1; int size = (int)(sizescale*2*FONTH)-SHADOW; if(visible()) { bool hit = ishit(size+SHADOW, size+SHADOW); float xs = size, ys = size, xi = curx, yi = cury; if(overlaid && hit && actionon) { glDisable(GL_TEXTURE_2D); notextureshader->set(); glColor4f(0, 0, 0, 0.75f); rect_(xi+SHADOW, yi+SHADOW, xs, ys, -1); glEnable(GL_TEXTURE_2D); defaultshader->set(); } int x1 = int(floor(screen->w*(xi*scale.x+origin.x))), y1 = int(floor(screen->h*(1 - ((yi+ys)*scale.y+origin.y)))), x2 = int(ceil(screen->w*((xi+xs)*scale.x+origin.x))), y2 = int(ceil(screen->h*(1 - (yi*scale.y+origin.y)))); glViewport(x1, y1, x2-x1, y2-y1); glScissor(x1, y1, x2-x1, y2-y1); glEnable(GL_SCISSOR_TEST); glDisable(GL_BLEND); modelpreview::start(overlaid); model *m = loadmodel(name); if(m) { entitylight light; light.color = vec(1, 1, 1); light.dir = vec(0, -1, 2).normalize(); vec center, radius; m->boundbox(0, center, radius); float dist = 2.0f*max(radius.magnitude2(), 1.1f*radius.z), yaw = fmod(lastmillis/10000.0f*360.0f, 360.0f); vec o(-center.x, dist - center.y, -0.1f*dist - center.z); rendermodel(&light, name, anim, o, yaw, 0, 0, NULL, NULL, 0); } modelpreview::end(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glDisable(GL_SCISSOR_TEST); glViewport(0, 0, screen->w, screen->h); if(overlaid) { if(hit) { glDisable(GL_TEXTURE_2D); notextureshader->set(); glBlendFunc(GL_ZERO, GL_SRC_COLOR); glColor3f(1, 0.5f, 0.5f); rect_(xi, yi, xs, ys, -1); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); defaultshader->set(); } if(!overlaytex) overlaytex = textureload("data/guioverlay.png", 3); glColor3fv(light.v); glBindTexture(GL_TEXTURE_2D, overlaytex->id); rect_(xi, yi, xs, ys, 0); } } return layout(size+SHADOW, size+SHADOW); } void slider(int &val, int vmin, int vmax, int color, const char *label) { autotab(); int x = curx; int y = cury; line_((FONTH*2)/3); if(visible()) { if(!label) label = intstr(val); int w = text_width(label); bool hit; int px, py; if(ishorizontal()) { hit = ishit(FONTH, ysize, x, y); px = x + (FONTH-w)/2; py = y + (ysize-FONTH) - ((ysize-FONTH)*(val-vmin))/((vmax==vmin) ? 1 : (vmax-vmin)); //vmin at bottom } else { hit = ishit(xsize, FONTH, x, y); px = x + FONTH/2 - w/2 + ((xsize-w)*(val-vmin))/((vmax==vmin) ? 1 : (vmax-vmin)); //vmin at left py = y; } if(hit) color = 0xFF0000; text_(label, px, py, color, hit && actionon, hit); if(hit && actionon) { int vnew = (vmin < vmax ? 1 : -1)+vmax-vmin; if(ishorizontal()) vnew = int((vnew*(y+ysize-FONTH/2-hity))/(ysize-FONTH)); else vnew = int((vnew*(hitx-x-FONTH/2))/(xsize-w)); vnew += vmin; vnew = vmin < vmax ? clamp(vnew, vmin, vmax) : clamp(vnew, vmax, vmin); if(vnew != val) val = vnew; } } } char *field(const char *name, int color, int length, int height, const char *initval, int initmode) { return field_(name, color, length, height, initval, initmode, FIELDEDIT); } char *keyfield(const char *name, int color, int length, int height, const char *initval, int initmode) { return field_(name, color, length, height, initval, initmode, FIELDKEY); } char *field_(const char *name, int color, int length, int height, const char *initval, int initmode, int fieldtype = FIELDEDIT) { editor *e = useeditor(name, initmode, false, initval); // generate a new editor if necessary if(layoutpass) { if(initval && e->mode==EDITORFOCUSED && (e!=currentfocus() || fieldmode == FIELDSHOW)) { if(strcmp(e->lines[0].text, initval)) e->clear(initval); } e->linewrap = (length<0); e->maxx = (e->linewrap) ? -1 : length; e->maxy = (height<=0)?1:-1; e->pixelwidth = abs(length)*FONTW; if(e->linewrap && e->maxy==1) { int temp; text_bounds(e->lines[0].text, temp, e->pixelheight, e->pixelwidth); //only single line editors can have variable height } else e->pixelheight = FONTH*max(height, 1); } int h = e->pixelheight; int w = e->pixelwidth + FONTW; bool wasvertical = isvertical(); if(wasvertical && e->maxy != 1) pushlist(); char *result = NULL; if(visible() && !layoutpass) { e->rendered = true; bool hit = ishit(w, h); if(hit) { if(mousebuttons&G3D_DOWN) //mouse request focus { if(fieldtype==FIELDKEY) e->clear(); useeditor(name, initmode, true); e->mark(false); fieldmode = fieldtype; } } bool editing = (fieldmode != FIELDSHOW) && (e==currentfocus()); if(hit && editing && (mousebuttons&G3D_PRESSED)!=0 && fieldtype==FIELDEDIT) e->hit(int(floor(hitx-(curx+FONTW/2))), int(floor(hity-cury)), (mousebuttons&G3D_DRAGGED)!=0); //mouse request position if(editing && ((fieldmode==FIELDCOMMIT) || (fieldmode==FIELDABORT) || !hit)) // commit field if user pressed enter or wandered out of focus { if(fieldmode==FIELDCOMMIT || (fieldmode!=FIELDABORT && !hit)) result = e->currentline().text; e->active = (e->mode!=EDITORFOCUSED); fieldmode = FIELDSHOW; } else fieldsactive = true; e->draw(curx+FONTW/2, cury, color, hit && editing); lineshader->set(); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); if(editing) glColor3f(1, 0, 0); else glColor3ub(color>>16, (color>>8)&0xFF, color&0xFF); rect_(curx, cury, w, h, -1, true); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); defaultshader->set(); } layout(w, h); if(e->maxy != 1) { int slines = e->limitscrolly(); if(slines > 0) { int pos = e->scrolly; slider(e->scrolly, slines, 0, color, NULL); if(pos != e->scrolly) e->cy = e->scrolly; } if(wasvertical) poplist(); } return result; } void rect_(float x, float y, float w, float h, int usetc = -1, bool lines = false) { glBegin(lines ? GL_LINE_LOOP : GL_TRIANGLE_STRIP); static const GLfloat tc[4][2] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}}; if(usetc>=0) glTexCoord2fv(tc[usetc]); glVertex2f(x, y); if(usetc>=0) glTexCoord2fv(tc[(usetc+1)%4]); glVertex2f(x + w, y); if(lines) { if(usetc>=0) glTexCoord2fv(tc[(usetc+2)%4]); glVertex2f(x + w, y + h); } if(usetc>=0) glTexCoord2fv(tc[(usetc+3)%4]); glVertex2f(x, y + h); if(!lines) { if(usetc>=0) glTexCoord2fv(tc[(usetc+2)%4]); glVertex2f(x + w, y + h); } glEnd(); xtraverts += 4; } void text_(const char *text, int x, int y, int color, bool shadow, bool force = false) { if(shadow) draw_text(text, x+SHADOW, y+SHADOW, 0x00, 0x00, 0x00, -0xC0); draw_text(text, x, y, color>>16, (color>>8)&0xFF, color&0xFF, force ? -0xFF : 0xFF); } void background(int color, int inheritw, int inherith) { if(layoutpass) return; glDisable(GL_TEXTURE_2D); notextureshader->set(); glColor4ub(color>>16, (color>>8)&0xFF, color&0xFF, 0x80); int w = xsize, h = ysize; if(inheritw>0) { int parentw = curlist, parentdepth = 0; for(;parentdepth < inheritw && lists[parentw].parent>=0; parentdepth++) parentw = lists[parentw].parent; list &p = lists[parentw]; w = p.springs > 0 && (curdepth-parentdepth)&1 ? lists[p.parent].w : p.w; } if(inherith>0) { int parenth = curlist, parentdepth = 0; for(;parentdepth < inherith && lists[parenth].parent>=0; parentdepth++) parenth = lists[parenth].parent; list &p = lists[parenth]; h = p.springs > 0 && !((curdepth-parentdepth)&1) ? lists[p.parent].h : p.h; } rect_(curx, cury, w, h); glEnable(GL_TEXTURE_2D); defaultshader->set(); } void icon_(Texture *t, bool overlaid, int x, int y, int size, bool hit) { float scale = float(size)/max(t->xs, t->ys); //scale and preserve aspect ratio float xs = t->xs*scale, ys = t->ys*scale; x += int((size-xs)/2); y += int((size-ys)/2); const vec &color = hit ? vec(1, 0.5f, 0.5f) : (overlaid ? vec(1, 1, 1) : light); glBindTexture(GL_TEXTURE_2D, t->id); if(hit && actionon) { glColor4f(0, 0, 0, 0.75f); rect_(x+SHADOW, y+SHADOW, xs, ys, 0); } glColor3fv(color.v); rect_(x, y, xs, ys, 0); if(overlaid) { if(!overlaytex) overlaytex = textureload("data/guioverlay.png", 3); glBindTexture(GL_TEXTURE_2D, overlaytex->id); glColor3fv(light.v); rect_(x, y, xs, ys, 0); } } void previewslot(VSlot &vslot, bool overlaid, int x, int y, int size, bool hit) { Slot &slot = *vslot.slot; if(slot.sts.empty()) return; VSlot *layer = NULL; Texture *t = NULL, *glowtex = NULL, *layertex = NULL; if(slot.loaded) { t = slot.sts[0].t; if(t == notexture) return; Slot &slot = *vslot.slot; if(slot.texmask&(1<slot->sts.empty()) layertex = layer->slot->sts[0].t; } } else if(slot.thumbnail && slot.thumbnail != notexture) t = slot.thumbnail; else return; float xt = min(1.0f, t->xs/(float)t->ys), yt = min(1.0f, t->ys/(float)t->xs), xs = size, ys = size; if(hit && actionon) { glDisable(GL_TEXTURE_2D); notextureshader->set(); glColor4f(0, 0, 0, 0.75f); rect_(x+SHADOW, y+SHADOW, xs, ys); glEnable(GL_TEXTURE_2D); defaultshader->set(); } SETSHADER(rgbonly); const vec &color = hit ? vec(1, 0.5f, 0.5f) : (overlaid ? vec(1, 1, 1) : light); float tc[4][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }; int xoff = vslot.xoffset, yoff = vslot.yoffset; if(vslot.rotation) { if((vslot.rotation&5) == 1) { swap(xoff, yoff); loopk(4) swap(tc[k][0], tc[k][1]); } if(vslot.rotation >= 2 && vslot.rotation <= 4) { xoff *= -1; loopk(4) tc[k][0] *= -1; } if(vslot.rotation <= 2 || vslot.rotation == 5) { yoff *= -1; loopk(4) tc[k][1] *= -1; } } loopk(4) { tc[k][0] = tc[k][0]/xt - float(xoff)/t->xs; tc[k][1] = tc[k][1]/yt - float(yoff)/t->ys; } if(slot.loaded) glColor3f(color.x*vslot.colorscale.x, color.y*vslot.colorscale.y, color.z*vslot.colorscale.z); else glColor3fv(color.v); glBindTexture(GL_TEXTURE_2D, t->id); glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(x, y); glTexCoord2fv(tc[1]); glVertex2f(x+xs, y); glTexCoord2fv(tc[3]); glVertex2f(x, y+ys); glTexCoord2fv(tc[2]); glVertex2f(x+xs, y+ys); glEnd(); if(glowtex) { glBlendFunc(GL_SRC_ALPHA, GL_ONE); glBindTexture(GL_TEXTURE_2D, glowtex->id); if(hit || overlaid) glColor3f(color.x*vslot.glowcolor.x, color.y*vslot.glowcolor.y, color.z*vslot.glowcolor.z); else glColor3fv(vslot.glowcolor.v); glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(x, y); glTexCoord2fv(tc[1]); glVertex2f(x+xs, y); glTexCoord2fv(tc[3]); glVertex2f(x, y+ys); glTexCoord2fv(tc[2]); glVertex2f(x+xs, y+ys); glEnd(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } if(layertex) { glBindTexture(GL_TEXTURE_2D, layertex->id); glColor3f(color.x*layer->colorscale.x, color.y*layer->colorscale.y, color.z*layer->colorscale.z); glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(x+xs/2, y+ys/2); glTexCoord2fv(tc[1]); glVertex2f(x+xs, y+ys/2); glTexCoord2fv(tc[3]); glVertex2f(x+xs/2, y+ys); glTexCoord2fv(tc[2]); glVertex2f(x+xs, y+ys); glEnd(); } defaultshader->set(); if(overlaid) { if(!overlaytex) overlaytex = textureload("data/guioverlay.png", 3); glBindTexture(GL_TEXTURE_2D, overlaytex->id); glColor3fv(light.v); rect_(x, y, xs, ys, 0); } } void line_(int size, float percent = 1.0f) { if(visible()) { if(!slidertex) slidertex = textureload("data/guislider.png", 3); glBindTexture(GL_TEXTURE_2D, slidertex->id); if(percent < 0.99f) { glColor4f(light.x, light.y, light.z, 0.375f); if(ishorizontal()) rect_(curx + FONTH/2 - size/2, cury, size, ysize, 0); else rect_(curx, cury + FONTH/2 - size/2, xsize, size, 1); } glColor3fv(light.v); if(ishorizontal()) rect_(curx + FONTH/2 - size/2, cury + ysize*(1-percent), size, ysize*percent, 0); else rect_(curx, cury + FONTH/2 - size/2, xsize*percent, size, 1); } layout(ishorizontal() ? FONTH : 0, ishorizontal() ? 0 : FONTH); } void textbox(const char *text, int width, int height, int color) { width *= FONTW; height *= FONTH; int w, h; text_bounds(text, w, h, width); if(h > height) height = h; if(visible()) draw_text(text, curx, cury, color>>16, (color>>8)&0xFF, color&0xFF, 0xFF, -1, width); layout(width, height); } int button_(const char *text, int color, const char *icon, bool clickable, bool center) { const int padding = 10; int w = 0; if(icon) w += ICON_SIZE; if(icon && text) w += padding; if(text) w += text_width(text); if(visible()) { bool hit = ishit(w, FONTH); if(hit && clickable) color = 0xFF0000; int x = curx; if(isvertical() && center) x += (xsize-w)/2; if(icon) { if(icon[0] != ' ') { const char *ext = strrchr(icon, '.'); defformatstring(tname)("packages/icons/%s%s", icon, ext ? "" : ".jpg"); icon_(textureload(tname, 3), false, x, cury, ICON_SIZE, clickable && hit); } x += ICON_SIZE; } if(icon && text) x += padding; if(text) text_(text, x, cury, color, center || (hit && clickable && actionon), hit && clickable); } return layout(w, FONTH); } static Texture *skintex, *overlaytex, *slidertex; static const int skinx[], skiny[]; static const struct patch { ushort left, right, top, bottom; uchar flags; } patches[]; static void drawskin(int x, int y, int gapw, int gaph, int start, int n, int passes = 1, const vec &light = vec(1, 1, 1), float alpha = 0.80f)//int vleft, int vright, int vtop, int vbottom, int start, int n) { if(!skintex) skintex = textureload("data/guiskin.png", 3); glBindTexture(GL_TEXTURE_2D, skintex->id); int gapx1 = INT_MAX, gapy1 = INT_MAX, gapx2 = INT_MAX, gapy2 = INT_MAX; float wscale = 1.0f/(SKIN_W*SKIN_SCALE), hscale = 1.0f/(SKIN_H*SKIN_SCALE); loopj(passes) { bool quads = false; if(passes>1) glDepthFunc(j ? GL_LEQUAL : GL_GREATER); glColor4f(j ? light.x : 1.0f, j ? light.y : 1.0f, j ? light.z : 1.0f, passes<=1 || j ? alpha : alpha/2); //ghost when its behind something in depth loopi(n) { const patch &p = patches[start+i]; int left = skinx[p.left]*SKIN_SCALE, right = skinx[p.right]*SKIN_SCALE, top = skiny[p.top]*SKIN_SCALE, bottom = skiny[p.bottom]*SKIN_SCALE; float tleft = left*wscale, tright = right*wscale, ttop = top*hscale, tbottom = bottom*hscale; if(p.flags&0x1) { gapx1 = left; gapx2 = right; } else if(left >= gapx2) { left += gapw - (gapx2-gapx1); right += gapw - (gapx2-gapx1); } if(p.flags&0x10) { gapy1 = top; gapy2 = bottom; } else if(top >= gapy2) { top += gaph - (gapy2-gapy1); bottom += gaph - (gapy2-gapy1); } //multiple tiled quads if necessary rather than a single stretched one int ystep = bottom-top; int yo = y+top; while(ystep > 0) { if(p.flags&0x10 && yo+ystep-(y+top) > gaph) { ystep = gaph+y+top-yo; tbottom = ttop+ystep*hscale; } int xstep = right-left; int xo = x+left; float tright2 = tright; while(xstep > 0) { if(p.flags&0x01 && xo+xstep-(x+left) > gapw) { xstep = gapw+x+left-xo; tright = tleft+xstep*wscale; } if(!quads) { quads = true; glBegin(GL_QUADS); } glTexCoord2f(tleft, ttop); glVertex2f(xo, yo); glTexCoord2f(tright, ttop); glVertex2f(xo+xstep, yo); glTexCoord2f(tright, tbottom); glVertex2f(xo+xstep, yo+ystep); glTexCoord2f(tleft, tbottom); glVertex2f(xo, yo+ystep); xtraverts += 4; if(!(p.flags&0x01)) break; xo += xstep; } tright = tright2; if(!(p.flags&0x10)) break; yo += ystep; } } if(quads) glEnd(); else break; //if it didn't happen on the first pass, it won't happen on the second.. } if(passes>1) glDepthFunc(GL_ALWAYS); } vec origin, scale, *savedorigin; float dist; g3d_callback *cb; bool gui2d; static float basescale, maxscale; static bool passthrough; static float alpha; static vec light; void adjustscale() { int w = xsize + (skinx[2]-skinx[1])*SKIN_SCALE + (skinx[10]-skinx[9])*SKIN_SCALE, h = ysize + (skiny[9]-skiny[7])*SKIN_SCALE; if(tcurrent) h += ((skiny[5]-skiny[1])-(skiny[3]-skiny[2]))*SKIN_SCALE + FONTH-2*INSERT; else h += (skiny[6]-skiny[3])*SKIN_SCALE; float aspect = forceaspect ? 1.0f/forceaspect : float(screen->h)/float(screen->w), fit = 1.0f; if(w*aspect*basescale>1.0f) fit = 1.0f/(w*aspect*basescale); if(h*basescale*fit>maxscale) fit *= maxscale/(h*basescale*fit); origin = vec(0.5f-((w-xsize)/2 - (skinx[2]-skinx[1])*SKIN_SCALE)*aspect*scale.x*fit, 0.5f + (0.5f*h-(skiny[9]-skiny[7])*SKIN_SCALE)*scale.y*fit, 0); scale = vec(aspect*scale.x*fit, scale.y*fit, 1); } void start(int starttime, float initscale, int *tab, bool allowinput) { if(gui2d) { initscale *= 0.025f; if(allowinput) hascursor = true; } basescale = initscale; if(layoutpass) scale.x = scale.y = scale.z = guifadein ? basescale*min((totalmillis-starttime)/300.0f, 1.0f) : basescale; alpha = allowinput ? 0.80f : 0.60f; passthrough = scale.xo.y, origin.x-camera1->o.x); glTranslatef(origin.x, origin.y, origin.z); glRotatef(yaw/RAD-90, 0, 0, 1); glRotatef(-90, 1, 0, 0); glScalef(-scale.x, scale.y, scale.z); vec dir; lightreaching(origin, light, dir, false, 0, 0.5f); float intensity = vec(yaw, 0.0f).dot(dir); light.mul(1.0f + max(intensity, 0.0f)); } drawskin(curx-skinx[2]*SKIN_SCALE, cury-skiny[6]*SKIN_SCALE, xsize, ysize, 0, 9, gui2d ? 1 : 2, light, alpha); if(!tcurrent) drawskin(curx-skinx[5]*SKIN_SCALE, cury-skiny[6]*SKIN_SCALE, xsize, 0, 9, 1, gui2d ? 1 : 2, light, alpha); } } void adjusthorizontalcolumn(int col, int i) { int h = columns[col], dh = 0; for(int d = 1; i >= 0; d ^= 1) { list &p = lists[i]; if(d&1) { dh = h - p.h; if(dh <= 0) break; p.h = h; } else { p.h += dh; h = p.h; } i = p.parent; } ysize += max(dh, 0); } void adjustverticalcolumn(int col, int i) { int w = columns[col], dw = 0; for(int d = 0; i >= 0; d ^= 1) { list &p = lists[i]; if(d&1) { p.w += dw; w = p.w; } else { dw = w - p.w; if(dw <= 0) break; p.w = w; } i = p.parent; } xsize = max(xsize, w); } void adjustcolumns() { if(lists.inrange(curlist)) { list &l = lists[curlist]; if(l.column >= 0) columns[l.column] = max(columns[l.column], ishorizontal() ? ysize : xsize); } int parent = -1, depth = 0; for(int i = firstlist; i < lists.length(); i++) { list &l = lists[i]; if(l.parent > parent) { parent = l.parent; depth++; } else if(l.parent < parent) { parent = l.parent; depth--; } if(l.column >= 0) { if(depth&1) adjusthorizontalcolumn(l.column, i); else adjustverticalcolumn(l.column, i); } } } void end() { if(layoutpass) { adjustcolumns(); xsize = max(tx, xsize); ysize = max(ty, ysize); ysize = max(ysize, (skiny[7]-skiny[6])*SKIN_SCALE); if(tcurrent) *tcurrent = max(1, min(*tcurrent, tpos)); if(gui2d) adjustscale(); if(!windowhit && !passthrough) { float dist = 0; if(gui2d) { hitx = (cursorx - origin.x)/scale.x; hity = (cursory - origin.y)/scale.y; } else { plane p; p.toplane(vec(origin).sub(camera1->o).set(2, 0).normalize(), origin); if(p.rayintersect(camera1->o, camdir, dist) && dist>=0) { vec hitpos(camdir); hitpos.mul(dist).add(camera1->o).sub(origin); hitx = vec(-p.y, p.x, 0).dot(hitpos)/scale.x; hity = -hitpos.z/scale.y; } } if((mousebuttons & G3D_PRESSED) && (fabs(hitx-firstx) > 2 || fabs(hity - firsty) > 2)) mousebuttons |= G3D_DRAGGED; if(dist>=0 && hitx>=-xsize/2 && hitx<=xsize/2 && hity<=0) { if(hity>=-ysize || (tcurrent && hity>=-ysize-(FONTH-2*INSERT)-((skiny[6]-skiny[1])-(skiny[3]-skiny[2]))*SKIN_SCALE && hitx<=tx-xsize/2)) windowhit = this; } } } else { if(tcurrent && txgui(*this, layoutpass); } }; Texture *gui::skintex = NULL, *gui::overlaytex = NULL, *gui::slidertex = NULL; //chop skin into a grid const int gui::skiny[] = {0, 7, 21, 34, 43, 48, 56, 104, 111, 117, 128}, gui::skinx[] = {0, 11, 23, 37, 105, 119, 137, 151, 215, 229, 246, 256}; //Note: skinx[3]-skinx[2] = skinx[7]-skinx[6] // skinx[5]-skinx[4] = skinx[9]-skinx[8] const gui::patch gui::patches[] = { //arguably this data can be compressed - it depends on what else needs to be skinned in the future {1,2,3,6, 0}, // body {2,9,5,6, 0x01}, {9,10,3,6, 0}, {1,2,6,7, 0x10}, {2,9,6,7, 0x11}, {9,10,6,7, 0x10}, {1,2,7,9, 0}, {2,9,7,9, 0x01}, {9,10,7,9, 0}, {5,6,3,5, 0x01}, // top {2,3,1,2, 0}, // selected tab {3,4,1,2, 0x01}, {4,5,1,2, 0}, {2,3,2,3, 0x10}, {3,4,2,3, 0x11}, {4,5,2,3, 0x10}, {2,3,3,5, 0}, {3,4,3,5, 0x01}, {4,5,3,5, 0}, {6,7,1,2, 0}, // deselected tab {7,8,1,2, 0x01}, {8,9,1,2, 0}, {6,7,2,3, 0x10}, {7,8,2,3, 0x11}, {8,9,2,3, 0x10}, {6,7,3,5, 0}, {7,8,3,5, 0x01}, {8,9,3,5, 0}, }; vector gui::lists; float gui::basescale, gui::maxscale = 1, gui::hitx, gui::hity, gui::alpha; bool gui::passthrough, gui::shouldmergehits = false, gui::shouldautotab = true; vec gui::light; int gui::curdepth, gui::curlist, gui::xsize, gui::ysize, gui::curx, gui::cury; int gui::ty, gui::tx, gui::tpos, *gui::tcurrent, gui::tcolor; static vector guis2d, guis3d; VARP(guipushdist, 1, 4, 64); bool menukey(int code, bool isdown, int cooked) { editor *e = currentfocus(); if(fieldmode == FIELDKEY) { switch(code) { case SDLK_ESCAPE: if(isdown) fieldmode = FIELDCOMMIT; return true; } const char *keyname = getkeyname(code); if(keyname && isdown) { if(e->lines.length()!=1 || !e->lines[0].empty()) e->insert(" "); e->insert(keyname); } return true; } if(code==-1 && g3d_windowhit(isdown, true)) return true; else if(code==-3 && g3d_windowhit(isdown, false)) return true; if(fieldmode == FIELDSHOW || !e) { if(windowhit) switch(code) { case -4: // window "management" if(isdown) { if(windowhit->gui2d) { vec origin = *guis2d.last().savedorigin; int i = windowhit - &guis2d[0]; for(int j = guis2d.length()-1; j > i; j--) *guis2d[j].savedorigin = *guis2d[j-1].savedorigin; *windowhit->savedorigin = origin; if(guis2d.length() > 1) { if(camera1->o.dist(*windowhit->savedorigin) <= camera1->o.dist(*guis2d.last().savedorigin)) windowhit->savedorigin->add(camdir); } } else windowhit->savedorigin->add(vec(camdir).mul(guipushdist)); } return true; case -5: if(isdown) { if(windowhit->gui2d) { vec origin = *guis2d[0].savedorigin; loopj(guis2d.length()-1) *guis2d[j].savedorigin = *guis2d[j + 1].savedorigin; *guis2d.last().savedorigin = origin; if(guis2d.length() > 1) { if(camera1->o.dist(*guis2d.last().savedorigin) >= camera1->o.dist(*guis2d[0].savedorigin)) guis2d.last().savedorigin->sub(camdir); } } else windowhit->savedorigin->sub(vec(camdir).mul(guipushdist)); } return true; } return false; } switch(code) { case SDLK_ESCAPE: //cancel editing without commit if(isdown) fieldmode = FIELDABORT; return true; case SDLK_RETURN: case SDLK_TAB: if(cooked && (e->maxy != 1)) break; case SDLK_KP_ENTER: if(isdown) fieldmode = FIELDCOMMIT; //signal field commit (handled when drawing field) return true; case SDLK_HOME: case SDLK_END: case SDLK_PAGEUP: case SDLK_PAGEDOWN: case SDLK_DELETE: case SDLK_BACKSPACE: case SDLK_UP: case SDLK_DOWN: case SDLK_LEFT: case SDLK_RIGHT: case SDLK_LSHIFT: case SDLK_RSHIFT: case -4: case -5: break; default: if(!cooked || (code<32)) return false; break; } if(!isdown) return true; e->key(code, cooked); return true; } void g3d_cursorpos(float &x, float &y) { if(guis2d.length()) { x = cursorx; y = cursory; } else x = y = 0.5f; } void g3d_resetcursor() { cursorx = cursory = 0.5f; } FVARP(guisens, 1e-3f, 1, 1e3f); bool g3d_movecursor(int dx, int dy) { if(!guis2d.length() || !hascursor) return false; const float CURSORSCALE = 500.0f; cursorx = max(0.0f, min(1.0f, cursorx+guisens*dx*(screen->h/(screen->w*CURSORSCALE)))); cursory = max(0.0f, min(1.0f, cursory+guisens*dy/CURSORSCALE)); return true; } VARNP(guifollow, useguifollow, 0, 1, 1); VARNP(gui2d, usegui2d, 0, 1, 1); void g3d_addgui(g3d_callback *cb, vec &origin, int flags) { bool gui2d = flags&GUI_FORCE_2D || (flags&GUI_2D && usegui2d) || mainmenu; if(!gui2d && flags&GUI_FOLLOW && useguifollow) origin.z = player->o.z-(player->eyeheight-1); gui &g = (gui2d ? guis2d : guis3d).add(); g.cb = cb; g.origin = origin; g.savedorigin = &origin; g.dist = flags&GUI_BOTTOM && gui2d ? 1e16f : camera1->o.dist(g.origin); g.gui2d = gui2d; } void g3d_limitscale(float scale) { gui::maxscale = scale; } static inline bool g3d_sort(const gui &a, const gui &b) { return a.dist < b.dist; } bool g3d_windowhit(bool on, bool act) { extern int cleargui(int n); if(act) { if(actionon || windowhit) { if(on) { firstx = gui::hitx; firsty = gui::hity; } mousebuttons |= (actionon=on) ? G3D_DOWN : G3D_UP; } } else if(!on && windowhit) cleargui(1); return (guis2d.length() && hascursor) || (windowhit && !windowhit->gui2d); } void g3d_render() { windowhit = NULL; if(actionon) mousebuttons |= G3D_PRESSED; gui::reset(); guis2d.shrink(0); guis3d.shrink(0); // call all places in the engine that may want to render a gui from here, they call g3d_addgui() extern void g3d_texturemenu(); if(!mainmenu) g3d_texturemenu(); g3d_mainmenu(); if(!mainmenu) game::g3d_gamemenus(); guis2d.sort(g3d_sort); guis3d.sort(g3d_sort); readyeditors(); bool wasfocused = (fieldmode!=FIELDSHOW); fieldsactive = false; hascursor = false; layoutpass = true; loopv(guis2d) guis2d[i].draw(); loopv(guis3d) guis3d[i].draw(); layoutpass = false; if(guis2d.length() || guis3d.length()) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } if(guis3d.length()) { glEnable(GL_DEPTH_TEST); glDepthFunc(GL_ALWAYS); glDepthMask(GL_FALSE); loopvrev(guis3d) guis3d[i].draw(); glDepthFunc(GL_LESS); glDepthMask(GL_TRUE); glDisable(GL_DEPTH_TEST); } if(guis2d.length()) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, 1, 1, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); loopvrev(guis2d) guis2d[i].draw(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } if(guis2d.length() || guis3d.length()) { glDisable(GL_BLEND); } flusheditors(); if(!fieldsactive) fieldmode = FIELDSHOW; //didn't draw any fields, so loose focus - mainly for menu closed if((fieldmode!=FIELDSHOW) != wasfocused) { SDL_EnableUNICODE(fieldmode!=FIELDSHOW); keyrepeat(fieldmode!=FIELDSHOW || editmode); } mousebuttons = 0; } void consolebox(int x1, int y1, int x2, int y2) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); glTranslatef(x1, y1, 0); float bw = x2 - x1, bh = y2 - y1, aspect = bw/bh, sh = bh, sw = sh*aspect; bw *= float(4*FONTH)/(SKIN_H*SKIN_SCALE); bh *= float(4*FONTH)/(SKIN_H*SKIN_SCALE); sw /= bw + (gui::skinx[2]-gui::skinx[1] + gui::skinx[10]-gui::skinx[9])*SKIN_SCALE; sh /= bh + (gui::skiny[9]-gui::skiny[7] + gui::skiny[6]-gui::skiny[4])*SKIN_SCALE; glScalef(sw, sh, 1); gui::drawskin(-gui::skinx[1]*SKIN_SCALE, -gui::skiny[4]*SKIN_SCALE, int(bw), int(bh), 0, 9, 1, vec(1, 1, 1), 0.60f); gui::drawskin((-gui::skinx[1] + gui::skinx[2] - gui::skinx[5])*SKIN_SCALE, -gui::skiny[4]*SKIN_SCALE, int(bw), 0, 9, 1, 1, vec(1, 1, 1), 0.60f); glPopMatrix(); } sauerbraten-0.0.20130203.dfsg/engine/grass.cpp0000644000175000017500000002615311767707565020521 0ustar vincentvincent#include "engine.h" VARP(grass, 0, 0, 1); VAR(dbggrass, 0, 0, 1); VARP(grassdist, 0, 256, 10000); FVARP(grasstaper, 0, 0.2, 1); FVARP(grassstep, 0.5, 2, 8); VARP(grassheight, 1, 4, 64); #define NUMGRASSWEDGES 8 static struct grasswedge { vec dir, across, edge1, edge2; plane bound1, bound2; grasswedge(int i) : dir(2*M_PI*(i+0.5f)/float(NUMGRASSWEDGES), 0), across(2*M_PI*((i+0.5f)/float(NUMGRASSWEDGES) + 0.25f), 0), edge1(vec(2*M_PI*i/float(NUMGRASSWEDGES), 0).div(cos(M_PI/NUMGRASSWEDGES))), edge2(vec(2*M_PI*(i+1)/float(NUMGRASSWEDGES), 0).div(cos(M_PI/NUMGRASSWEDGES))), bound1(vec(2*M_PI*(i/float(NUMGRASSWEDGES) - 0.25f), 0), 0), bound2(vec(2*M_PI*((i+1)/float(NUMGRASSWEDGES) + 0.25f), 0), 0) { across.div(-across.dot(bound1)); } } grasswedges[NUMGRASSWEDGES] = { 0, 1, 2, 3, 4, 5, 6, 7 }; struct grassvert { vec pos; uchar color[4]; float u, v, lmu, lmv; }; static vector grassverts; struct grassgroup { const grasstri *tri; float dist; int tex, lmtex, offset, numquads; }; static vector grassgroups; #define NUMGRASSOFFSETS 32 static float grassoffsets[NUMGRASSOFFSETS] = { -1 }, grassanimoffsets[NUMGRASSOFFSETS]; static int lastgrassanim = -1; VARR(grassanimmillis, 0, 3000, 60000); FVARR(grassanimscale, 0, 0.03f, 1); static void animategrass() { loopi(NUMGRASSOFFSETS) grassanimoffsets[i] = grassanimscale*sinf(2*M_PI*(grassoffsets[i] + lastmillis/float(grassanimmillis))); lastgrassanim = lastmillis; } VARR(grassscale, 1, 2, 64); bvec grasscolor(255, 255, 255); HVARFR(grasscolour, 0, 0xFFFFFF, 0xFFFFFF, { if(!grasscolour) grasscolour = 0xFFFFFF; grasscolor = bvec((grasscolour>>16)&0xFF, (grasscolour>>8)&0xFF, grasscolour&0xFF); }); FVARR(grassalpha, 0, 1, 1); static void gengrassquads(grassgroup *&group, const grasswedge &w, const grasstri &g, Texture *tex) { float t = camera1->o.dot(w.dir); int tstep = int(ceil(t/grassstep)); float tstart = tstep*grassstep, t0 = w.dir.dot(g.v[0]), t1 = w.dir.dot(g.v[1]), t2 = w.dir.dot(g.v[2]), t3 = w.dir.dot(g.v[3]), tmin = min(min(t0, t1), min(t2, t3)), tmax = max(max(t0, t1), max(t2, t3)); if(tmax < tstart || tmin > t + grassdist) return; int minstep = max(int(ceil(tmin/grassstep)) - tstep, 1), maxstep = int(floor(min(tmax, t + grassdist)/grassstep)) - tstep, numsteps = maxstep - minstep + 1; float texscale = (grassscale*tex->ys)/float(grassheight*tex->xs), animscale = grassheight*texscale; vec tc; tc.cross(g.surface, w.dir).mul(texscale); int color = tstep + maxstep; if(color < 0) color = NUMGRASSOFFSETS - (-color)%NUMGRASSOFFSETS; color += numsteps + NUMGRASSOFFSETS - numsteps%NUMGRASSOFFSETS; float leftdist = t0; const vec *leftv = &g.v[0]; if(t1 > leftdist) { leftv = &g.v[1]; leftdist = t1; } if(t2 > leftdist) { leftv = &g.v[2]; leftdist = t2; } if(t3 > leftdist) { leftv = &g.v[3]; leftdist = t3; } float rightdist = leftdist; const vec *rightv = leftv; vec across(w.across.x, w.across.y, g.surface.zdelta(w.across)), leftdir(0, 0, 0), rightdir(0, 0, 0), leftp = *leftv, rightp = *rightv; float taperdist = grassdist*grasstaper, taperscale = 1.0f / (grassdist - taperdist), dist = maxstep*grassstep + tstart, leftb = 0, rightb = 0, leftdb = 0, rightdb = 0; for(int i = maxstep; i >= minstep; i--, color--, leftp.add(leftdir), rightp.add(rightdir), leftb += leftdb, rightb += rightdb, dist -= grassstep) { if(dist <= leftdist) { const vec *prev = leftv; float prevdist = leftdist; if(--leftv < g.v) leftv += g.numv; leftdist = leftv->dot(w.dir); if(dist <= leftdist) { prev = leftv; prevdist = leftdist; if(--leftv < g.v) leftv += g.numv; leftdist = leftv->dot(w.dir); } leftdir = vec(*leftv).sub(*prev); leftdir.mul(grassstep/-w.dir.dot(leftdir)); leftp = vec(leftdir).mul((prevdist - dist)/grassstep).add(*prev); leftb = w.bound1.dist(leftp); leftdb = w.bound1.dot(leftdir); } if(dist <= rightdist) { const vec *prev = rightv; float prevdist = rightdist; if(++rightv >= &g.v[g.numv]) rightv = g.v; rightdist = rightv->dot(w.dir); if(dist <= rightdist) { prev = rightv; prevdist = rightdist; if(++rightv >= &g.v[g.numv]) rightv = g.v; rightdist = rightv->dot(w.dir); } rightdir = vec(*rightv).sub(*prev); rightdir.mul(grassstep/-w.dir.dot(rightdir)); rightp = vec(rightdir).mul((prevdist - dist)/grassstep).add(*prev); rightb = w.bound2.dist(rightp); rightdb = w.bound2.dot(rightdir); } vec p1 = leftp, p2 = rightp; if(leftb > 0) { if(w.bound1.dist(p2) >= 0) continue; p1.add(vec(across).mul(leftb)); } if(rightb > 0) { if(w.bound2.dist(p1) >= 0) continue; p2.sub(vec(across).mul(rightb)); } if(!group) { group = &grassgroups.add(); group->tri = &g; group->tex = tex->id; extern bool brightengeom; extern int fullbright; int lmid = brightengeom && (g.lmid < LMID_RESERVED || (fullbright && editmode)) ? LMID_BRIGHT : g.lmid; group->lmtex = lightmaptexs.inrange(lmid) ? lightmaptexs[lmid].id : notexture->id; group->offset = grassverts.length(); group->numquads = 0; if(lastgrassanim!=lastmillis) animategrass(); } group->numquads++; float offset = grassoffsets[color%NUMGRASSOFFSETS], animoffset = animscale*grassanimoffsets[color%NUMGRASSOFFSETS], tc1 = tc.dot(p1) + offset, tc2 = tc.dot(p2) + offset, lm1u = g.tcu.dot(p1), lm1v = g.tcv.dot(p1), lm2u = g.tcu.dot(p2), lm2v = g.tcv.dot(p2), fade = dist - t > taperdist ? (grassdist - (dist - t))*taperscale : 1, height = grassheight * fade; uchar color[4] = { grasscolor.x, grasscolor.y, grasscolor.z, uchar(fade*grassalpha*255) }; #define GRASSVERT(n, tcv, modify) { \ grassvert &gv = grassverts.add(); \ gv.pos = p##n; \ memcpy(gv.color, color, sizeof(color)); \ gv.u = tc##n; gv.v = tcv; \ gv.lmu = lm##n##u; gv.lmv = lm##n##v; \ modify; \ } GRASSVERT(2, 0, { gv.pos.z += height; gv.u += animoffset; }); GRASSVERT(1, 0, { gv.pos.z += height; gv.u += animoffset; }); GRASSVERT(1, 1, ); GRASSVERT(2, 1, ); } } static void gengrassquads(vtxarray *va) { loopv(va->grasstris) { grasstri &g = va->grasstris[i]; if(isfoggedsphere(g.radius, g.center)) continue; float dist = g.center.dist(camera1->o); if(dist - g.radius > grassdist) continue; Slot &s = *lookupvslot(g.texture, false).slot; if(!s.grasstex) { if(!s.autograss) continue; s.grasstex = textureload(s.autograss, 2); } grassgroup *group = NULL; loopi(NUMGRASSWEDGES) { grasswedge &w = grasswedges[i]; if(w.bound1.dist(g.center) > g.radius || w.bound2.dist(g.center) > g.radius) continue; gengrassquads(group, w, g, s.grasstex); } if(group) group->dist = dist; } } static inline bool comparegrassgroups(const grassgroup &x, const grassgroup &y) { return x.dist > y.dist; } void generategrass() { if(!grass || !grassdist) return; grassgroups.setsize(0); grassverts.setsize(0); if(grassoffsets[0] < 0) loopi(NUMGRASSOFFSETS) grassoffsets[i] = rnd(0x1000000)/float(0x1000000); loopi(NUMGRASSWEDGES) { grasswedge &w = grasswedges[i]; w.bound1.offset = -camera1->o.dot(w.bound1); w.bound2.offset = -camera1->o.dot(w.bound2); } extern vtxarray *visibleva; for(vtxarray *va = visibleva; va; va = va->next) { if(va->grasstris.empty() || va->occluded >= OCCLUDE_GEOM) continue; if(va->distance > grassdist) continue; if(reflecting || refracting>0 ? va->o.z+va->sizeo.z>=reflectz) continue; gengrassquads(va); } grassgroups.sort(comparegrassgroups); } void rendergrass() { if(!grass || !grassdist || grassgroups.empty() || dbggrass) return; glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(renderpath==R_FIXEDFUNCTION ? GL_SRC_ALPHA : GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDepthMask(GL_FALSE); SETSHADER(grass); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(grassvert), grassverts[0].pos.v); glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(grassvert), grassverts[0].color); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(grassvert), &grassverts[0].u); if(renderpath!=R_FIXEDFUNCTION || maxtmus>=2) { glActiveTexture_(GL_TEXTURE1_ARB); glClientActiveTexture_(GL_TEXTURE1_ARB); glEnable(GL_TEXTURE_2D); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(grassvert), &grassverts[0].lmu); if(renderpath==R_FIXEDFUNCTION) setuptmu(1, "P * T x 2"); glClientActiveTexture_(GL_TEXTURE0_ARB); glActiveTexture_(GL_TEXTURE0_ARB); } int texid = -1, lmtexid = -1; loopv(grassgroups) { grassgroup &g = grassgroups[i]; if(reflecting || refracting) { if(refracting < 0 ? g.tri->minz > reflectz : g.tri->maxz + grassheight < reflectz) continue; if(isfoggedsphere(g.tri->radius, g.tri->center)) continue; } if(texid != g.tex) { glBindTexture(GL_TEXTURE_2D, g.tex); texid = g.tex; } if(lmtexid != g.lmtex) { if(renderpath!=R_FIXEDFUNCTION || maxtmus>=2) { glActiveTexture_(GL_TEXTURE1_ARB); glBindTexture(GL_TEXTURE_2D, g.lmtex); glActiveTexture_(GL_TEXTURE0_ARB); } lmtexid = g.lmtex; } glDrawArrays(GL_QUADS, g.offset, 4*g.numquads); xtravertsva += 4*g.numquads; } glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); if(renderpath!=R_FIXEDFUNCTION || maxtmus>=2) { glActiveTexture_(GL_TEXTURE1_ARB); glClientActiveTexture_(GL_TEXTURE1_ARB); if(renderpath==R_FIXEDFUNCTION) resettmu(1); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_TEXTURE_2D); glClientActiveTexture_(GL_TEXTURE0_ARB); glActiveTexture_(GL_TEXTURE0_ARB); } glDisable(GL_BLEND); glDepthMask(GL_TRUE); glEnable(GL_CULL_FACE); } sauerbraten-0.0.20130203.dfsg/engine/bih.h0000644000175000017500000000227211543032106017553 0ustar vincentvincentstruct BIHNode { short split[2]; ushort child[2]; int axis() const { return child[0]>>14; } int childindex(int which) const { return child[which]&0x3FFF; } bool isleaf(int which) const { return (child[1]&(1<<(14+which)))!=0; } }; struct BIH { struct tri : triangle { float tc[6]; Texture *tex; }; int maxdepth; int numnodes; BIHNode *nodes; int numtris; tri *tris, *noclip; vec bbmin, bbmax; float radius; BIH(vector *t); ~BIH() { DELETEA(nodes); DELETEA(tris); } static bool triintersect(tri &t, const vec &o, const vec &ray, float maxdist, float &dist, int mode, tri *noclip); void build(vector &buildnodes, ushort *indices, int numindices, const vec &vmin, const vec &vmax, int depth = 1); bool traverse(const vec &o, const vec &ray, float maxdist, float &dist, int mode); bool traverse(const vec &o, const vec &ray, const vec &invray, float maxdist, float &dist, int mode, BIHNode *curnode, float tmin, float tmax); void preload(); }; extern bool mmintersect(const extentity &e, const vec &o, const vec &ray, float maxdist, int mode, float &dist); sauerbraten-0.0.20130203.dfsg/engine/lightning.h0000644000175000017500000000744411377352674021026 0ustar vincentvincent#define MAXLIGHTNINGSTEPS 64 #define LIGHTNINGSTEP 8 int lnjitterx[2][MAXLIGHTNINGSTEPS], lnjittery[2][MAXLIGHTNINGSTEPS]; int lnjitterframe = 0, lastlnjitter = 0; VAR(lnjittermillis, 0, 100, 1000); VAR(lnjitterradius, 0, 4, 100); FVAR(lnjitterscale, 0, 0.5f, 10); VAR(lnscrollmillis, 1, 300, 5000); FVAR(lnscrollscale, 0, 0.125f, 10); FVAR(lnblendpower, 0, 0.25f, 1000); static void calclightningjitter(int frame) { loopi(MAXLIGHTNINGSTEPS) { lnjitterx[lnjitterframe][i] = -lnjitterradius + rnd(2*lnjitterradius + 1); lnjittery[lnjitterframe][i] = -lnjitterradius + rnd(2*lnjitterradius + 1); } } static void setuplightning() { if(!lastlnjitter || lastmillis-lastlnjitter > lnjittermillis) { if(!lastlnjitter) calclightningjitter(lnjitterframe); lastlnjitter = lastmillis - (lastmillis%lnjittermillis); calclightningjitter(lnjitterframe ^= 1); } } static void renderlightning(Texture *tex, const vec &o, const vec &d, float sz) { vec step(d); step.sub(o); float len = step.magnitude(); int numsteps = clamp(int(ceil(len/LIGHTNINGSTEP)), 2, MAXLIGHTNINGSTEPS); step.div(numsteps+1); int jitteroffset = detrnd(int(d.x+d.y+d.z), MAXLIGHTNINGSTEPS); vec cur(o), up, right; up.orthogonal(step); up.normalize(); right.cross(up, step); right.normalize(); float scroll = -float(lastmillis%lnscrollmillis)/lnscrollmillis, scrollscale = lnscrollscale*(LIGHTNINGSTEP*tex->ys)/(sz*tex->xs), blend = pow(clamp(float(lastmillis - lastlnjitter)/lnjittermillis, 0.0f, 1.0f), lnblendpower), jitter0 = (1-blend)*lnjitterscale*sz/lnjitterradius, jitter1 = blend*lnjitterscale*sz/lnjitterradius; glBegin(GL_TRIANGLE_STRIP); loopj(numsteps) { vec next(cur); next.add(step); if(j+1==numsteps) next = d; else { int lj = (j+jitteroffset)%MAXLIGHTNINGSTEPS; next.add(vec(right).mul((jitter1*lnjitterx[lnjitterframe][lj] + jitter0*lnjitterx[lnjitterframe^1][lj]))); next.add(vec(up).mul((jitter1*lnjittery[lnjitterframe][lj] + jitter0*lnjittery[lnjitterframe^1][lj]))); } vec dir1 = next, dir2 = next, across; dir1.sub(cur); dir2.sub(camera1->o); across.cross(dir2, dir1).normalize().mul(sz); glTexCoord2f(scroll, 1); glVertex3f(cur.x-across.x, cur.y-across.y, cur.z-across.z); glTexCoord2f(scroll, 0); glVertex3f(cur.x+across.x, cur.y+across.y, cur.z+across.z); scroll += scrollscale; if(j+1==numsteps) { glTexCoord2f(scroll, 1); glVertex3f(next.x-across.x, next.y-across.y, next.z-across.z); glTexCoord2f(scroll, 0); glVertex3f(next.x+across.x, next.y+across.y, next.z+across.z); } cur = next; } glEnd(); } struct lightningrenderer : listrenderer { lightningrenderer() : listrenderer("packages/particles/lightning.jpg", 2, PT_LIGHTNING|PT_TRACK|PT_GLARE) {} void startrender() { glDisable(GL_CULL_FACE); } void endrender() { glEnable(GL_CULL_FACE); } void update() { setuplightning(); } void seedemitter(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int gravity) { pe.maxfade = max(pe.maxfade, fade); pe.extendbb(o, size); pe.extendbb(d, size); } void renderpart(listparticle *p, const vec &o, const vec &d, int blend, int ts, uchar *color) { blend = min(blend<<2, 255); if(type&PT_MOD) //multiply alpha into color glColor3ub((color[0]*blend)>>8, (color[1]*blend)>>8, (color[2]*blend)>>8); else glColor4ub(color[0], color[1], color[2], blend); renderlightning(tex, o, d, p->size); } }; static lightningrenderer lightnings; sauerbraten-0.0.20130203.dfsg/engine/mpr.h0000644000175000017500000004737511541232262017627 0ustar vincentvincent// This code is based off the Minkowski Portal Refinement algorithm by Gary Snethen in XenoCollide & Game Programming Gems 7. namespace mpr { struct CubePlanes { const clipplanes &p; CubePlanes(const clipplanes &p) : p(p) {} vec center() const { return p.o; } vec supportpoint(const vec &n) const { int besti = 7; float bestd = n.dot(p.v[7]); loopi(7) { float d = n.dot(p.v[i]); if(d > bestd) { besti = i; bestd = d; } } return p.v[besti]; } }; struct SolidCube { vec o; int size; SolidCube(float x, float y, float z, int size) : o(x, y, z), size(size) {} SolidCube(const vec &o, int size) : o(o), size(size) {} SolidCube(const ivec &o, int size) : o(o.tovec()), size(size) {} vec center() const { return vec(o).add(size/2); } vec supportpoint(const vec &n) const { vec p(o); if(n.x > 0) p.x += size; if(n.y > 0) p.y += size; if(n.z > 0) p.z += size; return p; } }; struct EntAABB { physent *ent; EntAABB(physent *ent) : ent(ent) {} vec center() const { vec o(ent->o); o.z += (ent->aboveeye - ent->eyeheight)/2; return o; } vec contactface(const vec &n, const vec &dir) const { vec an(n.x*dir.x < 0 ? fabs(n.x)/ent->xradius : 0, n.y*dir.y < 0 ? fabs(n.y)/ent->yradius : 0, n.z*dir.z < 0 ? fabs(n.z)*2/(ent->aboveeye + ent->eyeheight) : 0), fn(0, 0, 0); if(an.x > an.y) { if(an.x > an.z) fn.x = n.x > 0 ? 1 : -1; else if(an.z > 0) fn.z = n.z > 0 ? 1 : -1; } else if(an.y > an.z) fn.y = n.y > 0 ? 1 : -1; else if(an.z > 0) fn.z = n.z > 0 ? 1 : -1; return fn; } vec supportpoint(const vec &n) const { vec p(ent->o); if(n.x > 0) p.x += ent->xradius; else p.x -= ent->xradius; if(n.y > 0) p.y += ent->yradius; else p.y -= ent->yradius; if(n.z > 0) p.z += ent->aboveeye; else p.z -= ent->eyeheight; return p; } }; struct EntOBB { physent *ent; quat orient; float zmargin; EntOBB(physent *ent, float zmargin = 0) : ent(ent), orient(vec(0, 0, 1), ent->yaw*RAD), zmargin(zmargin) {} vec center() const { vec o(ent->o); o.z += (ent->aboveeye - ent->eyeheight - zmargin)/2; return o; } vec contactface(const vec &wn, const vec &wdir) const { vec n = orient.invertedrotate(wn).div(vec(ent->xradius, ent->yradius, (ent->aboveeye + ent->eyeheight + zmargin)/2)), dir = orient.invertedrotate(wdir), an(fabs(n.x), fabs(n.y), dir.z ? fabs(n.z) : 0), fn(0, 0, 0); if(an.x > an.y) { if(an.x > an.z) fn.x = n.x*dir.x < 0 ? (n.x > 0 ? 1 : -1) : 0; else if(an.z > 0) fn.z = n.z*dir.z < 0 ? (n.z > 0 ? 1 : -1) : 0; } else if(an.y > an.z) fn.y = n.y*dir.y < 0 ? (n.y > 0 ? 1 : -1) : 0; else if(an.z > 0) fn.z = n.z*dir.z < 0 ? (n.z > 0 ? 1 : -1) : 0; return orient.rotate(fn); } vec supportpoint(const vec &n) const { vec ln = orient.invertedrotate(n), p(0, 0, 0); if(ln.x > 0) p.x += ent->xradius; else p.x -= ent->xradius; if(ln.y > 0) p.y += ent->yradius; else p.y -= ent->yradius; if(ln.z > 0) p.z += ent->aboveeye; else p.z -= ent->eyeheight + zmargin; return orient.rotate(p).add(ent->o); } }; struct EntCylinder { physent *ent; float zmargin; EntCylinder(physent *ent, float zmargin = 0) : ent(ent), zmargin(zmargin) {} vec center() const { vec o(ent->o); o.z += (ent->aboveeye - ent->eyeheight - zmargin)/2; return o; } vec contactface(const vec &n, const vec &dir) const { float dxy = n.dot2(n)/(ent->radius*ent->radius), dz = n.z*n.z*4/(ent->aboveeye + ent->eyeheight + zmargin); vec fn(0, 0, 0); if(dz > dxy && dir.z) fn.z = n.z*dir.z < 0 ? (n.z > 0 ? 1 : -1) : 0; else if(n.dot2(dir) < 0) { fn.x = n.x; fn.y = n.y; fn.normalize(); } return fn; } vec supportpoint(const vec &n) const { vec p(ent->o); if(n.z > 0) p.z += ent->aboveeye; else p.z -= ent->eyeheight + zmargin; if(n.x || n.y) { float r = ent->radius / n.magnitude2(); p.x += n.x*r; p.y += n.y*r; } return p; } }; struct EntCapsule { physent *ent; EntCapsule(physent *ent) : ent(ent) {} vec center() const { vec o(ent->o); o.z += (ent->aboveeye - ent->eyeheight)/2; return o; } vec supportpoint(const vec &n) const { vec p(ent->o); if(n.z > 0) p.z += ent->aboveeye - ent->radius; else p.z -= ent->eyeheight - ent->radius; p.add(vec(n).mul(ent->radius / n.magnitude())); return p; } }; struct EntEllipsoid { physent *ent; EntEllipsoid(physent *ent) : ent(ent) {} vec center() const { vec o(ent->o); o.z += (ent->aboveeye - ent->eyeheight)/2; return o; } vec supportpoint(const vec &dir) const { vec p(ent->o), n = vec(dir).normalize(); p.x += ent->radius*n.x; p.y += ent->radius*n.y; p.z += (ent->aboveeye + ent->eyeheight)/2*(1 + n.z) - ent->eyeheight; return p; } }; struct ModelOBB { vec o, radius; quat orient; ModelOBB(const vec &ent, const vec ¢er, const vec &radius, float yaw) : o(ent), radius(radius), orient(vec(0, 0, 1), yaw*RAD) { o.add(orient.rotate(center)); } vec center() const { return o; } vec contactface(const vec &wn, const vec &wdir) const { vec n = orient.invertedrotate(wn).div(radius), dir = orient.invertedrotate(wdir), an(fabs(n.x), fabs(n.y), dir.z ? fabs(n.z) : 0), fn(0, 0, 0); if(an.x > an.y) { if(an.x > an.z) fn.x = n.x*dir.x < 0 ? (n.x > 0 ? 1 : -1) : 0; else if(an.z > 0) fn.z = n.z*dir.z < 0 ? (n.z > 0 ? 1 : -1) : 0; } else if(an.y > an.z) fn.y = n.y*dir.y < 0 ? (n.y > 0 ? 1 : -1) : 0; else if(an.z > 0) fn.z = n.z*dir.z < 0 ? (n.z > 0 ? 1 : -1) : 0; return orient.rotate(fn); } vec supportpoint(const vec &n) const { vec ln = orient.invertedrotate(n), p(0, 0, 0); if(ln.x > 0) p.x += radius.x; else p.x -= radius.x; if(ln.y > 0) p.y += radius.y; else p.y -= radius.y; if(ln.z > 0) p.z += radius.z; else p.z -= radius.z; return orient.rotate(p).add(o); } }; struct ModelEllipse { vec o, radius; quat orient; ModelEllipse(const vec &ent, const vec ¢er, const vec &radius, float yaw) : o(ent), radius(radius), orient(vec(0, 0, 1), yaw*RAD) { o.add(orient.rotate(center)); } vec center() const { return o; } vec contactface(const vec &wn, const vec &wdir) const { vec n = orient.invertedrotate(wn).div(radius), dir = orient.invertedrotate(wdir); float dxy = n.dot2(n), dz = n.z*n.z; vec fn(0, 0, 0); if(dz > dxy && dir.z) fn.z = n.z*dir.z < 0 ? (n.z > 0 ? 1 : -1) : 0; else if(n.dot2(dir) < 0) { fn.x = n.x*radius.x; fn.y = n.y*radius.y; fn.normalize(); } return orient.rotate(fn); } vec supportpoint(const vec &n) const { vec ln = orient.invertedrotate(n), p(0, 0, 0); if(ln.z > 0) p.z += radius.z; else p.z -= radius.z; if(ln.x || ln.y) { float r = n.magnitude2(); p.x += ln.x*radius.x/r; p.y += ln.y*radius.y/r; } return orient.rotate(p).add(o); } }; const float boundarytolerance = 1e-3f; template bool collide(const T &p1, const U &p2) { // v0 = center of Minkowski difference vec v0 = p2.center().sub(p1.center()); if(v0.iszero()) return true; // v0 and origin overlap ==> hit // v1 = support in direction of origin vec n = vec(v0).neg(); vec v1 = p2.supportpoint(n).sub(p1.supportpoint(vec(n).neg())); if(v1.dot(n) <= 0) return false; // origin outside v1 support plane ==> miss // v2 = support perpendicular to plane containing origin, v0 and v1 n.cross(v1, v0); if(n.iszero()) return true; // v0, v1 and origin colinear (and origin inside v1 support plane) == > hit vec v2 = p2.supportpoint(n).sub(p1.supportpoint(vec(n).neg())); if(v2.dot(n) <= 0) return false; // origin outside v2 support plane ==> miss // v3 = support perpendicular to plane containing v0, v1 and v2 n.cross(v0, v1, v2); // If the origin is on the - side of the plane, reverse the direction of the plane if(n.dot(v0) > 0) { swap(v1, v2); n.neg(); } /// // Phase One: Find a valid portal loopi(100) { // Obtain the next support point vec v3 = p2.supportpoint(n).sub(p1.supportpoint(vec(n).neg())); if(v3.dot(n) <= 0) return false; // origin outside v3 support plane ==> miss // If origin is outside (v1,v0,v3), then portal is invalid -- eliminate v2 and find new support outside face vec v3xv0; v3xv0.cross(v3, v0); if(v1.dot(v3xv0) < 0) { v2 = v3; n.cross(v0, v1, v3); continue; } // If origin is outside (v3,v0,v2), then portal is invalid -- eliminate v1 and find new support outside face if(v2.dot(v3xv0) > 0) { v1 = v3; n.cross(v0, v3, v2); continue; } /// // Phase Two: Refine the portal for(int j = 0;; j++) { // Compute outward facing normal of the portal n.cross(v1, v2, v3); // If the origin is inside the portal, we have a hit if(n.dot(v1) >= 0) return true; n.normalize(); // Find the support point in the direction of the portal's normal vec v4 = p2.supportpoint(n).sub(p1.supportpoint(vec(n).neg())); // If the origin is outside the support plane or the boundary is thin enough, we have a miss if(v4.dot(n) <= 0 || vec(v4).sub(v3).dot(n) <= boundarytolerance || j > 100) return false; // Test origin against the three planes that separate the new portal candidates: (v1,v4,v0) (v2,v4,v0) (v3,v4,v0) // Note: We're taking advantage of the triple product identities here as an optimization // (v1 % v4) * v0 == v1 * (v4 % v0) > 0 if origin inside (v1, v4, v0) // (v2 % v4) * v0 == v2 * (v4 % v0) > 0 if origin inside (v2, v4, v0) // (v3 % v4) * v0 == v3 * (v4 % v0) > 0 if origin inside (v3, v4, v0) vec v4xv0; v4xv0.cross(v4, v0); if(v1.dot(v4xv0) > 0) { if(v2.dot(v4xv0) > 0) v1 = v4; // Inside v1 & inside v2 ==> eliminate v1 else v3 = v4; // Inside v1 & outside v2 ==> eliminate v3 } else { if(v3.dot(v4xv0) > 0) v2 = v4; // Outside v1 & inside v3 ==> eliminate v2 else v1 = v4; // Outside v1 & outside v3 ==> eliminate v1 } } } return false; } template bool collide(const T &p1, const U &p2, vec *contactnormal, vec *contactpoint1, vec *contactpoint2) { // v0 = center of Minkowski sum vec v01 = p1.center(); vec v02 = p2.center(); vec v0 = vec(v02).sub(v01); // Avoid case where centers overlap -- any direction is fine in this case if(v0.iszero()) v0 = vec(0, 0, 1e-5f); // v1 = support in direction of origin vec n = vec(v0).neg(); vec v11 = p1.supportpoint(vec(n).neg()); vec v12 = p2.supportpoint(n); vec v1 = vec(v12).sub(v11); if(v1.dot(n) <= 0) { if(contactnormal) *contactnormal = n; return false; } // v2 - support perpendicular to v1,v0 n.cross(v1, v0); if(n.iszero()) { n = vec(v1).sub(v0); n.normalize(); if(contactnormal) *contactnormal = n; if(contactpoint1) *contactpoint1 = v11; if(contactpoint2) *contactpoint2 = v12; return true; } vec v21 = p1.supportpoint(vec(n).neg()); vec v22 = p2.supportpoint(n); vec v2 = vec(v22).sub(v21); if(v2.dot(n) <= 0) { if(contactnormal) *contactnormal = n; return false; } // Determine whether origin is on + or - side of plane (v1,v0,v2) n.cross(v0, v1, v2); ASSERT( !n.iszero() ); // If the origin is on the - side of the plane, reverse the direction of the plane if(n.dot(v0) > 0) { swap(v1, v2); swap(v11, v21); swap(v12, v22); n.neg(); } /// // Phase One: Identify a portal loopi(100) { // Obtain the support point in a direction perpendicular to the existing plane // Note: This point is guaranteed to lie off the plane vec v31 = p1.supportpoint(vec(n).neg()); vec v32 = p2.supportpoint(n); vec v3 = vec(v32).sub(v31); if(v3.dot(n) <= 0) { if(contactnormal) *contactnormal = n; return false; } // If origin is outside (v1,v0,v3), then eliminate v2 and loop vec v3xv0; v3xv0.cross(v3, v0); if(v1.dot(v3xv0) < 0) { v2 = v3; v21 = v31; v22 = v32; n.cross(v0, v1, v3); continue; } // If origin is outside (v3,v0,v2), then eliminate v1 and loop if(v2.dot(v3xv0) > 0) { v1 = v3; v11 = v31; v12 = v32; n.cross(v0, v3, v2); continue; } bool hit = false; /// // Phase Two: Refine the portal // We are now inside of a wedge... for(int j = 0;; j++) { // Compute normal of the wedge face n.cross(v1, v2, v3); // Can this happen??? Can it be handled more cleanly? if(n.iszero()) { ASSERT(0); return true; } n.normalize(); // If the origin is inside the wedge, we have a hit if(n.dot(v1) >= 0 && !hit) { if(contactnormal) *contactnormal = n; // Compute the barycentric coordinates of the origin if(contactpoint1 || contactpoint2) { float b0 = v3.scalartriple(v1, v2), b1 = v0.scalartriple(v3, v2), b2 = v3.scalartriple(v0, v1), b3 = v0.scalartriple(v2, v1), sum = b0 + b1 + b2 + b3; if(sum <= 0) { b0 = 0; b1 = n.scalartriple(v2, v3); b2 = n.scalartriple(v3, v1); b3 = n.scalartriple(v1, v2); sum = b1 + b2 + b3; } if(contactpoint1) *contactpoint1 = (vec(v01).mul(b0).add(vec(v11).mul(b1)).add(vec(v21).mul(b2)).add(vec(v31).mul(b3))).mul(1.0f/sum); if(contactpoint2) *contactpoint2 = (vec(v02).mul(b0).add(vec(v12).mul(b1)).add(vec(v22).mul(b2)).add(vec(v32).mul(b3))).mul(1.0f/sum); } // HIT!!! hit = true; } // Find the support point in the direction of the wedge face vec v41 = p1.supportpoint(vec(n).neg()); vec v42 = p2.supportpoint(n); vec v4 = vec(v42).sub(v41); // If the boundary is thin enough or the origin is outside the support plane for the newly discovered vertex, then we can terminate if(v4.dot(n) <= 0 || vec(v4).sub(v3).dot(n) <= boundarytolerance || j > 100) { if(contactnormal) *contactnormal = n; return hit; } // Test origin against the three planes that separate the new portal candidates: (v1,v4,v0) (v2,v4,v0) (v3,v4,v0) // Note: We're taking advantage of the triple product identities here as an optimization // (v1 % v4) * v0 == v1 * (v4 % v0) > 0 if origin inside (v1, v4, v0) // (v2 % v4) * v0 == v2 * (v4 % v0) > 0 if origin inside (v2, v4, v0) // (v3 % v4) * v0 == v3 * (v4 % v0) > 0 if origin inside (v3, v4, v0) vec v4xv0; v4xv0.cross(v4, v0); if(v1.dot(v4xv0) > 0) // Compute the tetrahedron dividing face d1 = (v4,v0,v1) { if(v2.dot(v4xv0) > 0) // Compute the tetrahedron dividing face d2 = (v4,v0,v2) { // Inside d1 & inside d2 ==> eliminate v1 v1 = v4; v11 = v41; v12 = v42; } else { // Inside d1 & outside d2 ==> eliminate v3 v3 = v4; v31 = v41; v32 = v42; } } else { if(v3.dot(v4xv0) > 0) // Compute the tetrahedron dividing face d3 = (v4,v0,v3) { // Outside d1 & inside d3 ==> eliminate v2 v2 = v4; v21 = v41; v22 = v42; } else { // Outside d1 & outside d3 ==> eliminate v1 v1 = v4; v11 = v41; v12 = v42; } } } } return false; } } sauerbraten-0.0.20130203.dfsg/engine/blend.cpp0000644000175000017500000006060112067722705020445 0ustar vincentvincent#include "engine.h" enum { BM_BRANCH = 0, BM_SOLID, BM_IMAGE }; struct BlendMapBranch; struct BlendMapSolid; struct BlendMapImage; struct BlendMapNode { union { BlendMapBranch *branch; BlendMapSolid *solid; BlendMapImage *image; }; void cleanup(int type); void splitsolid(uchar &type, uchar val); }; struct BlendMapBranch { uchar type[4]; BlendMapNode children[4]; ~BlendMapBranch() { loopi(4) children[i].cleanup(type[i]); } uchar shrink(BlendMapNode &child, int quadrant); }; struct BlendMapSolid { uchar val; BlendMapSolid(uchar val) : val(val) {} }; #define BM_SCALE 1 #define BM_IMAGE_SIZE 64 struct BlendMapImage { uchar data[BM_IMAGE_SIZE*BM_IMAGE_SIZE]; }; void BlendMapNode::cleanup(int type) { switch(type) { case BM_BRANCH: delete branch; break; case BM_IMAGE: delete image; break; } } #define DEFBMSOLIDS(n) n, n+1, n+2, n+3, n+4, n+5, n+6, n+7, n+8, n+9, n+10, n+11, n+12, n+13, n+14, n+15 static BlendMapSolid bmsolids[256] = { DEFBMSOLIDS(0x00), DEFBMSOLIDS(0x10), DEFBMSOLIDS(0x20), DEFBMSOLIDS(0x30), DEFBMSOLIDS(0x40), DEFBMSOLIDS(0x50), DEFBMSOLIDS(0x60), DEFBMSOLIDS(0x70), DEFBMSOLIDS(0x80), DEFBMSOLIDS(0x90), DEFBMSOLIDS(0xA0), DEFBMSOLIDS(0xB0), DEFBMSOLIDS(0xC0), DEFBMSOLIDS(0xD0), DEFBMSOLIDS(0xE0), DEFBMSOLIDS(0xF0), }; void BlendMapNode::splitsolid(uchar &type, uchar val) { cleanup(type); type = BM_BRANCH; branch = new BlendMapBranch; loopi(4) { branch->type[i] = BM_SOLID; branch->children[i].solid = &bmsolids[val]; } } uchar BlendMapBranch::shrink(BlendMapNode &child, int quadrant) { uchar childtype = type[quadrant]; child = children[quadrant]; type[quadrant] = BM_SOLID; children[quadrant].solid = &bmsolids[0]; return childtype; } struct BlendMapRoot : BlendMapNode { uchar type; BlendMapRoot() : type(BM_SOLID) { solid = &bmsolids[0xFF]; } BlendMapRoot(uchar type, const BlendMapNode &node) : BlendMapNode(node), type(type) {} void cleanup() { BlendMapNode::cleanup(type); } void shrink(int quadrant) { if(type == BM_BRANCH) { BlendMapRoot oldroot = *this; type = branch->shrink(*this, quadrant); oldroot.cleanup(); } } }; static BlendMapRoot blendmap; struct BlendMapCache { BlendMapRoot node; int scale; ivec origin; }; BlendMapCache *newblendmapcache() { return new BlendMapCache; } void freeblendmapcache(BlendMapCache *&cache) { delete cache; cache = NULL; } bool setblendmaporigin(BlendMapCache *cache, const ivec &o, int size) { if(blendmap.type!=BM_BRANCH) { cache->node = blendmap; cache->scale = worldscale-BM_SCALE; cache->origin = ivec(0, 0, 0); return cache->node.solid!=&bmsolids[0xFF]; } BlendMapBranch *bm = blendmap.branch; int bmscale = worldscale-BM_SCALE, bmsize = 1<>BM_SCALE, y = o.y>>BM_SCALE, x1 = max(x-1, 0), y1 = max(y-1, 0), x2 = min(((o.x + size + (1<>BM_SCALE) + 1, bmsize), y2 = min(((o.y + size + (1<>BM_SCALE) + 1, bmsize), diff = (x1^x2)|(y1^y2); if(diff < bmsize) while(!(diff&(1<<(bmscale-1)))) { bmscale--; int n = (((y1>>bmscale)&1)<<1) | ((x1>>bmscale)&1); if(bm->type[n]!=BM_BRANCH) { cache->node = BlendMapRoot(bm->type[n], bm->children[n]); cache->scale = bmscale; cache->origin = ivec(x1&(~0U<node.solid!=&bmsolids[0xFF]; } bm = bm->children[n].branch; } cache->node.type = BM_BRANCH; cache->node.branch = bm; cache->scale = bmscale; cache->origin = ivec(x1&(~0U<node.solid!=&bmsolids[0xFF]; } static uchar lookupblendmap(int x, int y, BlendMapBranch *bm, int bmscale) { for(;;) { bmscale--; int n = (((y>>bmscale)&1)<<1) | ((x>>bmscale)&1); switch(bm->type[n]) { case BM_SOLID: return bm->children[n].solid->val; case BM_IMAGE: return bm->children[n].image->data[(y&((1<children[n].branch; } } uchar lookupblendmap(BlendMapCache *cache, const vec &pos) { if(cache->node.type==BM_SOLID) return cache->node.solid->val; uchar vals[4], *val = vals; float bx = pos.x/(1<origin.x, ry = iy-cache->origin.y; loop(vy, 2) loop(vx, 2) { int cx = clamp(rx+vx, 0, (1<scale)-1), cy = clamp(ry+vy, 0, (1<scale)-1); if(cache->node.type==BM_IMAGE) *val++ = cache->node.image->data[cy*BM_IMAGE_SIZE + cx]; else *val++ = lookupblendmap(cx, cy, cache->node.branch, cache->scale); } float fx = bx - ix, fy = by - iy; return uchar((1-fy)*((1-fx)*vals[0] + fx*vals[1]) + fy*((1-fx)*vals[2] + fx*vals[3])); } static void fillblendmap(uchar &type, BlendMapNode &node, int size, uchar val, int x1, int y1, int x2, int y2) { if(max(x1, y1) <= 0 && min(x2, y2) >= size) { node.cleanup(type); type = BM_SOLID; node.solid = &bmsolids[val]; return; } if(type==BM_BRANCH) { size /= 2; if(y1 < size) { if(x1 < size) fillblendmap(node.branch->type[0], node.branch->children[0], size, val, x1, y1, min(x2, size), min(y2, size)); if(x2 > size) fillblendmap(node.branch->type[1], node.branch->children[1], size, val, max(x1-size, 0), y1, x2-size, min(y2, size)); } if(y2 > size) { if(x1 < size) fillblendmap(node.branch->type[2], node.branch->children[2], size, val, x1, max(y1-size, 0), min(x2, size), y2-size); if(x2 > size) fillblendmap(node.branch->type[3], node.branch->children[3], size, val, max(x1-size, 0), max(y1-size, 0), x2-size, y2-size); } loopi(4) if(node.branch->type[i]!=BM_SOLID || node.branch->children[i].solid->val!=val) return; node.cleanup(type); type = BM_SOLID; node.solid = &bmsolids[val]; return; } else if(type==BM_SOLID) { uchar oldval = node.solid->val; if(oldval==val) return; if(size > BM_IMAGE_SIZE) { node.splitsolid(type, oldval); fillblendmap(type, node, size, val, x1, y1, x2, y2); return; } type = BM_IMAGE; node.image = new BlendMapImage; memset(node.image->data, oldval, sizeof(node.image->data)); } uchar *dst = &node.image->data[y1*BM_IMAGE_SIZE + x1]; loopi(y2-y1) { memset(dst, val, x2-x1); dst += BM_IMAGE_SIZE; } } void fillblendmap(int x, int y, int w, int h, uchar val) { int bmsize = worldsize>>BM_SCALE, x1 = clamp(x, 0, bmsize), y1 = clamp(y, 0, bmsize), x2 = clamp(x+w, 0, bmsize), y2 = clamp(y+h, 0, bmsize); if(max(x1, y1) >= bmsize || min(x2, y2) <= 0 || x1>=x2 || y1>=y2) return; fillblendmap(blendmap.type, blendmap, bmsize, val, x1, y1, x2, y2); } static void invertblendmap(uchar &type, BlendMapNode &node, int size, int x1, int y1, int x2, int y2) { if(type==BM_BRANCH) { size /= 2; if(y1 < size) { if(x1 < size) invertblendmap(node.branch->type[0], node.branch->children[0], size, x1, y1, min(x2, size), min(y2, size)); if(x2 > size) invertblendmap(node.branch->type[1], node.branch->children[1], size, max(x1-size, 0), y1, x2-size, min(y2, size)); } if(y2 > size) { if(x1 < size) invertblendmap(node.branch->type[2], node.branch->children[2], size, x1, max(y1-size, 0), min(x2, size), y2-size); if(x2 > size) invertblendmap(node.branch->type[3], node.branch->children[3], size, max(x1-size, 0), max(y1-size, 0), x2-size, y2-size); } return; } else if(type==BM_SOLID) { fillblendmap(type, node, size, 255-node.solid->val, x1, y1, x2, y2); } else if(type==BM_IMAGE) { uchar *dst = &node.image->data[y1*BM_IMAGE_SIZE + x1]; loopi(y2-y1) { loopj(x2-x1) dst[j] = 255-dst[j]; dst += BM_IMAGE_SIZE; } } } void invertblendmap(int x, int y, int w, int h) { int bmsize = worldsize>>BM_SCALE, x1 = clamp(x, 0, bmsize), y1 = clamp(y, 0, bmsize), x2 = clamp(x+w, 0, bmsize), y2 = clamp(y+h, 0, bmsize); if(max(x1, y1) >= bmsize || min(x2, y2) <= 0 || x1>=x2 || y1>=y2) return; invertblendmap(blendmap.type, blendmap, bmsize, x1, y1, x2, y2); } static void optimizeblendmap(uchar &type, BlendMapNode &node) { switch(type) { case BM_IMAGE: { uint val = node.image->data[0]; val |= val<<8; val |= val<<16; for(uint *data = (uint *)node.image->data, *end = &data[sizeof(node.image->data)/sizeof(uint)]; data < end; data++) if(*data != val) return; node.cleanup(type); type = BM_SOLID; node.solid = &bmsolids[val&0xFF]; break; } case BM_BRANCH: { loopi(4) optimizeblendmap(node.branch->type[i], node.branch->children[i]); if(node.branch->type[3]!=BM_SOLID) return; uint val = node.branch->children[3].solid->val; loopi(3) if(node.branch->type[i]!=BM_SOLID || node.branch->children[i].solid->val != val) return; node.cleanup(type); type = BM_SOLID; node.solid = &bmsolids[val]; break; } } } void optimizeblendmap() { optimizeblendmap(blendmap.type, blendmap); } VARF(blendpaintmode, 0, 0, 5, { if(!blendpaintmode) stoppaintblendmap(); }); static void blitblendmap(uchar &type, BlendMapNode &node, int bmx, int bmy, int bmsize, uchar *src, int sx, int sy, int sw, int sh, int smode) { if(type==BM_BRANCH) { bmsize /= 2; if(sy < bmy + bmsize) { if(sx < bmx + bmsize) blitblendmap(node.branch->type[0], node.branch->children[0], bmx, bmy, bmsize, src, sx, sy, sw, sh, smode); if(sx + sw > bmx + bmsize) blitblendmap(node.branch->type[1], node.branch->children[1], bmx+bmsize, bmy, bmsize, src, sx, sy, sw, sh, smode); } if(sy + sh > bmy + bmsize) { if(sx < bmx + bmsize) blitblendmap(node.branch->type[2], node.branch->children[2], bmx, bmy+bmsize, bmsize, src, sx, sy, sw, sh, smode); if(sx + sw > bmx + bmsize) blitblendmap(node.branch->type[3], node.branch->children[3], bmx+bmsize, bmy+bmsize, bmsize, src, sx, sy, sw, sh, smode); } return; } if(type==BM_SOLID) { uchar val = node.solid->val; if(bmsize > BM_IMAGE_SIZE) { node.splitsolid(type, val); blitblendmap(type, node, bmx, bmy, bmsize, src, sx, sy, sw, sh, smode); return; } type = BM_IMAGE; node.image = new BlendMapImage; memset(node.image->data, val, sizeof(node.image->data)); } int x1 = clamp(sx - bmx, 0, bmsize), y1 = clamp(sy - bmy, 0, bmsize), x2 = clamp(sx+sw - bmx, 0, bmsize), y2 = clamp(sy+sh - bmy, 0, bmsize); uchar *dst = &node.image->data[y1*BM_IMAGE_SIZE + x1]; src += max(bmy - sy, 0)*sw + max(bmx - sx, 0); loopi(y2-y1) { switch(smode) { case 1: memcpy(dst, src, x2 - x1); break; case 2: loopi(x2 - x1) dst[i] = min(dst[i], src[i]); break; case 3: loopi(x2 - x1) dst[i] = max(dst[i], src[i]); break; case 4: loopi(x2 - x1) dst[i] = min(dst[i], uchar(0xFF - src[i])); break; case 5: loopi(x2 - x1) dst[i] = max(dst[i], uchar(0xFF - src[i])); break; } dst += BM_IMAGE_SIZE; src += sw; } } void blitblendmap(uchar *src, int sx, int sy, int sw, int sh, int smode) { int bmsize = worldsize>>BM_SCALE; if(max(sx, sy) >= bmsize || min(sx+sw, sy+sh) <= 0 || min(sw, sh) <= 0) return; blitblendmap(blendmap.type, blendmap, 0, 0, bmsize, src, sx, sy, sw, sh, smode); } void resetblendmap() { blendmap.cleanup(); blendmap.type = BM_SOLID; blendmap.solid = &bmsolids[0xFF]; } void enlargeblendmap() { if(blendmap.type == BM_SOLID) return; BlendMapBranch *branch = new BlendMapBranch; branch->type[0] = blendmap.type; branch->children[0] = blendmap; loopi(3) { branch->type[i+1] = BM_SOLID; branch->children[i+1].solid = &bmsolids[0xFF]; } blendmap.type = BM_BRANCH; blendmap.branch = branch; } void shrinkblendmap(int octant) { blendmap.shrink(octant&3); } void moveblendmap(uchar type, BlendMapNode &node, int size, int x, int y, int dx, int dy) { if(type == BM_BRANCH) { size /= 2; moveblendmap(node.branch->type[0], node.branch->children[0], size, x, y, dx, dy); moveblendmap(node.branch->type[1], node.branch->children[1], size, x + size, y, dx, dy); moveblendmap(node.branch->type[2], node.branch->children[2], size, x, y + size, dx, dy); moveblendmap(node.branch->type[3], node.branch->children[3], size, x + size, y + size, dx, dy); return; } else if(type == BM_SOLID) { fillblendmap(x+dx, y+dy, size, size, node.solid->val); } else if(type == BM_IMAGE) { blitblendmap(node.image->data, x+dx, y+dy, size, size, 1); } } void moveblendmap(int dx, int dy) { BlendMapRoot old = blendmap; blendmap.type = BM_SOLID; blendmap.solid = &bmsolids[0xFF]; moveblendmap(old.type, old, worldsize>>BM_SCALE, 0, 0, dx, dy); old.cleanup(); } struct BlendBrush { char *name; int w, h; uchar *data; GLuint tex; BlendBrush(const char *name, int w, int h) : name(newstring(name)), w(w), h(h), data(new uchar[w*h]), tex(0) {} ~BlendBrush() { cleanup(); delete[] name; if(data) delete[] data; } void cleanup() { if(tex) { glDeleteTextures(1, &tex); tex = 0; } } void gentex() { if(!tex) glGenTextures(1, &tex); uchar *buf = new uchar[2*w*h]; uchar *dst = buf, *src = data; loopi(h) { loopj(w) { *dst++ = 255 - *src; *dst++ = 255 - *src++; } } createtexture(tex, w, h, buf, 3, 1, GL_LUMINANCE_ALPHA); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); GLfloat border[4] = { 0, 0, 0, 0 }; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border); delete[] buf; } void reorient(bool flipx, bool flipy, bool swapxy) { uchar *rdata = new uchar[w*h]; int stridex = 1, stridey = 1; if(swapxy) stridex *= h; else stridey *= w; uchar *src = data, *dst = rdata; if(flipx) { dst += (w-1)*stridex; stridex = -stridex; } if(flipy) { dst += (h-1)*stridey; stridey = -stridey; } loopi(h) { uchar *curdst = dst; loopj(w) { *curdst = *src++; curdst += stridex; } dst += stridey; } if(swapxy) swap(w, h); delete[] data; data = rdata; if(tex) gentex(); } }; static vector brushes; static int curbrush = -1; void cleanupblendmap() { loopv(brushes) brushes[i]->cleanup(); } void clearblendbrushes() { while(brushes.length()) delete brushes.pop(); curbrush = -1; } void delblendbrush(const char *name) { loopv(brushes) if(!strcmp(brushes[i]->name, name)) { delete brushes[i]; brushes.remove(i--); } curbrush = brushes.empty() ? -1 : clamp(curbrush, 0, brushes.length()-1); } void addblendbrush(const char *name, const char *imgname) { delblendbrush(name); ImageData s; if(!loadimage(imgname, s)) { conoutf(CON_ERROR, "could not load blend brush image %s", imgname); return; } if(max(s.w, s.h) > (1<<12)) { conoutf(CON_ERROR, "blend brush image size exceeded %dx%d pixels: %s", 1<<12, 1<<12, imgname); return; } BlendBrush *brush = new BlendBrush(name, s.w, s.h); uchar *dst = brush->data, *srcrow = s.data; loopi(s.h) { for(uchar *src = srcrow, *end = &srcrow[s.w*s.bpp]; src < end; src += s.bpp) *dst++ = src[0]; srcrow += s.pitch; } brushes.add(brush); if(curbrush < 0) curbrush = 0; else if(curbrush >= brushes.length()) curbrush = brushes.length()-1; } void nextblendbrush(int *dir) { curbrush += *dir < 0 ? -1 : 1; if(brushes.empty()) curbrush = -1; else if(!brushes.inrange(curbrush)) curbrush = *dir < 0 ? brushes.length()-1 : 0; } void setblendbrush(const char *name) { loopv(brushes) if(!strcmp(brushes[i]->name, name)) { curbrush = i; break; } } void getblendbrushname(int *n) { result(brushes.inrange(*n) ? brushes[*n]->name : ""); } void curblendbrush() { intret(curbrush); } COMMAND(clearblendbrushes, ""); COMMAND(delblendbrush, "s"); COMMAND(addblendbrush, "ss"); COMMAND(nextblendbrush, "i"); COMMAND(setblendbrush, "s"); COMMAND(getblendbrushname, "i"); COMMAND(curblendbrush, ""); extern int nompedit; bool canpaintblendmap(bool brush = true, bool sel = false, bool msg = true) { if(noedit(!sel, msg) || (nompedit && multiplayer())) return false; if(!blendpaintmode) { if(msg) conoutf(CON_ERROR, "operation only allowed in blend paint mode"); return false; } if(brush && !brushes.inrange(curbrush)) { if(msg) conoutf(CON_ERROR, "no blend brush selected"); return false; } return true; } void rotateblendbrush(int *val) { if(!canpaintblendmap()) return; int numrots = *val < 0 ? 3 : clamp(*val, 1, 5); BlendBrush *brush = brushes[curbrush]; brush->reorient(numrots>=2 && numrots<=4, numrots<=2 || numrots==5, (numrots&5)==1); } COMMAND(rotateblendbrush, "i"); void paintblendmap(bool msg) { if(!canpaintblendmap(true, false, msg)) return; BlendBrush *brush = brushes[curbrush]; int x = (int)floor(clamp(worldpos.x, 0.0f, float(worldsize))/(1<w), y = (int)floor(clamp(worldpos.y, 0.0f, float(worldsize))/(1<h); blitblendmap(brush->data, x, y, brush->w, brush->h, blendpaintmode); previewblends(ivec((x-1)<w+2)<h+2)<>BM_SCALE, y1 = sel.o.y>>BM_SCALE, x2 = (sel.o.x+sel.s.x*sel.grid+(1<>BM_SCALE, y2 = (sel.o.y+sel.s.y*sel.grid+(1<>BM_SCALE; fillblendmap(x1, y1, x2-x1, y2-y1, 0xFF); previewblends(ivec(x1<>BM_SCALE, y1 = sel.o.y>>BM_SCALE, x2 = (sel.o.x+sel.s.x*sel.grid+(1<>BM_SCALE, y2 = (sel.o.y+sel.s.y*sel.grid+(1<>BM_SCALE; invertblendmap(x1, y1, x2-x1, y2-y1); previewblends(ivec(x1<>BM_SCALE, worldsize>>BM_SCALE); previewblends(ivec(0, 0, 0), ivec(worldsize, worldsize, worldsize)); } COMMAND(invertblendmap, ""); void showblendmap() { if(noedit(true) || (nompedit && multiplayer())) return; previewblends(ivec(0, 0, 0), ivec(worldsize, worldsize, worldsize)); } COMMAND(showblendmap, ""); COMMAND(optimizeblendmap, ""); ICOMMAND(clearblendmap, "", (), { if(noedit(true) || (nompedit && multiplayer())) return; resetblendmap(); showblendmap(); }); ICOMMAND(moveblendmap, "ii", (int *dx, int *dy), { if(noedit(true) || (nompedit && multiplayer())) return; if(*dx%(BM_IMAGE_SIZE<= worldsize || *dy <= -worldsize || *dy >= worldsize) resetblendmap(); else moveblendmap(*dx>>BM_SCALE, *dy>>BM_SCALE); showblendmap(); }); void renderblendbrush() { if(!blendpaintmode || !brushes.inrange(curbrush)) return; BlendBrush *brush = brushes[curbrush]; int x1 = (int)floor(clamp(worldpos.x, 0.0f, float(worldsize))/(1<w) << BM_SCALE, y1 = (int)floor(clamp(worldpos.y, 0.0f, float(worldsize))/(1<h) << BM_SCALE, x2 = x1 + (brush->w << BM_SCALE), y2 = y1 + (brush->h << BM_SCALE); if(max(x1, y1) >= worldsize || min(x2, y2) <= 0 || x1>=x2 || y1>=y2) return; if(!brush->tex) brush->gentex(); renderblendbrush(brush->tex, x1, y1, x2 - x1, y2 - y1); } bool loadblendmap(stream *f, uchar &type, BlendMapNode &node) { type = f->getchar(); switch(type) { case BM_SOLID: { int val = f->getchar(); if(val<0 || val>0xFF) return false; node.solid = &bmsolids[val]; break; } case BM_IMAGE: node.image = new BlendMapImage; if(f->read(node.image->data, sizeof(node.image->data)) != sizeof(node.image->data)) return false; break; case BM_BRANCH: node.branch = new BlendMapBranch; loopi(4) { node.branch->type[i] = BM_SOLID; node.branch->children[i].solid = &bmsolids[0xFF]; } loopi(4) if(!loadblendmap(f, node.branch->type[i], node.branch->children[i])) return false; break; default: type = BM_SOLID; node.solid = &bmsolids[0xFF]; return false; } return true; } bool loadblendmap(stream *f, int info) { resetblendmap(); return loadblendmap(f, blendmap.type, blendmap); } void saveblendmap(stream *f, uchar type, BlendMapNode &node) { f->putchar(type); switch(type) { case BM_SOLID: f->putchar(node.solid->val); break; case BM_IMAGE: f->write(node.image->data, sizeof(node.image->data)); break; case BM_BRANCH: loopi(4) saveblendmap(f, node.branch->type[i], node.branch->children[i]); break; } } void saveblendmap(stream *f) { saveblendmap(f, blendmap.type, blendmap); } uchar shouldsaveblendmap() { return blendmap.solid!=&bmsolids[0xFF] ? 1 : 0; } sauerbraten-0.0.20130203.dfsg/engine/cubeloader.cpp0000644000175000017500000003221012072672414021456 0ustar vincentvincent#include "engine.h" VAR(importcuberemip, 0, 1024, 2048); struct cubeloader { enum { DEFAULT_LIQUID = 1, DEFAULT_WALL, DEFAULT_FLOOR, DEFAULT_CEIL }; enum // block types, order matters! { C_SOLID = 0, // entirely solid cube [only specifies wtex] C_CORNER, // half full corner of a wall C_FHF, // floor heightfield using neighbour vdelta values C_CHF, // idem ceiling C_SPACE, // entirely empty cube C_SEMISOLID, // generated by mipmapping C_MAXTYPE }; struct c_sqr { uchar type; // one of the above char floor, ceil; // height, in cubes uchar wtex, ftex, ctex; // wall/floor/ceil texture ids uchar vdelta; // vertex delta, used for heightfield cubes uchar utex; // upper wall tex id }; struct c_persistent_entity // map entity { short x, y, z; // cube aligned position short attr1; uchar type; // type is one of the above uchar attr2, attr3, attr4; }; struct c_header // map file format header { char head[4]; // "CUBE" int version; // any >8bit quantity is little endian int headersize; // sizeof(header) int sfactor; // in bits int numents; char maptitle[128]; uchar texlists[3][256]; int waterlevel; int reserved[15]; }; c_sqr *world; int ssize; int x0, x1, y0, y1, z0, z1; c_sqr *o[4]; int lastremip; int progress; void create_ent(c_persistent_entity &ce) { if(ce.type>=7) ce.type++; // grenade ammo if(ce.type>=8) ce.type++; // pistol ammo if(ce.type==16) ce.type = ET_MAPMODEL; else if(ce.type>=ET_MAPMODEL && ce.type<16) ce.type++; if(ce.type>=ET_ENVMAP) ce.type++; if(ce.type>=ET_PARTICLES) ce.type++; if(ce.type>=ET_SOUND) ce.type++; if(ce.type>=ET_SPOTLIGHT) ce.type++; extentity &e = *entities::newentity(); entities::getents().add(&e); e.type = ce.type; e.spawned = false; e.inoctanode = false; e.o = vec(ce.x*4+worldsize/4, ce.y*4+worldsize/4, ce.z*4+worldsize/2); e.light.color = vec(1, 1, 1); e.light.dir = vec(0, 0, 1); e.attr1 = ce.attr1; e.attr2 = ce.attr2; switch(e.type) { case ET_MAPMODEL: e.o.z += ce.attr3*4; e.attr3 = e.attr4 = 0; break; case ET_LIGHT: e.attr1 *= 4; if(!ce.attr3 && !ce.attr4) { e.attr3 = e.attr4 = e.attr2; break; } // fall through default: e.attr3 = ce.attr3; e.attr4 = ce.attr4; break; } switch(e.type) { case ET_PLAYERSTART: case ET_MAPMODEL: case ET_GAMESPECIFIC+12: // teleport case ET_GAMESPECIFIC+13: // monster e.attr1 = (int(e.attr1)+180)%360; break; } e.attr5 = 0; } cube &getcube(int x, int y, int z) { return lookupcube(x*4+worldsize/4, y*4+worldsize/4, z*4+worldsize/2, 4); } int neighbours(c_sqr &t) { o[0] = &t; o[1] = &t+1; o[2] = &t+ssize; o[3] = &t+ssize+1; int best = 0xFFFF; loopi(4) if(o[i]->vdeltavdelta; return best; } void preprocess_cubes() // pull up heighfields to where they don't cross cube boundaries { for(;;) { bool changed = false; loop(x, ssize) { loop(y, ssize) { c_sqr &t = world[x+y*ssize]; if(t.type==C_FHF || t.type==C_CHF) { int bottom = (neighbours(t)&(~3))+4; loopj(4) if(o[j]->vdelta>bottom) { o[j]->vdelta = bottom; changed = true; } } } } if(!changed) break; } } int getfloorceil(c_sqr &s, int &floor, int &ceil) { floor = s.floor; ceil = s.ceil; int cap = 0; switch(s.type) { case C_SOLID: floor = ceil; break; case C_FHF: floor -= (cap = neighbours(s)&(~3))/4; break; case C_CHF: ceil += (cap = neighbours(s)&(~3))/4; break; } return cap; } void boundingbox() { x0 = y0 = ssize; x1 = y1 = 0; z0 = 128; z1 = -128; loop(x, ssize) loop(y, ssize) { c_sqr &t = world[x+y*ssize]; if(t.type!=C_SOLID) { if(xx1) x1 = x; if(y>y1) y1 = y; int floor, ceil; getfloorceil(t, floor, ceil); if(floorz1) z1 = ceil; } } } void hf(int x, int y, int z, int side, int dir, int cap) { cube &c = getcube(x, y, z); loopi(2) loopj(2) edgeset(cubeedge(c, 2, i, j), side, dir*(o[(j<<1)+i]->vdelta-cap)*2+side*8); } bool cornersolid(int z, c_sqr *s) { return s->type==C_SOLID || zfloor || z>=s->ceil; } void createcorner(cube &c, int lstart, int lend, int rstart, int rend) { int ledge = edgemake(lstart, lend); int redge = edgemake(rstart, rend); cubeedge(c, 1, 0, 0) = ledge; cubeedge(c, 1, 1, 0) = ledge; cubeedge(c, 1, 0, 1) = redge; cubeedge(c, 1, 1, 1) = redge; } void create_cubes() { preprocess_cubes(); boundingbox(); lastremip = allocnodes; progress = 0; for(int x = x0-1; x<=x1+1; x++) for(int y = y0-1; y<=y1+1; y++) { c_sqr &s = world[x+y*ssize]; int floor, ceil, cap = getfloorceil(s, floor, ceil); for(int z = z0-1; z<=z1+1; z++) { cube &c = getcube(x, y, z); c.texture[O_LEFT] = c.texture[O_RIGHT] = c.texture[O_BACK] = c.texture[O_FRONT] = s.type!=C_SOLID && z=floor && zfloor-1==z && bs->floor-1!=z) { c.texture[O_TOP] = ts->ftex; } else if (ts->floor-1!=z && bs->floor-1==z) { c.texture[O_TOP] = bs->ftex; } if (ts->ceil==z && bs->ceil!=z) { c.texture[O_BOTTOM] = ts->ctex; } else if (ts->ceil!=z && bs->ceil==z) { c.texture[O_BOTTOM] = bs->ctex; } } } } switch(s.type) { case C_FHF: hf(x, y, floor-1, 1, -1, cap); break; case C_CHF: hf(x, y, ceil, 0, 1, cap); break; } if(importcuberemip && (allocnodes - lastremip) * 8 > importcuberemip * 1024) { mpremip(true); lastremip = allocnodes; } if((progress++&0x7F)==0) { float bar = float((y1-y0+2)*(x-x0+1) + y-y0+1) / float((y1-y0+2)*(x1-x0+2)); defformatstring(text)("creating cubes... %d%%", int(bar*100)); renderprogress(bar, text); } } } void load_cube_world(char *mname) { int loadingstart = SDL_GetTicks(); string pakname, cgzname; formatstring(pakname)("cube/%s", mname); formatstring(cgzname)("packages/%s.cgz", pakname); stream *f = opengzfile(path(cgzname), "rb"); if(!f) { conoutf(CON_ERROR, "could not read cube map %s", cgzname); return; } c_header hdr; f->read(&hdr, sizeof(c_header)-sizeof(int)*16); lilswap(&hdr.version, 4); bool mod = false; if(strncmp(hdr.head, "CUBE", 4)) { if(!strncmp(hdr.head, "ACMP", 4)) mod = true; else { conoutf(CON_ERROR, "map %s has malformatted header", cgzname); delete f; return; } } else if(hdr.version>5) mod = true; if(hdr.version>5 && !mod) { conoutf(CON_ERROR, "map %s requires a newer version of the Cube 1 importer", cgzname); delete f; return; } if(!haslocalclients()) game::forceedit(""); emptymap(12, true, NULL); freeocta(worldroot); worldroot = newcubes(F_SOLID); defformatstring(cs)("importing %s", cgzname); renderbackground(cs); if(hdr.version>=4) { f->read(&hdr.waterlevel, sizeof(int)*16); lilswap(&hdr.waterlevel, 16); } else { hdr.waterlevel = -100000; } if(mod) f->seek(hdr.numents*sizeof(c_persistent_entity), SEEK_CUR); else loopi(hdr.numents) { c_persistent_entity e; f->read(&e, sizeof(c_persistent_entity)); lilswap(&e.x, 4); if(i < MAXENTS) create_ent(e); } ssize = 1<getchar(); switch(type) { case 255: { int n = f->getchar(); for(int i = 0; igetchar(); f->getchar(); break; } case C_SOLID: { s->type = C_SOLID; s->wtex = f->getchar(); s->vdelta = f->getchar(); if(hdr.version<=2) { f->getchar(); f->getchar(); } s->ftex = DEFAULT_FLOOR; s->ctex = DEFAULT_CEIL; s->utex = s->wtex; s->floor = 0; s->ceil = 16; break; } default: { if(type<0 || type>=C_MAXTYPE) { defformatstring(t)("%d @ %d", type, k); fatal("while reading map: type out of range: %s", t); } s->type = type; s->floor = f->getchar(); s->ceil = f->getchar(); if(s->floor>=s->ceil) s->floor = s->ceil-1; // for pre 12_13 s->wtex = f->getchar(); s->ftex = f->getchar(); s->ctex = f->getchar(); if(hdr.version<=2) { f->getchar(); f->getchar(); } s->vdelta = f->getchar(); s->utex = (hdr.version>=2) ? f->getchar() : s->wtex; if(hdr.version>=5) f->getchar(); s->type = type; } } t = s; } delete f; string cfgname; formatstring(cfgname)("packages/cube/%s.cfg", mname); identflags |= IDF_OVERRIDDEN; execfile("packages/cube/package.cfg"); execfile(path(cfgname)); identflags &= ~IDF_OVERRIDDEN; create_cubes(); mpremip(true); clearlights(); allchanged(); vector &ents = entities::getents(); loopv(ents) if(ents[i]->type!=ET_LIGHT) dropenttofloor(ents[i]); entitiesinoctanodes(); conoutf("read cube map %s (%.1f seconds)", cgzname, (SDL_GetTicks()-loadingstart)/1000.0f); startmap(NULL); } }; void importcube(char *name) { if(multiplayer()) return; cubeloader().load_cube_world(name); } COMMAND(importcube, "s"); sauerbraten-0.0.20130203.dfsg/engine/animmodel.h0000644000175000017500000016161312100047002020752 0ustar vincentvincentVARFP(lightmodels, 0, 1, 1, preloadmodelshaders()); VARFP(envmapmodels, 0, 1, 1, preloadmodelshaders()); VARFP(glowmodels, 0, 1, 1, preloadmodelshaders()); VARFP(bumpmodels, 0, 1, 1, preloadmodelshaders()); VARP(fullbrightmodels, 0, 0, 200); struct animmodel : model { struct animspec { int frame, range; float speed; int priority; }; struct animpos { int anim, fr1, fr2; float t; void setframes(const animinfo &info) { anim = info.anim; if(info.range<=1) { fr1 = 0; t = 0; } else { int time = info.anim&ANIM_SETTIME ? info.basetime : lastmillis-info.basetime; fr1 = (int)(time/info.speed); // round to full frames t = (time-fr1*info.speed)/info.speed; // progress of the frame, value from 0.0f to 1.0f } if(info.anim&ANIM_LOOP) { fr1 = fr1%info.range+info.frame; fr2 = fr1+1; if(fr2>=info.frame+info.range) fr2 = info.frame; } else { fr1 = min(fr1, info.range-1)+info.frame; fr2 = min(fr1+1, info.frame+info.range-1); } if(info.anim&ANIM_REVERSE) { fr1 = (info.frame+info.range-1)-(fr1-info.frame); fr2 = (info.frame+info.range-1)-(fr2-info.frame); } } bool operator==(const animpos &a) const { return fr1==a.fr1 && fr2==a.fr2 && (fr1==fr2 || t==a.t); } bool operator!=(const animpos &a) const { return fr1!=a.fr1 || fr2!=a.fr2 || (fr1!=fr2 && t!=a.t); } }; struct part; struct animstate { part *owner; animpos cur, prev; float interp; bool operator==(const animstate &a) const { return cur==a.cur && (interp<1 ? interp==a.interp && prev==a.prev : a.interp>=1); } bool operator!=(const animstate &a) const { return cur!=a.cur || (interp<1 ? interp!=a.interp || prev!=a.prev : a.interp<1); } }; struct linkedpart; struct mesh; struct skin { part *owner; Texture *tex, *masks, *envmap, *unlittex, *normalmap; Shader *shader; float spec, ambient, glow, glowdelta, glowpulse, specglare, glowglare, fullbright, envmapmin, envmapmax, scrollu, scrollv, alphatest; bool alphablend, cullface; skin() : owner(0), tex(notexture), masks(notexture), envmap(NULL), unlittex(NULL), normalmap(NULL), shader(NULL), spec(1.0f), ambient(0.3f), glow(3.0f), glowdelta(0), glowpulse(0), specglare(1), glowglare(1), fullbright(0), envmapmin(0), envmapmax(0), scrollu(0), scrollv(0), alphatest(0.9f), alphablend(true), cullface(true) {} bool multitextured() { return enableglow; } bool envmapped() { return hasCM && envmapmax>0 && envmapmodels && (renderpath!=R_FIXEDFUNCTION || maxtmus >= 3); } bool bumpmapped() { return renderpath!=R_FIXEDFUNCTION && normalmap && bumpmodels; } bool normals() { return renderpath!=R_FIXEDFUNCTION || (lightmodels && !fullbright) || envmapped() || bumpmapped(); } bool tangents() { return bumpmapped(); } void setuptmus(const animstate *as, bool masked) { if(fullbright) { if(enablelighting) { glDisable(GL_LIGHTING); enablelighting = false; } } else if(lightmodels && !enablelighting) { glEnable(GL_LIGHTING); enablelighting = true; if(!enablerescale) { glEnable(hasRN ? GL_RESCALE_NORMAL_EXT : GL_NORMALIZE); enablerescale = true; } } if(masked!=enableglow) lasttex = lastmasks = NULL; float mincolor = as->cur.anim&ANIM_FULLBRIGHT ? fullbrightmodels/100.0f : 0.0f; vec color = vec(lightcolor).max(mincolor), matcolor(1, 1, 1); if(masked) { bool needenvmap = envmaptmu>=0 && envmapmax>0; if(enableoverbright) disableoverbright(); if(!enableglow || enableenvmap!=needenvmap) setuptmu(0, "1 , C @ T", needenvmap ? "= Ta" : "= Ca"); int glowscale = glow>2 ? 4 : (glow>1 || mincolor>1 ? 2 : 1); matcolor.div(glowscale); glActiveTexture_(GL_TEXTURE1_ARB); if(!enableglow || enableenvmap!=needenvmap) { if(!enableglow) glEnable(GL_TEXTURE_2D); setuptmu(1, "P * T", needenvmap ? "= Pa" : "Pa * Ta"); } scaletmu(1, glowscale); glActiveTexture_(GL_TEXTURE0_ARB); enableglow = true; } else { if(enableglow) disableglow(); if(mincolor>1 && maxtmus>=1) { matcolor.div(2); if(!enableoverbright) { setuptmu(0, "C * T x 2"); enableoverbright = true; } } else if(enableoverbright) disableoverbright(); } if(fullbright) glColor4f(matcolor.x*fullbright, matcolor.y*fullbright, matcolor.z*fullbright, transparent); else if(lightmodels) { GLfloat material[4] = { matcolor.x, matcolor.y, matcolor.z, transparent }; glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, material); } else glColor4f(matcolor.x*color.x, matcolor.y*color.y, matcolor.z*color.z, transparent); if(lightmodels && !fullbright) { float ambientk = min(max(ambient, mincolor)*0.75f, 1.0f), diffusek = 1-ambientk; GLfloat ambientcol[4] = { color.x*ambientk, color.y*ambientk, color.z*ambientk, 1 }, diffusecol[4] = { color.x*diffusek, color.y*diffusek, color.z*diffusek, 1 }; float ambientmax = max(ambientcol[0], max(ambientcol[1], ambientcol[2])), diffusemax = max(diffusecol[0], max(diffusecol[1], diffusecol[2])); if(ambientmax>1e-3f) loopk(3) ambientcol[k] *= min(1.5f, 1.0f/min(ambientmax, 1.0f)); if(diffusemax>1e-3f) loopk(3) diffusecol[k] *= min(1.5f, 1.0f/min(diffusemax, 1.0f)); glLightfv(GL_LIGHT0, GL_AMBIENT, ambientcol); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffusecol); } } void setshaderparams(mesh *m, const animstate *as, bool masked) { if(fullbright) { glColor4f(fullbright/2, fullbright/2, fullbright/2, transparent); setenvparamf("lightscale", SHPARAM_VERTEX, 2, 0, 0, 2); setenvparamf("lightscale", SHPARAM_PIXEL, 2, 0, 0, 2); } else { float mincolor = as->cur.anim&ANIM_FULLBRIGHT ? fullbrightmodels/100.0f : 0.0f, bias = max(mincolor-1.0f, 0.2f), scale = 0.5f*max(0.8f-bias, 0.0f), minshade = scale*max(ambient, mincolor); vec color = vec(lightcolor).max(mincolor); glColor4f(color.x, color.y, color.z, transparent); setenvparamf("lightscale", SHPARAM_VERTEX, 2, scale - minshade, scale, minshade + bias); setenvparamf("lightscale", SHPARAM_PIXEL, 2, scale - minshade, scale, minshade + bias); } float curglow = glow; if(glowpulse > 0) { float curpulse = lastmillis*glowpulse; curpulse -= floor(curpulse); curglow += glowdelta*2*fabs(curpulse - 0.5f); } setenvparamf("maskscale", SHPARAM_PIXEL, 4, 0.5f*spec*lightmodels, 0.5f*curglow*glowmodels, 16*specglare, 4*glowglare); setenvparamf("texscroll", SHPARAM_VERTEX, 5, lastmillis/1000.0f, scrollu*lastmillis/1000.0f, scrollv*lastmillis/1000.0f); if(envmaptmu>=0 && envmapmax>0) setenvparamf("envmapscale", bumpmapped() ? SHPARAM_PIXEL : SHPARAM_VERTEX, 3, envmapmin-envmapmax, envmapmax); } Shader *loadshader(bool shouldenvmap, bool masked) { #define DOMODELSHADER(name, body) \ do { \ static Shader *name##shader = NULL; \ if(!name##shader) name##shader = useshaderbyname(#name); \ body; \ } while(0) #define LOADMODELSHADER(name) DOMODELSHADER(name, return name##shader) #define SETMODELSHADER(m, name) DOMODELSHADER(name, (m)->setshader(name##shader)) if(shader) return shader; else if(bumpmapped()) { if(shouldenvmap) { if(lightmodels && !fullbright && (masked || spec>=0.01f)) LOADMODELSHADER(bumpenvmapmodel); else LOADMODELSHADER(bumpenvmapnospecmodel); } else if(masked && lightmodels && !fullbright) LOADMODELSHADER(bumpmasksmodel); else if(masked && glowmodels) LOADMODELSHADER(bumpmasksnospecmodel); else if(spec>=0.01f && lightmodels && !fullbright) LOADMODELSHADER(bumpmodel); else LOADMODELSHADER(bumpnospecmodel); } else if(shouldenvmap) { if(lightmodels && !fullbright && (masked || spec>=0.01f)) LOADMODELSHADER(envmapmodel); else LOADMODELSHADER(envmapnospecmodel); } else if(masked && lightmodels && !fullbright) LOADMODELSHADER(masksmodel); else if(masked && glowmodels) LOADMODELSHADER(masksnospecmodel); else if(spec>=0.01f && lightmodels && !fullbright) LOADMODELSHADER(stdmodel); else LOADMODELSHADER(nospecmodel); } void preloadBIH() { if(tex && tex->type&Texture::ALPHA && !tex->alphamask) loadalphamask(tex); } void preloadshader() { bool shouldenvmap = envmapped(); if(masks->type&Texture::STUB && !strncmp(masks->name, "", 6)) { float glowscale = glow/(glow>2 ? 4 : (glow>1 ? 2 : 1)), envscale = envmapmax > 0 ? 0.2f*envmapmax + 0.8f*envmapmin : 0; defformatstring(ffmask)("", floor(glowscale*16 + 0.5f)/16, floor(envscale*16 + 0.5f)/16); masks = textureload(makerelpath(NULL, masks->name + 6, NULL, ffmask), 0, true, false); } loadshader(shouldenvmap, masks!=notexture && !(masks->type&Texture::STUB) && (lightmodels || glowmodels || shouldenvmap)); } void setshader(mesh *m, const animstate *as, bool masked) { m->setshader(loadshader(envmaptmu>=0 && envmapmax>0, masked)); } void bind(mesh *b, const animstate *as) { if(!cullface && enablecullface) { glDisable(GL_CULL_FACE); enablecullface = false; } else if(cullface && !enablecullface) { glEnable(GL_CULL_FACE); enablecullface = true; } if(as->cur.anim&ANIM_NOSKIN) { if(enablealphatest) { glDisable(GL_ALPHA_TEST); enablealphatest = false; } if(enablealphablend) { glDisable(GL_BLEND); enablealphablend = false; } if(enableglow) disableglow(); if(enableenvmap) disableenvmap(); if(enablelighting) { glDisable(GL_LIGHTING); enablelighting = false; } if(enablerescale) { glDisable(hasRN ? GL_RESCALE_NORMAL_EXT : GL_NORMALIZE); enablerescale = false; } if(shadowmapping) SETMODELSHADER(b, shadowmapcaster); else /*if(as->cur.anim&ANIM_SHADOW)*/ SETMODELSHADER(b, notexturemodel); return; } Texture *s = bumpmapped() && unlittex ? unlittex : tex, *m = masks->type&Texture::STUB ? notexture : masks, *n = bumpmapped() ? normalmap : NULL; if((renderpath==R_FIXEDFUNCTION || !lightmodels) && !glowmodels && (!envmapmodels || envmaptmu<0 || envmapmax<=0)) m = notexture; if(renderpath==R_FIXEDFUNCTION) setuptmus(as, m!=notexture); else { setshaderparams(b, as, m!=notexture); setshader(b, as, m!=notexture); } int activetmu = 0; if(s!=lasttex) { if(enableglow) { glActiveTexture_(GL_TEXTURE1_ARB); activetmu = 1; } glBindTexture(GL_TEXTURE_2D, s->id); lasttex = s; } if(n && n!=lastnormalmap) { glActiveTexture_(GL_TEXTURE3_ARB); activetmu = 3; glBindTexture(GL_TEXTURE_2D, n->id); lastnormalmap = n; } if(s->type&Texture::ALPHA) { if(alphablend) { if(!enablealphablend && !reflecting && !refracting) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); enablealphablend = true; } } else if(enablealphablend) { glDisable(GL_BLEND); enablealphablend = false; } if(alphatest>0) { if(!enablealphatest) { glEnable(GL_ALPHA_TEST); enablealphatest = true; } if(lastalphatest!=alphatest) { glAlphaFunc(GL_GREATER, alphatest); lastalphatest = alphatest; } } else if(enablealphatest) { glDisable(GL_ALPHA_TEST); enablealphatest = false; } } else { if(enablealphatest) { glDisable(GL_ALPHA_TEST); enablealphatest = false; } if(enablealphablend && transparent>=1) { glDisable(GL_BLEND); enablealphablend = false; } } if(m!=lastmasks && m!=notexture) { if(!enableglow) { glActiveTexture_(GL_TEXTURE1_ARB); activetmu = 1; } else if(activetmu != 0) { glActiveTexture_(GL_TEXTURE0_ARB); activetmu = 0; } glBindTexture(GL_TEXTURE_2D, m->id); lastmasks = m; } if((renderpath!=R_FIXEDFUNCTION || m!=notexture) && envmaptmu>=0 && envmapmax>0) { GLuint emtex = envmap ? envmap->id : closestenvmaptex; if(!enableenvmap || lastenvmaptex!=emtex) { glActiveTexture_(GL_TEXTURE0_ARB+envmaptmu); activetmu = envmaptmu; if(!enableenvmap) { glEnable(GL_TEXTURE_CUBE_MAP_ARB); if(!lastenvmaptex && renderpath==R_FIXEDFUNCTION) { glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glEnable(GL_TEXTURE_GEN_R); } enableenvmap = true; if(!enablerescale) { glEnable(hasRN ? GL_RESCALE_NORMAL_EXT : GL_NORMALIZE); enablerescale = true; } } if(lastenvmaptex!=emtex) { glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, emtex); lastenvmaptex = emtex; } } } else if(enableenvmap) { disableenvmap(); activetmu = 0; } if(activetmu != 0) glActiveTexture_(GL_TEXTURE0_ARB); } }; struct meshgroup; struct mesh { meshgroup *group; char *name; bool noclip; mesh() : group(NULL), name(NULL), noclip(false) { } virtual ~mesh() { DELETEA(name); } virtual void calcbb(int frame, vec &bbmin, vec &bbmax, const matrix3x4 &m) {} virtual void gentris(int frame, Texture *tex, vector *out, const matrix3x4 &m) {} virtual void setshader(Shader *s) { if(glaring) s->setvariant(0, 2); else s->set(); } template void smoothnorms(V *verts, int numverts, T *tris, int numtris, float limit, bool areaweight) { hashtable share; int *next = new int[numverts]; memset(next, -1, numverts*sizeof(int)); loopi(numverts) { V &v = verts[i]; v.norm = vec(0, 0, 0); int idx = share.access(v.pos, i); if(idx != i) { next[i] = next[idx]; next[idx] = i; } } loopi(numtris) { T &t = tris[i]; V &v1 = verts[t.vert[0]], &v2 = verts[t.vert[1]], &v3 = verts[t.vert[2]]; vec norm; norm.cross(vec(v2.pos).sub(v1.pos), vec(v3.pos).sub(v1.pos)); if(!areaweight) norm.normalize(); v1.norm.add(norm); v2.norm.add(norm); v3.norm.add(norm); } vec *norms = new vec[numverts]; memset(norms, 0, numverts*sizeof(vec)); loopi(numverts) { V &v = verts[i]; norms[i].add(v.norm); if(next[i] >= 0) { float vlimit = limit*v.norm.magnitude(); for(int j = next[i]; j >= 0; j = next[j]) { V &o = verts[j]; if(v.norm.dot(o.norm) >= vlimit*o.norm.magnitude()) { norms[i].add(o.norm); norms[j].add(v.norm); } } } } loopi(numverts) verts[i].norm = norms[i].normalize(); delete[] next; delete[] norms; } template void buildnorms(V *verts, int numverts, T *tris, int numtris, bool areaweight) { loopi(numverts) verts[i].norm = vec(0, 0, 0); loopi(numtris) { T &t = tris[i]; V &v1 = verts[t.vert[0]], &v2 = verts[t.vert[1]], &v3 = verts[t.vert[2]]; vec norm; norm.cross(vec(v2.pos).sub(v1.pos), vec(v3.pos).sub(v1.pos)); if(!areaweight) norm.normalize(); v1.norm.add(norm); v2.norm.add(norm); v3.norm.add(norm); } loopi(numverts) verts[i].norm.normalize(); } template void calctangents(B *bumpverts, V *verts, TC *tcverts, int numverts, T *tris, int numtris, bool areaweight) { vec *tangent = new vec[2*numverts], *bitangent = tangent+numverts; memset(tangent, 0, 2*numverts*sizeof(vec)); loopi(numtris) { const T &t = tris[i]; const vec &e0 = verts[t.vert[0]].pos; vec e1 = vec(verts[t.vert[1]].pos).sub(e0), e2 = vec(verts[t.vert[2]].pos).sub(e0); const TC &tc0 = tcverts[t.vert[0]], &tc1 = tcverts[t.vert[1]], &tc2 = tcverts[t.vert[2]]; float u1 = tc1.u - tc0.u, v1 = tc1.v - tc0.v, u2 = tc2.u - tc0.u, v2 = tc2.v - tc0.v; vec u(e2), v(e2); u.mul(v1).sub(vec(e1).mul(v2)); v.mul(u1).sub(vec(e1).mul(u2)); if(vec().cross(e2, e1).dot(vec().cross(v, u)) >= 0) { u.neg(); v.neg(); } if(!areaweight) { u.normalize(); v.normalize(); } loopj(3) { tangent[t.vert[j]].sub(u); bitangent[t.vert[j]].add(v); } } loopi(numverts) { const vec &n = verts[i].norm, &t = tangent[i], &bt = bitangent[i]; B &bv = bumpverts[i]; (bv.tangent = t).sub(vec(n).mul(n.dot(t))).normalize(); bv.bitangent = vec().cross(n, t).dot(bt) < 0 ? -1 : 1; } delete[] tangent; } }; struct meshgroup { meshgroup *next; int shared; char *name; vector meshes; meshgroup() : next(NULL), shared(0), name(NULL) { } virtual ~meshgroup() { DELETEA(name); meshes.deletecontents(); DELETEP(next); } virtual int findtag(const char *name) { return -1; } virtual void concattagtransform(part *p, int frame, int i, const matrix3x4 &m, matrix3x4 &n) {} void calcbb(int frame, vec &bbmin, vec &bbmax, const matrix3x4 &m) { loopv(meshes) meshes[i]->calcbb(frame, bbmin, bbmax, m); } void gentris(int frame, vector &skins, vector *tris, const matrix3x4 &m) { loopv(meshes) meshes[i]->gentris(frame, skins[i].tex && skins[i].tex->type&Texture::ALPHA ? skins[i].tex : NULL, tris, m); } virtual int totalframes() const { return 1; } bool hasframe(int i) const { return i>=0 && i=0 && i+n<=totalframes(); } int clipframes(int i, int n) const { return min(n, totalframes() - i); } virtual void cleanup() {} virtual void preload(part *p) {} virtual void render(const animstate *as, float pitch, const vec &axis, const vec &forward, dynent *d, part *p) {} }; virtual meshgroup *loadmeshes(const char *name, va_list args) { return NULL; } meshgroup *sharemeshes(const char *name, ...) { static hashtable meshgroups; if(!meshgroups.access(name)) { va_list args; va_start(args, name); meshgroup *group = loadmeshes(name, args); va_end(args); if(!group) return NULL; meshgroups[group->name] = group; } return meshgroups[name]; } struct linkedpart { part *p; int tag, anim, basetime; vec translate; vec *pos; glmatrixf matrix; linkedpart() : p(NULL), tag(-1), anim(-1), basetime(0), translate(0, 0, 0), pos(NULL) {} }; struct part { animmodel *model; int index; meshgroup *meshes; vector links; vector skins; vector *anims[MAXANIMPARTS]; int numanimparts; float pitchscale, pitchoffset, pitchmin, pitchmax; vec translate; part() : meshes(NULL), numanimparts(1), pitchscale(1), pitchoffset(0), pitchmin(0), pitchmax(0), translate(0, 0, 0) { loopk(MAXANIMPARTS) anims[k] = NULL; } virtual ~part() { loopk(MAXANIMPARTS) DELETEA(anims[k]); } virtual void cleanup() { if(meshes) meshes->cleanup(); } void calcbb(int frame, vec &bbmin, vec &bbmax, const matrix3x4 &m) { matrix3x4 t = m; t.translate(translate); t.scale(model->scale); meshes->calcbb(frame, bbmin, bbmax, t); loopv(links) { matrix3x4 n; meshes->concattagtransform(this, frame, links[i].tag, m, n); n.transformedtranslate(links[i].translate, model->scale); links[i].p->calcbb(frame, bbmin, bbmax, n); } } void gentris(int frame, vector *tris, const matrix3x4 &m) { matrix3x4 t = m; t.translate(translate); t.scale(model->scale); meshes->gentris(frame, skins, tris, t); loopv(links) { matrix3x4 n; meshes->concattagtransform(this, frame, links[i].tag, m, n); n.transformedtranslate(links[i].translate, model->scale); links[i].p->gentris(frame, tris, n); } } bool link(part *p, const char *tag, const vec &translate = vec(0, 0, 0), int anim = -1, int basetime = 0, vec *pos = NULL) { int i = meshes ? meshes->findtag(tag) : -1; if(i<0) { loopv(links) if(links[i].p && links[i].p->link(p, tag, translate, anim, basetime, pos)) return true; return false; } linkedpart &l = links.add(); l.p = p; l.tag = i; l.anim = anim; l.basetime = basetime; l.translate = translate; l.pos = pos; return true; } bool unlink(part *p) { loopvrev(links) if(links[i].p==p) { links.remove(i, 1); return true; } loopv(links) if(links[i].p && links[i].p->unlink(p)) return true; return false; } void initskins(Texture *tex = notexture, Texture *masks = notexture, int limit = 0) { if(!limit) { if(!meshes) return; limit = meshes->meshes.length(); } while(skins.length() < limit) { skin &s = skins.add(); s.owner = this; s.tex = tex; s.masks = masks; } } void preloadBIH() { loopv(skins) skins[i].preloadBIH(); } void preloadshaders() { loopv(skins) skins[i].preloadshader(); } void preloadmeshes() { if(meshes) meshes->preload(this); } virtual void getdefaultanim(animinfo &info, int anim, uint varseed, dynent *d) { info.frame = 0; info.range = 1; } bool calcanim(int animpart, int anim, int basetime, int basetime2, dynent *d, int interp, animinfo &info, int &aitime) { uint varseed = uint((size_t)d); info.anim = anim; info.basetime = basetime; info.varseed = varseed; info.speed = anim&ANIM_SETSPEED ? basetime2 : 100.0f; if((anim&ANIM_INDEX)==ANIM_ALL) { info.frame = 0; info.range = meshes->totalframes(); } else { animspec *spec = NULL; if(anims[animpart]) { vector &primary = anims[animpart][anim&ANIM_INDEX]; if(&primary < &anims[animpart][NUMANIMS] && primary.length()) spec = &primary[uint(varseed + basetime)%primary.length()]; if((anim>>ANIM_SECONDARY)&(ANIM_INDEX|ANIM_DIR)) { vector &secondary = anims[animpart][(anim>>ANIM_SECONDARY)&ANIM_INDEX]; if(&secondary < &anims[animpart][NUMANIMS] && secondary.length()) { animspec &spec2 = secondary[uint(varseed + basetime2)%secondary.length()]; if(!spec || spec2.priority > spec->priority) { spec = &spec2; info.anim >>= ANIM_SECONDARY; info.basetime = basetime2; } } } } if(spec) { info.frame = spec->frame; info.range = spec->range; if(spec->speed>0) info.speed = 1000.0f/spec->speed; } else getdefaultanim(info, anim, uint(varseed + info.basetime), d); } info.anim &= (1<hasframes(info.frame, info.range)) { if(!meshes->hasframe(info.frame)) return false; info.range = meshes->clipframes(info.frame, info.range); } if(d && interp>=0) { animinterpinfo &ai = d->animinterp[interp]; if((info.anim&ANIM_CLAMP)==ANIM_CLAMP) aitime = min(aitime, int(info.range*info.speed*0.5e-3f)); if(d->ragdoll && !(anim&ANIM_RAGDOLL)) { ai.prev.range = ai.cur.range = 0; ai.lastswitch = -1; } else if(ai.lastmodel!=this || ai.lastswitch<0 || lastmillis-d->lastrendered>aitime) { ai.prev = ai.cur = info; ai.lastswitch = lastmillis-aitime*2; } else if(ai.cur!=info) { if(lastmillis-ai.lastswitch>aitime/2) ai.prev = ai.cur; ai.cur = info; ai.lastswitch = lastmillis; } else if(info.anim&ANIM_SETTIME) ai.cur.basetime = info.basetime; ai.lastmodel = this; } return true; } void render(int anim, int basetime, int basetime2, float pitch, const vec &axis, const vec &forward, dynent *d) { animstate as[MAXANIMPARTS]; render(anim, basetime, basetime2, pitch, axis, forward, d, as); } void render(int anim, int basetime, int basetime2, float pitch, const vec &axis, const vec &forward, dynent *d, animstate *as) { if(!(anim&ANIM_REUSE)) loopi(numanimparts) { animinfo info; int interp = d && index+numanimparts<=MAXANIMPARTS ? index+i : -1, aitime = animationinterpolationtime; if(!calcanim(i, anim, basetime, basetime2, d, interp, info, aitime)) return; animstate &p = as[i]; p.owner = this; p.cur.setframes(info); p.interp = 1; if(interp>=0 && d->animinterp[interp].prev.range>0) { int diff = lastmillis-d->animinterp[interp].lastswitch; if(diffaniminterp[interp].prev); p.interp = diff/float(aitime); } } } vec oaxis, oforward; matrixstack[matrixpos].transposedtransformnormal(axis, oaxis); float pitchamount = pitchscale*pitch + pitchoffset; if(pitchmin || pitchmax) pitchamount = clamp(pitchamount, pitchmin, pitchmax); if(as->cur.anim&ANIM_NOPITCH || (as->interp < 1 && as->prev.anim&ANIM_NOPITCH)) pitchamount *= (as->cur.anim&ANIM_NOPITCH ? 0 : as->interp) + (as->interp < 1 && as->prev.anim&ANIM_NOPITCH ? 0 : 1-as->interp); if(pitchamount) { ++matrixpos; matrixstack[matrixpos] = matrixstack[matrixpos-1]; matrixstack[matrixpos].rotate(pitchamount*RAD, oaxis); } matrixstack[matrixpos].transposedtransformnormal(forward, oforward); if(!(anim&ANIM_NORENDER)) { glPushMatrix(); glMultMatrixf(matrixstack[matrixpos].v); if(model->scale!=1) glScalef(model->scale, model->scale, model->scale); if(!translate.iszero()) glTranslatef(translate.x, translate.y, translate.z); if(renderpath!=R_FIXEDFUNCTION && envmaptmu>=0) { glMatrixMode(GL_TEXTURE); glLoadMatrixf(matrixstack[matrixpos].v); glMatrixMode(GL_MODELVIEW); } } if(!(anim&(ANIM_NOSKIN|ANIM_NORENDER))) { if(renderpath!=R_FIXEDFUNCTION) { vec odir, ocampos; matrixstack[matrixpos].transposedtransformnormal(lightdir, odir); setenvparamf("lightdir", SHPARAM_VERTEX, 0, odir.x, odir.y, odir.z); setenvparamf("lightdir", SHPARAM_PIXEL, 0, odir.x, odir.y, odir.z); matrixstack[matrixpos].transposedtransform(camera1->o, ocampos); ocampos.div(model->scale).sub(translate); setenvparamf("camera", SHPARAM_VERTEX, 1, ocampos.x, ocampos.y, ocampos.z, 1); } } meshes->render(as, pitch, oaxis, oforward, d, this); if(!(anim&ANIM_NORENDER)) { glPopMatrix(); } if(!(anim&ANIM_REUSE)) { loopv(links) { linkedpart &link = links[i]; link.matrix.transformedtranslate(links[i].translate, model->scale); matrixpos++; matrixstack[matrixpos].mul(matrixstack[matrixpos-1], link.matrix); if(link.pos) *link.pos = matrixstack[matrixpos].gettranslation(); if(!link.p) { matrixpos--; continue; } int nanim = anim, nbasetime = basetime, nbasetime2 = basetime2; if(link.anim>=0) { nanim = link.anim | (anim&ANIM_FLAGS); nbasetime = link.basetime; nbasetime2 = 0; } link.p->render(nanim, nbasetime, nbasetime2, pitch, axis, forward, d); matrixpos--; } } if(pitchamount) matrixpos--; } void setanim(int animpart, int num, int frame, int range, float speed, int priority = 0) { if(animpart<0 || animpart>=MAXANIMPARTS) return; if(frame<0 || range<=0 || !meshes || !meshes->hasframes(frame, range)) { conoutf("invalid frame %d, range %d in model %s", frame, range, model->loadname); return; } if(!anims[animpart]) anims[animpart] = new vector[NUMANIMS]; animspec &spec = anims[animpart][num].add(); spec.frame = frame; spec.range = range; spec.speed = speed; spec.priority = priority; } }; enum { LINK_TAG = 0, LINK_COOP, LINK_REUSE }; virtual int linktype(animmodel *m) const { return LINK_TAG; } void render(int anim, int basetime, int basetime2, float pitch, const vec &axis, const vec &forward, dynent *d, modelattach *a) { if(!loaded) return; int numtags = 0; if(a) { int index = parts.last()->index + parts.last()->numanimparts; for(int i = 0; a[i].tag; i++) { numtags++; animmodel *m = (animmodel *)a[i].m; if(!m || !m->loaded) { if(a[i].pos) link(NULL, a[i].tag, vec(0, 0, 0), 0, 0, a[i].pos); continue; } part *p = m->parts[0]; switch(linktype(m)) { case LINK_TAG: p->index = link(p, a[i].tag, vec(0, 0, 0), a[i].anim, a[i].basetime, a[i].pos) ? index : -1; break; case LINK_COOP: p->index = index; break; default: continue; } index += p->numanimparts; } } animstate as[MAXANIMPARTS]; parts[0]->render(anim, basetime, basetime2, pitch, axis, forward, d, as); if(a) for(int i = numtags-1; i >= 0; i--) { animmodel *m = (animmodel *)a[i].m; if(!m || !m->loaded) { if(a[i].pos) unlink(NULL); continue; } part *p = m->parts[0]; switch(linktype(m)) { case LINK_TAG: if(p->index >= 0) unlink(p); p->index = 0; break; case LINK_COOP: p->render(anim, basetime, basetime2, pitch, axis, forward, d); p->index = 0; break; case LINK_REUSE: p->render(anim | ANIM_REUSE, basetime, basetime2, pitch, axis, forward, d, as); break; } } } void render(int anim, int basetime, int basetime2, const vec &o, float yaw, float pitch, dynent *d, modelattach *a, const vec &color, const vec &dir, float trans) { if(!loaded) return; yaw += spinyaw*lastmillis/1000.0f; pitch += offsetpitch + spinpitch*lastmillis/1000.0f; vec axis(0, -1, 0), forward(1, 0, 0); matrixpos = 0; matrixstack[0].identity(); if(!d || !d->ragdoll || anim&ANIM_RAGDOLL) { matrixstack[0].translate(o); matrixstack[0].rotate_around_z(yaw*RAD); matrixstack[0].transformnormal(vec(axis), axis); matrixstack[0].transformnormal(vec(forward), forward); if(offsetyaw) matrixstack[0].rotate_around_z(offsetyaw*RAD); } else pitch = 0; if(anim&ANIM_NORENDER) { render(anim, basetime, basetime2, pitch, axis, forward, d, a); if(d) d->lastrendered = lastmillis; return; } if(!(anim&ANIM_NOSKIN)) { if(renderpath==R_FIXEDFUNCTION && lightmodels) { GLfloat pos[4] = { dir.x*1000, dir.y*1000, dir.z*1000, 0 }; glLightfv(GL_LIGHT0, GL_POSITION, pos); } transparent = trans; lightdir = dir; lightcolor = color; if(envmapped()) envmaptmu = 2; else if(a) for(int i = 0; a[i].tag; i++) if(a[i].m && a[i].m->envmapped()) { envmaptmu = 2; break; } if(envmaptmu>=0) closestenvmaptex = lookupenvmap(closestenvmap(o)); } if(depthoffset && !enabledepthoffset) { enablepolygonoffset(GL_POLYGON_OFFSET_FILL); enabledepthoffset = true; } if(envmaptmu>=0) { if(renderpath==R_FIXEDFUNCTION) { glActiveTexture_(GL_TEXTURE0_ARB+envmaptmu); setuptmu(envmaptmu, "T , P @ Pa", hasTEX || hasTE4 ? "Ca * $1a" : "= Ca"); glMatrixMode(GL_TEXTURE); glLoadMatrixf(envmatrix.v); glMatrixMode(GL_MODELVIEW); glActiveTexture_(GL_TEXTURE0_ARB); } else { setenvparamf("lightdirworld", SHPARAM_PIXEL, 1, dir.x, dir.y, dir.z); } } if(transparent<1) { if(anim&ANIM_GHOST) { glDepthFunc(GL_GREATER); glDepthMask(GL_FALSE); } else if(alphadepth) { glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); render(anim|ANIM_NOSKIN, basetime, basetime2, pitch, axis, forward, d, a); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, fading ? GL_FALSE : GL_TRUE); glDepthFunc(GL_LEQUAL); } if(!enablealphablend) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); enablealphablend = true; } } render(anim, basetime, basetime2, pitch, axis, forward, d, a); if(envmaptmu>=0) { if(renderpath==R_FIXEDFUNCTION) glActiveTexture_(GL_TEXTURE0_ARB+envmaptmu); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); if(renderpath==R_FIXEDFUNCTION) glActiveTexture_(GL_TEXTURE0_ARB); } if(transparent<1 && (alphadepth || anim&ANIM_GHOST)) { glDepthFunc(GL_LESS); if(anim&ANIM_GHOST) glDepthMask(GL_TRUE); } if(d) d->lastrendered = lastmillis; } bool loaded; char *loadname; vector parts; animmodel(const char *name) : loaded(false) { loadname = newstring(name); } virtual ~animmodel() { delete[] loadname; parts.deletecontents(); } const char *name() const { return loadname; } void cleanup() { loopv(parts) parts[i]->cleanup(); enablelight0 = false; } void initmatrix(matrix3x4 &m) { m.identity(); if(offsetyaw) m.rotate_around_z(offsetyaw*RAD); if(offsetpitch) m.rotate_around_y(-offsetpitch*RAD); } void gentris(int frame, vector *tris) { if(parts.empty()) return; matrix3x4 m; initmatrix(m); parts[0]->gentris(frame, tris, m); } void preloadBIH() { model::preloadBIH(); if(bih) loopv(parts) parts[i]->preloadBIH(); } BIH *setBIH() { if(bih) return bih; vector tris[2]; gentris(0, tris); bih = new BIH(tris); return bih; } bool link(part *p, const char *tag, const vec &translate = vec(0, 0, 0), int anim = -1, int basetime = 0, vec *pos = NULL) { if(parts.empty()) return false; return parts[0]->link(p, tag, translate, anim, basetime, pos); } bool unlink(part *p) { if(parts.empty()) return false; return parts[0]->unlink(p); } bool envmapped() { loopv(parts) loopvj(parts[i]->skins) if(parts[i]->skins[j].envmapped()) return true; return false; } virtual bool loaddefaultparts() { return true; } void preloadshaders() { loopv(parts) parts[i]->preloadshaders(); } void preloadmeshes() { loopv(parts) parts[i]->preloadmeshes(); } void setshader(Shader *shader) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].shader = shader; } void setenvmap(float envmapmin, float envmapmax, Texture *envmap) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) { skin &s = parts[i]->skins[j]; if(envmapmax) { s.envmapmin = envmapmin; s.envmapmax = envmapmax; } if(envmap) s.envmap = envmap; } } void setspec(float spec) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].spec = spec; } void setambient(float ambient) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].ambient = ambient; } void setglow(float glow, float delta, float pulse) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) { skin &s = parts[i]->skins[j]; s.glow = glow; s.glowdelta = delta; s.glowpulse = pulse; } } void setglare(float specglare, float glowglare) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) { skin &s = parts[i]->skins[j]; s.specglare = specglare; s.glowglare = glowglare; } } void setalphatest(float alphatest) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].alphatest = alphatest; } void setalphablend(bool alphablend) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].alphablend = alphablend; } void setfullbright(float fullbright) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].fullbright = fullbright; } void setcullface(bool cullface) { if(parts.empty()) loaddefaultparts(); loopv(parts) loopvj(parts[i]->skins) parts[i]->skins[j].cullface = cullface; } void calcbb(int frame, vec ¢er, vec &radius) { if(parts.empty()) return; vec bbmin(1e16f, 1e16f, 1e16f), bbmax(-1e16f, -1e16f, -1e16f); matrix3x4 m; initmatrix(m); parts[0]->calcbb(frame, bbmin, bbmax, m); radius = bbmax; radius.sub(bbmin); radius.mul(0.5f); center = bbmin; center.add(radius); } static bool enabletc, enablemtc, enablealphatest, enablealphablend, enableenvmap, enableglow, enableoverbright, enablelighting, enablelight0, enablecullface, enablenormals, enabletangents, enablebones, enablerescale, enabledepthoffset; static vec lightdir, lightcolor; static float transparent, lastalphatest; static void *lastvbuf, *lasttcbuf, *lastmtcbuf, *lastnbuf, *lastxbuf, *lastbbuf, *lastsdata, *lastbdata; static GLuint lastebuf, lastenvmaptex, closestenvmaptex; static Texture *lasttex, *lastmasks, *lastnormalmap; static int envmaptmu, matrixpos; static glmatrixf matrixstack[64]; void startrender() { enabletc = enablemtc = enablealphatest = enablealphablend = enableenvmap = enableglow = enableoverbright = enablelighting = enablenormals = enabletangents = enablebones = enablerescale = enabledepthoffset = false; enablecullface = true; lastalphatest = -1; lastvbuf = lasttcbuf = lastmtcbuf = lastxbuf = lastnbuf = lastbbuf = lastsdata = lastbdata = NULL; lastebuf = lastenvmaptex = closestenvmaptex = 0; lasttex = lastmasks = lastnormalmap = NULL; envmaptmu = -1; transparent = 1; if(renderpath==R_FIXEDFUNCTION && lightmodels && !enablelight0) { glEnable(GL_LIGHT0); static const GLfloat zero[4] = { 0, 0, 0, 0 }; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, zero); glLightfv(GL_LIGHT0, GL_SPECULAR, zero); glMaterialfv(GL_FRONT, GL_SPECULAR, zero); glMaterialfv(GL_FRONT, GL_EMISSION, zero); enablelight0 = true; } } static void disablebones() { glDisableVertexAttribArray_(6); glDisableVertexAttribArray_(7); enablebones = false; } static void disabletangents() { glDisableVertexAttribArray_(1); enabletangents = false; } static void disablemtc() { glClientActiveTexture_(GL_TEXTURE1_ARB); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glClientActiveTexture_(GL_TEXTURE0_ARB); enablemtc = false; } static void disabletc() { glDisableClientState(GL_TEXTURE_COORD_ARRAY); if(enablemtc) disablemtc(); enabletc = false; } static void disablenormals() { glDisableClientState(GL_NORMAL_ARRAY); enablenormals = false; } static void disablevbo() { if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); if(enabletc) disabletc(); if(enablenormals) disablenormals(); if(enabletangents) disabletangents(); if(enablebones) disablebones(); lastvbuf = lasttcbuf = lastmtcbuf = lastxbuf = lastnbuf = lastbbuf = NULL; lastebuf = 0; } static void disableoverbright() { resettmu(0); enableoverbright = false; } static void disableglow() { resettmu(0); glActiveTexture_(GL_TEXTURE1_ARB); resettmu(1); glDisable(GL_TEXTURE_2D); glActiveTexture_(GL_TEXTURE0_ARB); lasttex = lastmasks = NULL; enableglow = false; } static void disableenvmap(bool cleanup = false) { glActiveTexture_(GL_TEXTURE0_ARB+envmaptmu); if(enableenvmap) glDisable(GL_TEXTURE_CUBE_MAP_ARB); if(cleanup && renderpath==R_FIXEDFUNCTION) { resettmu(envmaptmu); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_R); } glActiveTexture_(GL_TEXTURE0_ARB); enableenvmap = false; } void endrender() { if(lastvbuf || lastebuf) disablevbo(); if(enablealphatest) glDisable(GL_ALPHA_TEST); if(enablealphablend) glDisable(GL_BLEND); if(enableglow) disableglow(); if(enableoverbright) disableoverbright(); if(enablelighting) glDisable(GL_LIGHTING); if(lastenvmaptex) disableenvmap(true); if(enablerescale) glDisable(hasRN ? GL_RESCALE_NORMAL_EXT : GL_NORMALIZE); if(!enablecullface) glEnable(GL_CULL_FACE); if(enabledepthoffset) disablepolygonoffset(GL_POLYGON_OFFSET_FILL); } }; bool animmodel::enabletc = false, animmodel::enablemtc = false, animmodel::enablealphatest = false, animmodel::enablealphablend = false, animmodel::enableenvmap = false, animmodel::enableglow = false, animmodel::enableoverbright = false, animmodel::enablelighting = false, animmodel::enablelight0 = false, animmodel::enablecullface = true, animmodel::enablenormals = false, animmodel::enabletangents = false, animmodel::enablebones = false, animmodel::enablerescale = false, animmodel::enabledepthoffset = false; vec animmodel::lightdir(0, 0, 1), animmodel::lightcolor(1, 1, 1); float animmodel::transparent = 1, animmodel::lastalphatest = -1; void *animmodel::lastvbuf = NULL, *animmodel::lasttcbuf = NULL, *animmodel::lastmtcbuf = NULL, *animmodel::lastnbuf = NULL, *animmodel::lastxbuf = NULL, *animmodel::lastbbuf = NULL, *animmodel::lastsdata = NULL, *animmodel::lastbdata = NULL; GLuint animmodel::lastebuf = 0, animmodel::lastenvmaptex = 0, animmodel::closestenvmaptex = 0; Texture *animmodel::lasttex = NULL, *animmodel::lastmasks = NULL, *animmodel::lastnormalmap = NULL; int animmodel::envmaptmu = -1, animmodel::matrixpos = 0; glmatrixf animmodel::matrixstack[64]; template struct modelloader { static MDL *loading; static string dir; static bool animated() { return true; } static bool multiparted() { return true; } static bool multimeshed() { return true; } }; template MDL *modelloader::loading = NULL; template string modelloader::dir = {'\0'}; // crashes clang if "" is used here template struct modelcommands { typedef struct MDL::part part; typedef struct MDL::skin skin; static void setdir(char *name) { if(!MDL::loading) { conoutf("not loading an %s", MDL::formatname()); return; } formatstring(MDL::dir)("packages/models/%s", name); } #define loopmeshes(meshname, m, body) \ if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } \ part &mdl = *MDL::loading->parts.last(); \ if(!mdl.meshes) return; \ loopv(mdl.meshes->meshes) \ { \ MESH &m = *(MESH *)mdl.meshes->meshes[i]; \ if(!strcmp(meshname, "*") || (m.name && !strcmp(m.name, meshname))) \ { \ body; \ } \ } #define loopskins(meshname, s, body) loopmeshes(meshname, m, { skin &s = mdl.skins[i]; body; }) static void setskin(char *meshname, char *tex, char *masks, float *envmapmax, float *envmapmin) { loopskins(meshname, s, s.tex = textureload(makerelpath(MDL::dir, tex), 0, true, false); if(*masks) { s.masks = textureload(makerelpath(MDL::dir, masks, ""), 0, true, false); s.envmapmax = *envmapmax; s.envmapmin = *envmapmin; } ); } static void setspec(char *meshname, int *percent) { float spec = 1.0f; if(*percent>0) spec = *percent/100.0f; else if(*percent<0) spec = 0.0f; loopskins(meshname, s, s.spec = spec); } static void setambient(char *meshname, int *percent) { float ambient = 0.3f; if(*percent>0) ambient = *percent/100.0f; else if(*percent<0) ambient = 0.0f; loopskins(meshname, s, s.ambient = ambient); } static void setglow(char *meshname, int *percent, int *delta, float *pulse) { float glow = 3.0f, glowdelta = *delta/100.0f, glowpulse = *pulse > 0 ? *pulse/1000.0f : 0; if(*percent>0) glow = *percent/100.0f; else if(*percent<0) glow = 0.0f; glowdelta -= glow; loopskins(meshname, s, { s.glow = glow; s.glowdelta = glowdelta; s.glowpulse = glowpulse; }); } static void setglare(char *meshname, float *specglare, float *glowglare) { loopskins(meshname, s, { s.specglare = *specglare; s.glowglare = *glowglare; }); } static void setalphatest(char *meshname, float *cutoff) { loopskins(meshname, s, s.alphatest = max(0.0f, min(1.0f, *cutoff))); } static void setalphablend(char *meshname, int *blend) { loopskins(meshname, s, s.alphablend = *blend!=0); } static void setcullface(char *meshname, int *cullface) { loopskins(meshname, s, s.cullface = *cullface!=0); } static void setenvmap(char *meshname, char *envmap) { Texture *tex = cubemapload(envmap); loopskins(meshname, s, s.envmap = tex); } static void setbumpmap(char *meshname, char *normalmapfile, char *skinfile) { Texture *normalmaptex = NULL, *skintex = NULL; normalmaptex = textureload(makerelpath(MDL::dir, normalmapfile, ""), 0, true, false); if(skinfile[0]) skintex = textureload(makerelpath(MDL::dir, skinfile, ""), 0, true, false); loopskins(meshname, s, { s.unlittex = skintex; s.normalmap = normalmaptex; m.calctangents(); }); } static void setfullbright(char *meshname, float *fullbright) { loopskins(meshname, s, s.fullbright = *fullbright); } static void setshader(char *meshname, char *shader) { loopskins(meshname, s, s.shader = lookupshaderbyname(shader)); } static void setscroll(char *meshname, float *scrollu, float *scrollv) { loopskins(meshname, s, { s.scrollu = *scrollu; s.scrollv = *scrollv; }); } static void setnoclip(char *meshname, int *noclip) { loopmeshes(meshname, m, m.noclip = *noclip!=0); } static void setlink(int *parent, int *child, char *tagname, float *x, float *y, float *z) { if(!MDL::loading) { conoutf("not loading an %s", MDL::formatname()); return; } if(!MDL::loading->parts.inrange(*parent) || !MDL::loading->parts.inrange(*child)) { conoutf("no models loaded to link"); return; } if(!MDL::loading->parts[*parent]->link(MDL::loading->parts[*child], tagname, vec(*x, *y, *z))) conoutf("could not link model %s", MDL::loading->loadname); } template void modelcommand(F *fun, const char *suffix, const char *args) { defformatstring(name)("%s%s", MDL::formatname(), suffix); addcommand(newstring(name), (void (*)())fun, args); } modelcommands() { modelcommand(setdir, "dir", "s"); if(MDL::multimeshed()) { modelcommand(setskin, "skin", "sssff"); modelcommand(setspec, "spec", "si"); modelcommand(setambient, "ambient", "si"); modelcommand(setglow, "glow", "siif"); modelcommand(setglare, "glare", "sff"); modelcommand(setalphatest, "alphatest", "sf"); modelcommand(setalphablend, "alphablend", "si"); modelcommand(setcullface, "cullface", "si"); modelcommand(setenvmap, "envmap", "ss"); modelcommand(setbumpmap, "bumpmap", "sss"); modelcommand(setfullbright, "fullbright", "sf"); modelcommand(setshader, "shader", "ss"); modelcommand(setscroll, "scroll", "sff"); modelcommand(setnoclip, "noclip", "si"); } if(MDL::multiparted()) modelcommand(setlink, "link", "iisfff"); } }; sauerbraten-0.0.20130203.dfsg/engine/world.h0000644000175000017500000000302412057466657020163 0ustar vincentvincent enum // hardcoded texture numbers { DEFAULT_SKY = 0, DEFAULT_GEOM }; #define MAPVERSION 33 // bump if map format changes, see worldio.cpp struct octaheader { char magic[4]; // "OCTA" int version; // any >8bit quantity is little endian int headersize; // sizeof(header) int worldsize; int numents; int numpvs; int lightmaps; int blendmap; int numvars; int numvslots; }; struct compatheader // map file format header { char magic[4]; // "OCTA" int version; // any >8bit quantity is little endian int headersize; // sizeof(header) int worldsize; int numents; int numpvs; int lightmaps; int lightprecision, lighterror, lightlod; uchar ambient; uchar watercolour[3]; uchar blendmap; uchar lerpangle, lerpsubdiv, lerpsubdivsize; uchar bumperror; uchar skylight[3]; uchar lavacolour[3]; uchar waterfallcolour[3]; uchar reserved[10]; char maptitle[128]; }; #define WATER_AMPLITUDE 0.4f #define WATER_OFFSET 1.1f enum { MATSURF_NOT_VISIBLE = 0, MATSURF_VISIBLE, MATSURF_EDIT_ONLY }; #define TEX_SCALE 8.0f struct vertexff { vec pos; bvec norm; uchar reserved; float u, v; float lmu, lmv; }; struct vertex { vec pos; bvec norm; uchar reserved; float u, v; short lmu, lmv; bvec tangent; uchar bitangent; }; #define VTXSIZE (renderpath==R_FIXEDFUNCTION ? sizeof(vertexff) : sizeof(vertex)) sauerbraten-0.0.20130203.dfsg/engine/texture.cpp0000644000175000017500000030102312077450335021053 0ustar vincentvincent// texture.cpp: texture slot management #include "engine.h" #define FUNCNAME(name) name##1 #define DEFPIXEL uint OP(r, 0); #define PIXELOP OP(r, 0); #define BPP 1 #include "scale.h" #define FUNCNAME(name) name##2 #define DEFPIXEL uint OP(r, 0), OP(g, 1); #define PIXELOP OP(r, 0); OP(g, 1); #define BPP 2 #include "scale.h" #define FUNCNAME(name) name##3 #define DEFPIXEL uint OP(r, 0), OP(g, 1), OP(b, 2); #define PIXELOP OP(r, 0); OP(g, 1); OP(b, 2); #define BPP 3 #include "scale.h" #define FUNCNAME(name) name##4 #define DEFPIXEL uint OP(r, 0), OP(g, 1), OP(b, 2), OP(a, 3); #define PIXELOP OP(r, 0); OP(g, 1); OP(b, 2); OP(a, 3); #define BPP 4 #include "scale.h" static void scaletexture(uchar *src, uint sw, uint sh, uint bpp, uint pitch, uchar *dst, uint dw, uint dh) { if(sw == dw*2 && sh == dh*2) { switch(bpp) { case 1: return halvetexture1(src, sw, sh, pitch, dst); case 2: return halvetexture2(src, sw, sh, pitch, dst); case 3: return halvetexture3(src, sw, sh, pitch, dst); case 4: return halvetexture4(src, sw, sh, pitch, dst); } } else if(sw < dw || sh < dh || sw&(sw-1) || sh&(sh-1)) { switch(bpp) { case 1: return scaletexture1(src, sw, sh, pitch, dst, dw, dh); case 2: return scaletexture2(src, sw, sh, pitch, dst, dw, dh); case 3: return scaletexture3(src, sw, sh, pitch, dst, dw, dh); case 4: return scaletexture4(src, sw, sh, pitch, dst, dw, dh); } } else { switch(bpp) { case 1: return shifttexture1(src, sw, sh, pitch, dst, dw, dh); case 2: return shifttexture2(src, sw, sh, pitch, dst, dw, dh); case 3: return shifttexture3(src, sw, sh, pitch, dst, dw, dh); case 4: return shifttexture4(src, sw, sh, pitch, dst, dw, dh); } } } static inline void reorienttexture(uchar *src, int sw, int sh, int bpp, int stride, uchar *dst, bool flipx, bool flipy, bool swapxy, bool normals = false) { int stridex = bpp, stridey = bpp; if(swapxy) stridex *= sh; else stridey *= sw; if(flipx) { dst += (sw-1)*stridex; stridex = -stridex; } if(flipy) { dst += (sh-1)*stridey; stridey = -stridey; } uchar *srcrow = src; loopi(sh) { for(uchar *curdst = dst, *src = srcrow, *end = &srcrow[sw*bpp]; src < end;) { loopk(bpp) curdst[k] = *src++; if(normals) { if(flipx) curdst[0] = 255-curdst[0]; if(flipy) curdst[1] = 255-curdst[1]; if(swapxy) swap(curdst[0], curdst[1]); } curdst += stridex; } srcrow += stride; dst += stridey; } } static void reorients3tc(GLenum format, int blocksize, int w, int h, uchar *src, uchar *dst, bool flipx, bool flipy, bool swapxy, bool normals = false) { int bx1 = 0, by1 = 0, bx2 = min(w, 4), by2 = min(h, 4), bw = (w+3)/4, bh = (h+3)/4, stridex = blocksize, stridey = blocksize; if(swapxy) stridex *= bw; else stridey *= bh; if(flipx) { dst += (bw-1)*stridex; stridex = -stridex; bx1 += 4-bx2; bx2 = 4; } if(flipy) { dst += (bh-1)*stridey; stridey = -stridey; by1 += 4-by2; by2 = 4; } loopi(bh) { for(uchar *curdst = dst, *end = &src[bw*blocksize]; src < end; src += blocksize, curdst += stridex) { if(format == GL_COMPRESSED_RGBA_S3TC_DXT3_EXT) { ullong salpha = lilswap(*(ullong *)src), dalpha = 0; uint xmask = flipx ? 15 : 0, ymask = flipy ? 15 : 0, xshift = 2, yshift = 4; if(swapxy) swap(xshift, yshift); for(int y = by1; y < by2; y++) for(int x = bx1; x < bx2; x++) { dalpha |= ((salpha&15) << (((xmask^x)<>= 4; } *(ullong *)curdst = lilswap(dalpha); src += 8; curdst += 8; } else if(format == GL_COMPRESSED_RGBA_S3TC_DXT5_EXT) { uchar alpha1 = src[0], alpha2 = src[1]; ullong salpha = lilswap(*(ushort *)&src[2]) + ((ullong)lilswap(*(ushort *)&src[4])<<16) + ((ullong)lilswap(*(ushort *)&src[6])<<32), dalpha = 0; uint xmask = flipx ? 7 : 0, ymask = flipy ? 7 : 0, xshift = 0, yshift = 2; if(swapxy) swap(xshift, yshift); for(int y = by1; y < by2; y++) for(int x = bx1; x < bx2; x++) { dalpha |= ((salpha&7) << (3*((xmask^x)<>= 3; } curdst[0] = alpha1; curdst[1] = alpha2; *(ushort *)&curdst[2] = lilswap(ushort(dalpha)); *(ushort *)&curdst[4] = lilswap(ushort(dalpha>>16)); *(ushort *)&curdst[6] = lilswap(ushort(dalpha>>32)); src += 8; curdst += 8; } ushort color1 = lilswap(*(ushort *)src), color2 = lilswap(*(ushort *)&src[2]); uint sbits = lilswap(*(uint *)&src[4]); if(normals) { ushort ncolor1 = color1, ncolor2 = color2; if(flipx) { ncolor1 = (ncolor1 & ~0xF800) | (0xF800 - (ncolor1 & 0xF800)); ncolor2 = (ncolor2 & ~0xF800) | (0xF800 - (ncolor2 & 0xF800)); } if(flipy) { ncolor1 = (ncolor1 & ~0x7E0) | (0x7E0 - (ncolor1 & 0x7E0)); ncolor2 = (ncolor2 & ~0x7E0) | (0x7E0 - (ncolor2 & 0x7E0)); } if(swapxy) { ncolor1 = (ncolor1 & 0x1F) | (((((ncolor1 >> 11) & 0x1F) * 0x3F) / 0x1F) << 5) | (((((ncolor1 >> 5) & 0x3F) * 0x1F) / 0x3F) << 11); ncolor2 = (ncolor2 & 0x1F) | (((((ncolor2 >> 11) & 0x1F) * 0x3F) / 0x1F) << 5) | (((((ncolor2 >> 5) & 0x3F) * 0x1F) / 0x3F) << 11); } if(color1 <= color2 && ncolor1 > ncolor2) { color1 = ncolor2; color2 = ncolor1; } else { color1 = ncolor1; color2 = ncolor2; } } uint dbits = 0, xmask = flipx ? 3 : 0, ymask = flipy ? 3 : 0, xshift = 1, yshift = 3; if(swapxy) swap(xshift, yshift); for(int y = by1; y < by2; y++) for(int x = bx1; x < bx2; x++) { dbits |= ((sbits&3) << (((xmask^x)<>= 2; } *(ushort *)curdst = lilswap(color1); *(ushort *)&curdst[2] = lilswap(color2); *(uint *)&curdst[4] = lilswap(dbits); if(blocksize > 8) { src -= 8; curdst -= 8; } } dst += stridey; } } #define writetex(t, body) \ { \ uchar *dstrow = t.data; \ loop(y, t.h) \ { \ for(uchar *dst = dstrow, *end = &dstrow[t.w*t.bpp]; dst < end; dst += t.bpp) \ { \ body; \ } \ dstrow += t.pitch; \ } \ } #define readwritetex(t, s, body) \ { \ uchar *dstrow = t.data, *srcrow = s.data; \ loop(y, t.h) \ { \ for(uchar *dst = dstrow, *src = srcrow, *end = &srcrow[s.w*s.bpp]; src < end; dst += t.bpp, src += s.bpp) \ { \ body; \ } \ dstrow += t.pitch; \ srcrow += s.pitch; \ } \ } #define read2writetex(t, s1, src1, s2, src2, body) \ { \ uchar *dstrow = t.data, *src1row = s1.data, *src2row = s2.data; \ loop(y, t.h) \ { \ for(uchar *dst = dstrow, *end = &dstrow[t.w*t.bpp], *src1 = src1row, *src2 = src2row; dst < end; dst += t.bpp, src1 += s1.bpp, src2 += s2.bpp) \ { \ body; \ } \ dstrow += t.pitch; \ src1row += s1.pitch; \ src2row += s2.pitch; \ } \ } void texreorient(ImageData &s, bool flipx, bool flipy, bool swapxy, int type = TEX_DIFFUSE) { ImageData d(swapxy ? s.h : s.w, swapxy ? s.w : s.h, s.bpp, s.levels, s.align, s.compressed); switch(s.compressed) { case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: { uchar *dst = d.data, *src = s.data; loopi(s.levels) { reorients3tc(s.compressed, s.bpp, max(s.w>>i, 1), max(s.h>>i, 1), src, dst, flipx, flipy, swapxy, type==TEX_NORMAL); src += s.calclevelsize(i); dst += d.calclevelsize(i); } break; } default: reorienttexture(s.data, s.w, s.h, s.bpp, s.pitch, d.data, flipx, flipy, swapxy, type==TEX_NORMAL); break; } s.replace(d); } void texrotate(ImageData &s, int numrots, int type = TEX_DIFFUSE) { // 1..3 rotate through 90..270 degrees, 4 flips X, 5 flips Y if(numrots>=1 && numrots<=5) texreorient(s, numrots>=2 && numrots<=4, // flip X on 180/270 degrees numrots<=2 || numrots==5, // flip Y on 90/180 degrees (numrots&5)==1, // swap X/Y on 90/270 degrees type); } void texoffset(ImageData &s, int xoffset, int yoffset) { xoffset = max(xoffset, 0); xoffset %= s.w; yoffset = max(yoffset, 0); yoffset %= s.h; if(!xoffset && !yoffset) return; ImageData d(s.w, s.h, s.bpp); uchar *src = s.data; loop(y, s.h) { uchar *dst = (uchar *)d.data+((y+yoffset)%d.h)*d.pitch; memcpy(dst+xoffset*s.bpp, src, (s.w-xoffset)*s.bpp); memcpy(dst, src+(s.w-xoffset)*s.bpp, xoffset*s.bpp); src += s.pitch; } s.replace(d); } void texmad(ImageData &s, const vec &mul, const vec &add) { int maxk = min(int(s.bpp), 3); writetex(s, loopk(maxk) dst[k] = uchar(clamp(dst[k]*mul[k] + 255*add[k], 0.0f, 255.0f)); ); } void texcolorify(ImageData &s, const vec &color, vec weights) { if(s.bpp < 3) return; if(weights.iszero()) weights = vec(0.21f, 0.72f, 0.07f); writetex(s, float lum = dst[0]*weights.x + dst[1]*weights.y + dst[2]*weights.z; loopk(3) dst[k] = uchar(clamp(lum*color[k], 0.0f, 255.0f)); ); } void texcolormask(ImageData &s, const vec &color1, const vec &color2) { if(s.bpp < 4) return; ImageData d(s.w, s.h, 3); readwritetex(d, s, vec color; color.lerp(color2, color1, src[3]/255.0f); loopk(3) dst[k] = uchar(clamp(color[k]*src[k], 0.0f, 255.0f)); ); s.replace(d); } void texffmask(ImageData &s, float glowscale, float envscale) { if(renderpath!=R_FIXEDFUNCTION) return; if(nomasks || s.bpp<3) { s.cleanup(); return; } const int minval = 0x18; bool glow = false, envmap = true; writetex(s, if(dst[1]>minval) glow = true; if(dst[2]>minval) { glow = envmap = true; goto needmask; } ); if(!glow && !envmap) { s.cleanup(); return; } needmask: ImageData m(s.w, s.h, envmap ? 2 : 1); readwritetex(m, s, dst[0] = uchar(src[1]*glowscale); if(envmap) dst[1] = uchar(src[2]*envscale); ); s.replace(m); } void texdup(ImageData &s, int srcchan, int dstchan) { if(srcchan==dstchan || max(srcchan, dstchan) >= s.bpp) return; writetex(s, dst[dstchan] = dst[srcchan]); } void texdecal(ImageData &s) { if(renderpath!=R_FIXEDFUNCTION || hasTE) return; ImageData m(s.w, s.w, 2); readwritetex(m, s, dst[0] = src[0]; dst[1] = 255 - src[0]; ); s.replace(m); } void texmix(ImageData &s, int c1, int c2, int c3, int c4) { int numchans = c1 < 0 ? 0 : (c2 < 0 ? 1 : (c3 < 0 ? 2 : (c4 < 0 ? 3 : 4))); if(numchans <= 0) return; ImageData d(s.w, s.h, numchans); readwritetex(d, s, switch(numchans) { case 4: dst[3] = src[c4]; case 3: dst[2] = src[c3]; case 2: dst[1] = src[c2]; case 1: dst[0] = src[c1]; } ); s.replace(d); } void texgrey(ImageData &s) { if(s.bpp <= 2) return; ImageData d(s.w, s.h, s.bpp >= 4 ? 2 : 1); if(s.bpp >= 4) { readwritetex(d, s, dst[0] = src[0]; dst[1] = src[3]; ); } else { readwritetex(d, s, dst[0] = src[0]); } s.replace(d); } void texpremul(ImageData &s) { switch(s.bpp) { case 2: writetex(s, dst[0] = uchar((uint(dst[0])*uint(dst[1]))/255); ); break; case 4: writetex(s, uint alpha = dst[3]; dst[0] = uchar((uint(dst[0])*alpha)/255); dst[1] = uchar((uint(dst[1])*alpha)/255); dst[2] = uchar((uint(dst[2])*alpha)/255); ); break; } } void texagrad(ImageData &s, float x2, float y2, float x1, float y1) { if(s.bpp != 2 && s.bpp != 4) return; y1 = 1 - y1; y2 = 1 - y2; float minx = 1, miny = 1, maxx = 1, maxy = 1; if(x1 != x2) { minx = (0 - x1) / (x2 - x1); maxx = (1 - x1) / (x2 - x1); } if(y1 != y2) { miny = (0 - y1) / (y2 - y1); maxy = (1 - y1) / (y2 - y1); } float dx = (maxx - minx)/max(s.w-1, 1), dy = (maxy - miny)/max(s.h-1, 1), cury = miny; for(uchar *dstrow = s.data + s.bpp - 1, *endrow = dstrow + s.h*s.pitch; dstrow < endrow; dstrow += s.pitch) { float curx = minx; for(uchar *dst = dstrow, *end = &dstrow[s.w*s.bpp]; dst < end; dst += s.bpp) { dst[0] = uchar(dst[0]*clamp(curx, 0.0f, 1.0f)*clamp(cury, 0.0f, 1.0f)); curx += dx; } cury += dy; } } VAR(hwtexsize, 1, 0, 0); VAR(hwcubetexsize, 1, 0, 0); VAR(hwmaxaniso, 1, 0, 0); VARFP(maxtexsize, 0, 0, 1<<12, initwarning("texture quality", INIT_LOAD)); VARFP(reducefilter, 0, 1, 1, initwarning("texture quality", INIT_LOAD)); VARFP(texreduce, 0, 0, 12, initwarning("texture quality", INIT_LOAD)); VARFP(texcompress, 0, 1<<10, 1<<12, initwarning("texture quality", INIT_LOAD)); VARFP(texcompressquality, -1, -1, 1, setuptexcompress()); VARFP(trilinear, 0, 1, 1, initwarning("texture filtering", INIT_LOAD)); VARFP(bilinear, 0, 1, 1, initwarning("texture filtering", INIT_LOAD)); VARFP(aniso, 0, 0, 16, initwarning("texture filtering", INIT_LOAD)); extern int usetexcompress; void setuptexcompress() { if(!hasTC || !usetexcompress) return; GLenum hint = GL_DONT_CARE; switch(texcompressquality) { case 1: hint = GL_NICEST; break; case 0: hint = GL_FASTEST; break; } glHint(GL_TEXTURE_COMPRESSION_HINT_ARB, hint); } GLenum compressedformat(GLenum format, int w, int h, int force = 0) { if(hasTC && usetexcompress && texcompress && force >= 0 && (force || max(w, h) >= texcompress)) switch(format) { case GL_RGB5: case GL_RGB8: case GL_LUMINANCE: case GL_RGB: return usetexcompress > 1 ? GL_COMPRESSED_RGB_S3TC_DXT1_EXT : GL_COMPRESSED_RGB_ARB; case GL_LUMINANCE_ALPHA: case GL_RGBA: return usetexcompress > 1 ? GL_COMPRESSED_RGBA_S3TC_DXT5_EXT : GL_COMPRESSED_RGBA_ARB; } return format; } int formatsize(GLenum format) { switch(format) { case GL_LUMINANCE: case GL_ALPHA: return 1; case GL_LUMINANCE_ALPHA: return 2; case GL_RGB: return 3; case GL_RGBA: return 4; default: return 4; } } VARFP(hwmipmap, 0, 0, 1, initwarning("texture filtering", INIT_LOAD)); VARFP(usenp2, 0, 0, 1, initwarning("texture quality", INIT_LOAD)); void resizetexture(int w, int h, bool mipmap, bool canreduce, GLenum target, int compress, int &tw, int &th) { int hwlimit = target==GL_TEXTURE_CUBE_MAP_ARB ? hwcubetexsize : hwtexsize, sizelimit = mipmap && maxtexsize ? min(maxtexsize, hwlimit) : hwlimit; if(compress > 0 && (!hasTC || !usetexcompress)) { w = max(w/compress, 1); h = max(h/compress, 1); } if(canreduce && texreduce) { w = max(w>>texreduce, 1); h = max(h>>texreduce, 1); } w = min(w, sizelimit); h = min(h, sizelimit); if((!hasNP2 || !usenp2) && target!=GL_TEXTURE_RECTANGLE_ARB && (w&(w-1) || h&(h-1))) { tw = th = 1; while(tw < w) tw *= 2; while(th < h) th *= 2; if(w < tw - tw/4) tw /= 2; if(h < th - th/4) th /= 2; } else { tw = w; th = h; } } void uploadtexture(GLenum target, GLenum internal, int tw, int th, GLenum format, GLenum type, void *pixels, int pw, int ph, int pitch, bool mipmap) { int bpp = formatsize(format), row = 0, rowalign = 0; if(!pitch) pitch = pw*bpp; uchar *buf = NULL; if(pw!=tw || ph!=th) { buf = new uchar[tw*th*bpp]; scaletexture((uchar *)pixels, pw, ph, bpp, pitch, buf, tw, th); } else if(tw*bpp != pitch) { row = pitch/bpp; rowalign = texalign(pixels, pitch, 1); while(rowalign > 0 && ((row*bpp + rowalign - 1)/rowalign)*rowalign != pitch) rowalign >>= 1; if(!rowalign) { row = 0; buf = new uchar[tw*th*bpp]; loopi(th) memcpy(&buf[i*tw*bpp], &((uchar *)pixels)[i*pitch], tw*bpp); } } for(int level = 0, align = 0;; level++) { uchar *src = buf ? buf : (uchar *)pixels; if(buf) pitch = tw*bpp; int srcalign = row > 0 ? rowalign : texalign(src, pitch, 1); if(align != srcalign) glPixelStorei(GL_UNPACK_ALIGNMENT, align = srcalign); if(row > 0) glPixelStorei(GL_UNPACK_ROW_LENGTH, row); if(target==GL_TEXTURE_1D) glTexImage1D(target, level, internal, tw, 0, format, type, src); else glTexImage2D(target, level, internal, tw, th, 0, format, type, src); if(row > 0) glPixelStorei(GL_UNPACK_ROW_LENGTH, row = 0); if(!mipmap || (hasGM && hwmipmap) || max(tw, th) <= 1) break; int srcw = tw, srch = th; if(tw > 1) tw /= 2; if(th > 1) th /= 2; if(!buf) buf = new uchar[tw*th*bpp]; scaletexture(src, srcw, srch, bpp, pitch, buf, tw, th); } if(buf) delete[] buf; } void uploadcompressedtexture(GLenum target, GLenum subtarget, GLenum format, int w, int h, uchar *data, int align, int blocksize, int levels, bool mipmap) { int hwlimit = target==GL_TEXTURE_CUBE_MAP_ARB ? hwcubetexsize : hwtexsize, sizelimit = levels > 1 && maxtexsize ? min(maxtexsize, hwlimit) : hwlimit; int level = 0; loopi(levels) { int size = ((w + align-1)/align) * ((h + align-1)/align) * blocksize; if(w <= sizelimit && h <= sizelimit) { if(target==GL_TEXTURE_1D) glCompressedTexImage1D_(subtarget, level, format, w, 0, size, data); else glCompressedTexImage2D_(subtarget, level, format, w, h, 0, size, data); level++; if(!mipmap) break; } if(max(w, h) <= 1) break; if(w > 1) w /= 2; if(h > 1) h /= 2; data += size; } } GLenum textarget(GLenum subtarget) { switch(subtarget) { case GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB: case GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB: case GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB: case GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB: return GL_TEXTURE_CUBE_MAP_ARB; } return subtarget; } GLenum uncompressedformat(GLenum format) { switch(format) { case GL_COMPRESSED_RGB_ARB: case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: return GL_RGB; case GL_COMPRESSED_RGBA_ARB: case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: return GL_RGBA; } return GL_FALSE; } void setuptexparameters(int tnum, void *pixels, int clamp, int filter, GLenum format, GLenum target) { glBindTexture(target, tnum); glTexParameteri(target, GL_TEXTURE_WRAP_S, clamp&1 ? GL_CLAMP_TO_EDGE : GL_REPEAT); if(target!=GL_TEXTURE_1D) glTexParameteri(target, GL_TEXTURE_WRAP_T, clamp&2 ? GL_CLAMP_TO_EDGE : GL_REPEAT); if(target==GL_TEXTURE_2D && hasAF && min(aniso, hwmaxaniso) > 0 && filter > 1) glTexParameteri(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, min(aniso, hwmaxaniso)); glTexParameteri(target, GL_TEXTURE_MAG_FILTER, filter && bilinear ? GL_LINEAR : GL_NEAREST); glTexParameteri(target, GL_TEXTURE_MIN_FILTER, filter > 1 ? (trilinear ? (bilinear ? GL_LINEAR_MIPMAP_LINEAR : GL_NEAREST_MIPMAP_LINEAR) : (bilinear ? GL_LINEAR_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_NEAREST)) : (filter && bilinear ? GL_LINEAR : GL_NEAREST)); if(hasGM && filter > 1 && pixels && hwmipmap && !uncompressedformat(format)) glTexParameteri(target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE); } void createtexture(int tnum, int w, int h, void *pixels, int clamp, int filter, GLenum component, GLenum subtarget, int pw, int ph, int pitch, bool resize, GLenum format) { GLenum target = textarget(subtarget), type = GL_UNSIGNED_BYTE; switch(component) { case GL_FLOAT_RG16_NV: case GL_FLOAT_R32_NV: case GL_RGB16F_ARB: case GL_RGB32F_ARB: if(!format) format = GL_RGB; type = GL_FLOAT; break; case GL_RGBA16F_ARB: case GL_RGBA32F_ARB: if(!format) format = GL_RGBA; type = GL_FLOAT; break; case GL_DEPTH_COMPONENT16: case GL_DEPTH_COMPONENT24: case GL_DEPTH_COMPONENT32: if(!format) format = GL_DEPTH_COMPONENT; break; case GL_RGB5: case GL_RGB8: case GL_RGB16: case GL_COMPRESSED_RGB_ARB: case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: if(!format) format = GL_RGB; break; case GL_RGBA8: case GL_RGBA16: case GL_COMPRESSED_RGBA_ARB: case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: if(!format) format = GL_RGBA; break; } if(!format) format = component; if(tnum) setuptexparameters(tnum, pixels, clamp, filter, format, target); if(!pw) pw = w; if(!ph) ph = h; int tw = w, th = h; bool mipmap = filter > 1 && pixels; if(resize && pixels) { resizetexture(w, h, mipmap, false, target, 0, tw, th); if(mipmap) component = compressedformat(component, tw, th); } uploadtexture(subtarget, component, tw, th, format, type, pixels, pw, ph, pitch, mipmap); } void createcompressedtexture(int tnum, int w, int h, uchar *data, int align, int blocksize, int levels, int clamp, int filter, GLenum format, GLenum subtarget) { GLenum target = textarget(subtarget); if(tnum) setuptexparameters(tnum, data, clamp, filter, format, target); uploadcompressedtexture(target, subtarget, format, w, h, data, align, blocksize, levels, filter > 1); } hashtable textures; Texture *notexture = NULL; // used as default, ensured to be loaded static GLenum texformat(int bpp) { switch(bpp) { case 1: return GL_LUMINANCE; case 2: return GL_LUMINANCE_ALPHA; case 3: return GL_RGB; case 4: return GL_RGBA; default: return 0; } } static bool alphaformat(GLenum format) { switch(format) { case GL_ALPHA: case GL_LUMINANCE_ALPHA: case GL_RGBA: return true; default: return false; } } int texalign(void *data, int w, int bpp) { size_t address = size_t(data) | (w*bpp); if(address&1) return 1; if(address&2) return 2; if(address&4) return 4; return 8; } static Texture *newtexture(Texture *t, const char *rname, ImageData &s, int clamp = 0, bool mipit = true, bool canreduce = false, bool transient = false, int compress = 0) { if(!t) { char *key = newstring(rname); t = &textures[key]; t->name = key; } t->clamp = clamp; t->mipmap = mipit; t->type = Texture::IMAGE; if(transient) t->type |= Texture::TRANSIENT; if(!s.data) { t->type |= Texture::STUB; t->w = t->h = t->xs = t->ys = t->bpp = 0; return t; } GLenum format; if(s.compressed) { format = uncompressedformat(s.compressed); t->bpp = formatsize(format); t->type |= Texture::COMPRESSED; } else { format = texformat(s.bpp); t->bpp = s.bpp; } if(alphaformat(format)) t->type |= Texture::ALPHA; t->w = t->xs = s.w; t->h = t->ys = s.h; int filter = !canreduce || reducefilter ? (mipit ? 2 : 1) : 0; glGenTextures(1, &t->id); if(s.compressed) { uchar *data = s.data; int levels = s.levels, level = 0; if(canreduce && texreduce) loopi(min(texreduce, s.levels-1)) { data += s.calclevelsize(level++); levels--; if(t->w > 1) t->w /= 2; if(t->h > 1) t->h /= 2; } int sizelimit = mipit && maxtexsize ? min(maxtexsize, hwtexsize) : hwtexsize; while(t->w > sizelimit || t->h > sizelimit) { data += s.calclevelsize(level++); levels--; if(t->w > 1) t->w /= 2; if(t->h > 1) t->h /= 2; } createcompressedtexture(t->id, t->w, t->h, data, s.align, s.bpp, levels, clamp, filter, s.compressed, GL_TEXTURE_2D); } else { resizetexture(t->w, t->h, mipit, canreduce, GL_TEXTURE_2D, compress, t->w, t->h); GLenum component = compressedformat(format, t->w, t->h, compress); createtexture(t->id, t->w, t->h, s.data, clamp, filter, component, GL_TEXTURE_2D, t->xs, t->ys, s.pitch, false, format); } return t; } #if SDL_BYTEORDER == SDL_BIG_ENDIAN #define RGBAMASKS 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff #define RGBMASKS 0xff0000, 0x00ff00, 0x0000ff, 0 #else #define RGBAMASKS 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 #define RGBMASKS 0x0000ff, 0x00ff00, 0xff0000, 0 #endif SDL_Surface *wrapsurface(void *data, int width, int height, int bpp) { switch(bpp) { case 3: return SDL_CreateRGBSurfaceFrom(data, width, height, 8*bpp, bpp*width, RGBMASKS); case 4: return SDL_CreateRGBSurfaceFrom(data, width, height, 8*bpp, bpp*width, RGBAMASKS); } return NULL; } SDL_Surface *creatergbsurface(SDL_Surface *os) { SDL_Surface *ns = SDL_CreateRGBSurface(SDL_SWSURFACE, os->w, os->h, 24, RGBMASKS); if(ns) SDL_BlitSurface(os, NULL, ns, NULL); SDL_FreeSurface(os); return ns; } SDL_Surface *creatergbasurface(SDL_Surface *os) { SDL_Surface *ns = SDL_CreateRGBSurface(SDL_SWSURFACE, os->w, os->h, 32, RGBAMASKS); if(ns) { SDL_SetAlpha(os, 0, 0); SDL_BlitSurface(os, NULL, ns, NULL); } SDL_FreeSurface(os); return ns; } bool checkgrayscale(SDL_Surface *s) { // gray scale images have 256 levels, no colorkey, and the palette is a ramp if(s->format->palette) { if(s->format->palette->ncolors != 256 || s->format->colorkey) return false; const SDL_Color *colors = s->format->palette->colors; loopi(256) if(colors[i].r != i || colors[i].g != i || colors[i].b != i) return false; } return true; } SDL_Surface *fixsurfaceformat(SDL_Surface *s) { if(!s) return NULL; if(!s->pixels || min(s->w, s->h) <= 0 || s->format->BytesPerPixel <= 0) { SDL_FreeSurface(s); return NULL; } static const uint rgbmasks[] = { RGBMASKS }, rgbamasks[] = { RGBAMASKS }; switch(s->format->BytesPerPixel) { case 1: if(!checkgrayscale(s)) return s->format->colorkey ? creatergbasurface(s) : creatergbsurface(s); break; case 3: if(s->format->Rmask != rgbmasks[0] || s->format->Gmask != rgbmasks[1] || s->format->Bmask != rgbmasks[2]) return creatergbsurface(s); break; case 4: if(s->format->Rmask != rgbamasks[0] || s->format->Gmask != rgbamasks[1] || s->format->Bmask != rgbamasks[2] || s->format->Amask != rgbamasks[3]) return s->format->Amask ? creatergbasurface(s) : creatergbsurface(s); break; } return s; } void texflip(ImageData &s) { ImageData d(s.w, s.h, s.bpp); uchar *dst = d.data, *src = &s.data[s.pitch*s.h]; loopi(s.h) { src -= s.pitch; memcpy(dst, src, s.bpp*s.w); dst += d.pitch; } s.replace(d); } void texnormal(ImageData &s, int emphasis) { ImageData d(s.w, s.h, 3); uchar *src = s.data, *dst = d.data; loop(y, s.h) loop(x, s.w) { vec normal(0.0f, 0.0f, 255.0f/emphasis); normal.x += src[y*s.pitch + ((x+s.w-1)%s.w)*s.bpp]; normal.x -= src[y*s.pitch + ((x+1)%s.w)*s.bpp]; normal.y += src[((y+s.h-1)%s.h)*s.pitch + x*s.bpp]; normal.y -= src[((y+1)%s.h)*s.pitch + x*s.bpp]; normal.normalize(); *dst++ = uchar(127.5f + normal.x*127.5f); *dst++ = uchar(127.5f + normal.y*127.5f); *dst++ = uchar(127.5f + normal.z*127.5f); } s.replace(d); } template static void blurtexture(int w, int h, uchar *dst, const uchar *src, int margin) { static const int matrix3x3[9] = { 0x10, 0x20, 0x10, 0x20, 0x40, 0x20, 0x10, 0x20, 0x10 }; static const int matrix5x5[25] = { 0x05, 0x05, 0x09, 0x05, 0x05, 0x05, 0x0A, 0x14, 0x0A, 0x05, 0x09, 0x14, 0x28, 0x14, 0x09, 0x05, 0x0A, 0x14, 0x0A, 0x05, 0x05, 0x05, 0x09, 0x05, 0x05 }; const int *mat = n > 1 ? matrix5x5 : matrix3x3; int mstride = 2*n + 1, mstartoffset = n*(mstride + 1), stride = bpp*w, startoffset = n*bpp, nextoffset1 = stride + mstride*bpp, nextoffset2 = stride - mstride*bpp; src += margin*(stride + bpp); for(int y = margin; y < h-margin; y++) { for(int x = margin; x < w-margin; x++) { int dr = 0, dg = 0, db = 0; const uchar *p = src - startoffset; const int *m = mat + mstartoffset; for(int t = y; t >= y-n; t--, p -= nextoffset1, m -= mstride) { if(t < 0) p += stride; int a = 0; if(n > 1) { a += m[-2]; if(x >= 2) { dr += p[0] * a; dg += p[1] * a; db += p[2] * a; a = 0; } p += bpp; } a += m[-1]; if(x >= 1) { dr += p[0] * a; dg += p[1] * a; db += p[2] * a; a = 0; } p += bpp; int cr = p[0], cg = p[1], cb = p[2]; a += m[0]; dr += cr * a; dg += cg * a; db += cb * a; p += bpp; if(x+1 < w) { cr = p[0]; cg = p[1]; cb = p[2]; } dr += cr * m[1]; dg += cg * m[1]; db += cb * m[1]; p += bpp; if(n > 1) { if(x+2 < w) { cr = p[0]; cg = p[1]; cb = p[2]; } dr += cr * m[2]; dg += cg * m[2]; db += cb * m[2]; p += bpp; } } p = src - startoffset + stride; m = mat + mstartoffset + mstride; for(int t = y+1; t <= y+n; t++, p += nextoffset2, m += mstride) { if(t >= h) p -= stride; int a = 0; if(n > 1) { a += m[-2]; if(x >= 2) { dr += p[0] * a; dg += p[1] * a; db += p[2] * a; a = 0; } p += bpp; } a += m[-1]; if(x >= 1) { dr += p[0] * a; dg += p[1] * a; db += p[2] * a; a = 0; } p += bpp; int cr = p[0], cg = p[1], cb = p[2]; a += m[0]; dr += cr * a; dg += cg * a; db += cb * a; p += bpp; if(x+1 < w) { cr = p[0]; cg = p[1]; cb = p[2]; } dr += cr * m[1]; dg += cg * m[1]; db += cb * m[1]; p += bpp; if(n > 1) { if(x+2 < w) { cr = p[0]; cg = p[1]; cb = p[2]; } dr += cr * m[2]; dg += cg * m[2]; db += cb * m[2]; p += bpp; } } if(normals) { vec v(dr-0x7F80, dg-0x7F80, db-0x7F80); float mag = 127.5f/v.magnitude(); dst[0] = uchar(v.x*mag + 127.5f); dst[1] = uchar(v.y*mag + 127.5f); dst[2] = uchar(v.z*mag + 127.5f); } else { dst[0] = dr>>8; dst[1] = dg>>8; dst[2] = db>>8; } if(bpp > 3) dst[3] = src[3]; dst += bpp; src += bpp; } src += 2*margin*bpp; } } void blurtexture(int n, int bpp, int w, int h, uchar *dst, const uchar *src, int margin) { switch((clamp(n, 1, 2)<<4) | bpp) { case 0x13: blurtexture<1, 3, false>(w, h, dst, src, margin); break; case 0x23: blurtexture<2, 3, false>(w, h, dst, src, margin); break; case 0x14: blurtexture<1, 4, false>(w, h, dst, src, margin); break; case 0x24: blurtexture<2, 4, false>(w, h, dst, src, margin); break; } } void blurnormals(int n, int w, int h, bvec *dst, const bvec *src, int margin) { switch(clamp(n, 1, 2)) { case 1: blurtexture<1, 3, true>(w, h, dst->v, src->v, margin); break; case 2: blurtexture<2, 3, true>(w, h, dst->v, src->v, margin); break; } } void texblur(ImageData &s, int n, int r) { if(s.bpp < 3) return; loopi(r) { ImageData d(s.w, s.h, s.bpp); blurtexture(n, s.bpp, s.w, s.h, d.data, s.data); s.replace(d); } } void scaleimage(ImageData &s, int w, int h) { ImageData d(w, h, s.bpp); scaletexture(s.data, s.w, s.h, s.bpp, s.pitch, d.data, w, h); s.replace(d); } #define readwritergbtex(t, s, body) \ { \ if(t.bpp >= 3) { readwritetex(t, s, body); } \ else \ { \ ImageData rgb(t.w, t.h, 3); \ read2writetex(rgb, t, orig, s, src, \ { \ switch(t.bpp) \ { \ case 1: dst[0] = orig[0]; dst[1] = orig[0]; dst[2] = orig[0]; break; \ case 2: dst[0] = orig[0]; dst[1] = orig[1]; dst[2] = orig[1]; break; \ } \ body; \ }); \ t.replace(rgb); \ } \ } void forcergbimage(ImageData &s) { if(s.bpp >= 3) return; ImageData d(s.w, s.h, 3); readwritetex(d, s, switch(s.bpp) { case 1: dst[0] = src[0]; dst[1] = src[0]; dst[2] = src[0]; break; case 2: dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[1]; break; } ); s.replace(d); } #define readwritergbatex(t, s, body) \ { \ if(t.bpp >= 4) { readwritetex(t, s, body); } \ else \ { \ ImageData rgba(t.w, t.h, 4); \ read2writetex(rgba, t, orig, s, src, \ { \ switch(t.bpp) \ { \ case 1: dst[0] = orig[0]; dst[1] = orig[0]; dst[2] = orig[0]; break; \ case 2: dst[0] = orig[0]; dst[1] = orig[1]; dst[2] = orig[1]; break; \ case 3: dst[0] = orig[0]; dst[1] = orig[1]; dst[2] = orig[2]; break; \ } \ body; \ }); \ t.replace(rgba); \ } \ } void forcergbaimage(ImageData &s) { if(s.bpp >= 4) return; ImageData d(s.w, s.h, 4); readwritetex(d, s, switch(s.bpp) { case 1: dst[0] = src[0]; dst[1] = src[0]; dst[2] = src[0]; break; case 2: dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[1]; break; case 3: dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; break; } ); s.replace(d); } bool canloadsurface(const char *name) { stream *f = openfile(name, "rb"); if(!f) return false; delete f; return true; } SDL_Surface *loadsurface(const char *name) { SDL_Surface *s = NULL; stream *z = openzipfile(name, "rb"); if(z) { SDL_RWops *rw = z->rwops(); if(rw) { s = IMG_Load_RW(rw, 0); SDL_FreeRW(rw); } delete z; } if(!s) s = IMG_Load(findfile(name, "rb")); return fixsurfaceformat(s); } static vec parsevec(const char *arg) { vec v(0, 0, 0); int i = 0; for(; arg[0] && (!i || arg[0]=='/') && i<3; arg += strcspn(arg, "/,><"), i++) { if(i) arg++; v[i] = atof(arg); } if(i==1) v.y = v.z = v.x; return v; } VAR(usedds, 0, 1, 1); VAR(dbgdds, 0, 0, 1); static bool texturedata(ImageData &d, const char *tname, Slot::Tex *tex = NULL, bool msg = true, int *compress = NULL) { const char *cmds = NULL, *file = tname; if(!tname) { if(!tex) return false; if(tex->name[0]=='<') { cmds = tex->name; file = strrchr(tex->name, '>'); if(!file) { if(msg) conoutf(CON_ERROR, "could not load texture packages/%s", tex->name); return false; } file++; } else file = tex->name; static string pname; formatstring(pname)("packages/%s", file); file = path(pname); } else if(tname[0]=='<') { cmds = tname; file = strrchr(tname, '>'); if(!file) { if(msg) conoutf(CON_ERROR, "could not load texture %s", tname); return NULL; } file++; } bool raw = !usedds || !compress, dds = false; for(const char *pcmds = cmds; pcmds;) { #define PARSETEXCOMMANDS(cmds) \ const char *cmd = NULL, *end = NULL, *arg[4] = { NULL, NULL, NULL, NULL }; \ cmd = &cmds[1]; \ end = strchr(cmd, '>'); \ if(!end) break; \ cmds = strchr(cmd, '<'); \ size_t len = strcspn(cmd, ":,><"); \ loopi(4) \ { \ arg[i] = strchr(i ? arg[i-1] : cmd, i ? ',' : ':'); \ if(!arg[i] || arg[i] >= end) arg[i] = ""; \ else arg[i]++; \ } PARSETEXCOMMANDS(pcmds); if(!strncmp(cmd, "noff", len)) { if(renderpath==R_FIXEDFUNCTION) return true; } else if(!strncmp(cmd, "ffmask", len) || !strncmp(cmd, "ffskip", len)) { if(renderpath==R_FIXEDFUNCTION) raw = true; } else if(!strncmp(cmd, "decal", len)) { if(renderpath==R_FIXEDFUNCTION && !hasTE) raw = true; } else if(!strncmp(cmd, "dds", len)) dds = true; else if(!strncmp(cmd, "thumbnail", len)) raw = true; else if(!strncmp(cmd, "stub", len)) return canloadsurface(file); } if(msg) renderprogress(loadprogress, file); int flen = strlen(file); if(flen >= 4 && (!strcasecmp(file + flen - 4, ".dds") || dds)) { string dfile; copystring(dfile, file); memcpy(dfile + flen - 4, ".dds", 4); if(!raw && hasS3TC && loaddds(dfile, d)) return true; if(!dds || dbgdds) { if(msg) conoutf(CON_ERROR, "could not load texture %s", dfile); return false; } } SDL_Surface *s = loadsurface(file); if(!s) { if(msg) conoutf(CON_ERROR, "could not load texture %s", file); return false; } int bpp = s->format->BitsPerPixel; if(bpp%8 || !texformat(bpp/8)) { SDL_FreeSurface(s); conoutf(CON_ERROR, "texture must be 8, 16, 24, or 32 bpp: %s", file); return false; } if(max(s->w, s->h) > (1<<12)) { SDL_FreeSurface(s); conoutf(CON_ERROR, "texture size exceeded %dx%d pixels: %s", 1<<12, 1<<12, file); return false; } d.wrap(s); while(cmds) { PARSETEXCOMMANDS(cmds); if(!strncmp(cmd, "mad", len)) texmad(d, parsevec(arg[0]), parsevec(arg[1])); else if(!strncmp(cmd, "colorify", len)) texcolorify(d, parsevec(arg[0]), parsevec(arg[1])); else if(!strncmp(cmd, "colormask", len)) texcolormask(d, parsevec(arg[0]), *arg[1] ? parsevec(arg[1]) : vec(1, 1, 1)); else if(!strncmp(cmd, "ffmask", len)) { texffmask(d, atof(arg[0]), atof(arg[1])); if(!d.data) break; } else if(!strncmp(cmd, "normal", len)) { int emphasis = atoi(arg[0]); texnormal(d, emphasis > 0 ? emphasis : 3); } else if(!strncmp(cmd, "dup", len)) texdup(d, atoi(arg[0]), atoi(arg[1])); else if(!strncmp(cmd, "decal", len)) texdecal(d); else if(!strncmp(cmd, "offset", len)) texoffset(d, atoi(arg[0]), atoi(arg[1])); else if(!strncmp(cmd, "rotate", len)) texrotate(d, atoi(arg[0]), tex ? tex->type : 0); else if(!strncmp(cmd, "reorient", len)) texreorient(d, atoi(arg[0])>0, atoi(arg[1])>0, atoi(arg[2])>0, tex ? tex->type : TEX_DIFFUSE); else if(!strncmp(cmd, "mix", len)) texmix(d, *arg[0] ? atoi(arg[0]) : -1, *arg[1] ? atoi(arg[1]) : -1, *arg[2] ? atoi(arg[2]) : -1, *arg[3] ? atoi(arg[3]) : -1); else if(!strncmp(cmd, "grey", len)) texgrey(d); else if(!strncmp(cmd, "blur", len)) { int emphasis = atoi(arg[0]), repeat = atoi(arg[1]); texblur(d, emphasis > 0 ? clamp(emphasis, 1, 2) : 1, repeat > 0 ? repeat : 1); } else if(!strncmp(cmd, "premul", len)) texpremul(d); else if(!strncmp(cmd, "agrad", len)) texagrad(d, atof(arg[0]), atof(arg[1]), atof(arg[2]), atof(arg[3])); else if(!strncmp(cmd, "compress", len) || !strncmp(cmd, "dds", len)) { int scale = atoi(arg[0]); if(scale <= 0) scale = 2; if(compress) *compress = scale; } else if(!strncmp(cmd, "nocompress", len)) { if(compress) *compress = -1; } else if(!strncmp(cmd, "thumbnail", len)) { int w = atoi(arg[0]), h = atoi(arg[1]); if(w <= 0 || w > (1<<12)) w = 64; if(h <= 0 || h > (1<<12)) h = w; if(d.w > w || d.h > h) scaleimage(d, w, h); } else if(!strncmp(cmd, "ffskip", len)) { if(renderpath==R_FIXEDFUNCTION) break; } } return true; } void loadalphamask(Texture *t) { if(t->alphamask || (t->type&(Texture::ALPHA|Texture::COMPRESSED)) != Texture::ALPHA) return; ImageData s; if(!texturedata(s, t->name, NULL, false) || !s.data || s.compressed) return; t->alphamask = new uchar[s.h * ((s.w+7)/8)]; uchar *srcrow = s.data, *dst = t->alphamask-1; loop(y, s.h) { uchar *src = srcrow+s.bpp-1; loop(x, s.w) { int offset = x%8; if(!offset) *++dst = 0; if(*src) *dst |= 1<id); return t != notexture; } vector vslots; vector slots; MSlot materialslots[(MATF_VOLUME|MATF_INDEX)+1]; Slot dummyslot; VSlot dummyvslot(&dummyslot); void texturereset(int *n) { if(!(identflags&IDF_OVERRIDDEN) && !game::allowedittoggle()) return; resetslotshader(); int limit = clamp(*n, 0, slots.length()); for(int i = limit; i < slots.length(); i++) { Slot *s = slots[i]; for(VSlot *vs = s->variants; vs; vs = vs->next) vs->slot = &dummyslot; delete s; } slots.setsize(limit); } COMMAND(texturereset, "i"); void materialreset() { if(!(identflags&IDF_OVERRIDDEN) && !game::allowedittoggle()) return; loopi((MATF_VOLUME|MATF_INDEX)+1) materialslots[i].reset(); } COMMAND(materialreset, ""); static int compactedvslots = 0, compactvslotsprogress = 0, clonedvslots = 0; static bool markingvslots = false; void clearslots() { resetslotshader(); slots.deletecontents(); vslots.deletecontents(); loopi((MATF_VOLUME|MATF_INDEX)+1) materialslots[i].reset(); clonedvslots = 0; } static void assignvslot(VSlot &vs); static inline void assignvslotlayer(VSlot &vs) { if(vs.layer && vslots.inrange(vs.layer)) { VSlot &layer = *vslots[vs.layer]; if(layer.index < 0) assignvslot(layer); } } static void assignvslot(VSlot &vs) { vs.index = compactedvslots++; assignvslotlayer(vs); } void compactvslot(int &index) { if(vslots.inrange(index)) { VSlot &vs = *vslots[index]; if(vs.index < 0) assignvslot(vs); if(!markingvslots) index = vs.index; } } void compactvslots(cube *c, int n) { if((compactvslotsprogress++&0xFFF)==0) renderprogress(min(float(compactvslotsprogress)/allocnodes, 1.0f), markingvslots ? "marking slots..." : "compacting slots..."); loopi(n) { if(c[i].children) compactvslots(c[i].children); else loopj(6) if(vslots.inrange(c[i].texture[j])) { VSlot &vs = *vslots[c[i].texture[j]]; if(vs.index < 0) assignvslot(vs); if(!markingvslots) c[i].texture[j] = vs.index; } } } int compactvslots() { clonedvslots = 0; markingvslots = false; compactedvslots = 0; compactvslotsprogress = 0; loopv(vslots) vslots[i]->index = -1; loopv(slots) slots[i]->variants->index = compactedvslots++; loopv(slots) assignvslotlayer(*slots[i]->variants); loopv(vslots) { VSlot &vs = *vslots[i]; if(!vs.changed && vs.index < 0) { markingvslots = true; break; } } compactvslots(worldroot); int total = compactedvslots; compacteditvslots(); loopv(vslots) { VSlot *vs = vslots[i]; if(vs->changed) continue; while(vs->next) { if(vs->next->index < 0) vs->next = vs->next->next; else vs = vs->next; } } if(markingvslots) { markingvslots = false; compactedvslots = 0; compactvslotsprogress = 0; int lastdiscard = 0; loopv(vslots) { VSlot &vs = *vslots[i]; if(vs.changed || (vs.index < 0 && !vs.next)) vs.index = -1; else { while(lastdiscard < i) { VSlot &ds = *vslots[lastdiscard++]; if(!ds.changed && ds.index < 0) ds.index = compactedvslots++; } vs.index = compactedvslots++; } } compactvslots(worldroot); total = compactedvslots; compacteditvslots(); } compactmruvslots(); loopv(vslots) { VSlot &vs = *vslots[i]; if(vs.index >= 0 && vs.layer && vslots.inrange(vs.layer)) vs.layer = vslots[vs.layer]->index; } loopv(vslots) { while(vslots[i]->index >= 0 && vslots[i]->index != i) swap(vslots[i], vslots[vslots[i]->index]); } for(int i = compactedvslots; i < vslots.length(); i++) delete vslots[i]; vslots.setsize(compactedvslots); return total; } ICOMMAND(compactvslots, "", (), { extern int nompedit; if(nompedit && multiplayer()) return; compactvslots(); allchanged(); }); static Slot &loadslot(Slot &s, bool forceload); static void clampvslotoffset(VSlot &dst, Slot *slot = NULL) { if(!slot) slot = dst.slot; if(slot && slot->sts.inrange(0)) { if(!slot->loaded) loadslot(*slot, false); int xs = slot->sts[0].t->xs, ys = slot->sts[0].t->ys; if((dst.rotation&5)==1) swap(xs, ys); dst.xoffset %= xs; if(dst.xoffset < 0) dst.xoffset += xs; dst.yoffset %= ys; if(dst.yoffset < 0) dst.yoffset += ys; } else { dst.xoffset = max(dst.xoffset, 0); dst.yoffset = max(dst.yoffset, 0); } } static void propagatevslot(VSlot &dst, const VSlot &src, int diff, bool edit = false) { if(diff & (1<next; vs; vs = vs->next) { int diff = changed & ~vs->changed; if(diff) propagatevslot(*vs, *root, diff); } } static void mergevslot(VSlot &dst, const VSlot &src, int diff, Slot *slot = NULL) { if(diff & (1<slot = &owner; vs->linked = false; vs = vs->next; } return owner.variants; } static VSlot *emptyvslot(Slot &owner) { int offset = 0; loopvrev(slots) if(slots[i]->variants) { offset = slots[i]->variants->index + 1; break; } for(int i = offset; i < vslots.length(); i++) if(!vslots[i]->changed) return reassignvslot(owner, vslots[i]); return vslots.add(new VSlot(&owner, vslots.length())); } static bool comparevslot(const VSlot &dst, const VSlot &src, int diff) { if(diff & (1<next) { if((!dst->changed || dst->changed == (src.changed | delta.changed)) && comparevslot(*dst, src, src.changed & ~delta.changed) && comparevslot(*dst, delta, delta.changed)) return dst; } return NULL; } static VSlot *clonevslot(const VSlot &src, const VSlot &delta) { VSlot *dst = vslots.add(new VSlot(src.slot, vslots.length())); dst->changed = src.changed | delta.changed; propagatevslot(*dst, src, ((1<=0x10000) { compactvslots(); allchanged(); if(vslots.length()>=0x10000) return NULL; } if(autocompactvslots && ++clonedvslots >= autocompactvslots) { compactvslots(); allchanged(); } return clonevslot(src, delta); } static void fixinsidefaces(cube *c, const ivec &o, int size, int tex) { loopi(8) { ivec co(i, o.x, o.y, o.z, size); if(c[i].children) fixinsidefaces(c[i].children, co, size>>1, tex); else loopj(6) if(!visibletris(c[i], j, co.x, co.y, co.z, size)) c[i].texture[j] = tex; } } ICOMMAND(fixinsidefaces, "i", (int *tex), { extern int nompedit; if(noedit(true) || (nompedit && multiplayer())) return; fixinsidefaces(worldroot, ivec(0, 0, 0), worldsize>>1, *tex && vslots.inrange(*tex) ? *tex : DEFAULT_GEOM); allchanged(); }); const struct slottex { const char *name; int id; } slottexs[] = { {"c", TEX_DIFFUSE}, {"u", TEX_UNKNOWN}, {"d", TEX_DECAL}, {"n", TEX_NORMAL}, {"g", TEX_GLOW}, {"s", TEX_SPEC}, {"z", TEX_DEPTH}, {"e", TEX_ENVMAP} }; int findslottex(const char *name) { loopi(sizeof(slottexs)/sizeof(slottex)) { if(!strcmp(slottexs[i].name, name)) return slottexs[i].id; } return -1; } void texture(char *type, char *name, int *rot, int *xoffset, int *yoffset, float *scale) { if(slots.length()>=0x10000) return; static int lastmatslot = -1; int tnum = findslottex(type), matslot = findmaterial(type); if(tnum<0) tnum = atoi(type); if(tnum==TEX_DIFFUSE) lastmatslot = matslot; else if(lastmatslot>=0) matslot = lastmatslot; else if(slots.empty()) return; Slot &s = matslot>=0 ? materialslots[matslot] : *(tnum!=TEX_DIFFUSE ? slots.last() : slots.add(new Slot(slots.length()))); s.loaded = false; s.texmask |= 1<=8) conoutf(CON_WARN, "warning: too many textures in slot %d", slots.length()-1); Slot::Tex &st = s.sts.add(); st.type = tnum; st.combined = -1; st.t = NULL; copystring(st.name, name); path(st.name); if(tnum==TEX_DIFFUSE) { setslotshader(s); VSlot &vs = matslot >= 0 ? materialslots[matslot] : *emptyvslot(s); vs.reset(); vs.rotation = clamp(*rot, 0, 5); vs.xoffset = max(*xoffset, 0); vs.yoffset = max(*yoffset, 0); vs.scale = *scale <= 0 ? 1 : *scale; propagatevslot(&vs, (1<")) : NULL; } COMMAND(autograss, "s"); void texscroll(float *scrollS, float *scrollT) { if(slots.empty()) return; Slot &s = *slots.last(); s.variants->scrollS = *scrollS/1000.0f; s.variants->scrollT = *scrollT/1000.0f; propagatevslot(s.variants, 1<xoffset = max(*xoffset, 0); s.variants->yoffset = max(*yoffset, 0); propagatevslot(s.variants, 1<rotation = clamp(*rot, 0, 5); propagatevslot(s.variants, 1<scale = *scale <= 0 ? 1 : *scale; propagatevslot(s.variants, 1<layer = *layer < 0 ? max(slots.length()-1+*layer, 0) : *layer; s.layermaskname = name[0] ? newstring(path(makerelpath("packages", name))) : NULL; s.layermaskmode = *mode; s.layermaskscale = *scale <= 0 ? 1 : *scale; propagatevslot(s.variants, 1<alphafront = clamp(*front, 0.0f, 1.0f); s.variants->alphaback = clamp(*back, 0.0f, 1.0f); propagatevslot(s.variants, 1<colorscale = vec(clamp(*r, 0.0f, 1.0f), clamp(*g, 0.0f, 1.0f), clamp(*b, 0.0f, 1.0f)); propagatevslot(s.variants, 1<0; } COMMAND(texffenv, "i"); static int findtextype(Slot &s, int type, int last = -1) { for(int i = last+1; i &key, Slot &slot, Slot::Tex &t, bool combined = false, const char *prefix = NULL) { if(combined) key.add('&'); if(prefix) { while(*prefix) key.add(*prefix++); } defformatstring(tname)("packages/%s", t.name); for(const char *s = path(tname); *s; key.add(*s++)); } static void texcombine(Slot &s, int index, Slot::Tex &t, bool forceload = false) { if(renderpath==R_FIXEDFUNCTION && t.type!=TEX_DIFFUSE && t.type!=TEX_GLOW && !forceload) { t.t = notexture; return; } vector key; addname(key, s, t); int texmask = 0; bool envmap = renderpath==R_FIXEDFUNCTION && s.shader->type&SHADER_ENVMAP && s.ffenv && hasCM && maxtmus >= 2; if(!forceload) switch(t.type) { case TEX_DIFFUSE: if(renderpath==R_FIXEDFUNCTION) { int mask = (1<=0;) { texmask |= 1<" : NULL); } break; } // fall through to shader case case TEX_NORMAL: { if(renderpath==R_FIXEDFUNCTION) break; int i = findtextype(s, t.type==TEX_DIFFUSE ? (1<= 0) continue; switch(t.type) { case TEX_ENVMAP: if(hasCM && (renderpath != R_FIXEDFUNCTION || (s.shader->type&SHADER_ENVMAP && s.ffenv && maxtmus >= 2) || forceload)) t.t = cubemapload(t.name); break; default: texcombine(s, i, t, forceload); break; } } s.loaded = true; return s; } MSlot &lookupmaterialslot(int index, bool load) { MSlot &s = materialslots[index]; if(load && !s.linked) { if(!s.loaded) loadslot(s, true); linkvslotshader(s); s.linked = true; } return s; } Slot &lookupslot(int index, bool load) { Slot &s = slots.inrange(index) ? *slots[index] : (slots.inrange(DEFAULT_GEOM) ? *slots[DEFAULT_GEOM] : dummyslot); return s.loaded || !load ? s : loadslot(s, false); } VSlot &lookupvslot(int index, bool load) { VSlot &s = vslots.inrange(index) && vslots[index]->slot ? *vslots[index] : (slots.inrange(DEFAULT_GEOM) && slots[DEFAULT_GEOM]->variants ? *slots[DEFAULT_GEOM]->variants : dummyvslot); if(load && !s.linked) { if(!s.slot->loaded) loadslot(*s.slot, false); linkvslotshader(s); s.linked = true; } return s; } void linkslotshaders() { loopv(slots) if(slots[i]->loaded) linkslotshader(*slots[i]); loopv(vslots) if(vslots[i]->linked) linkvslotshader(*vslots[i]); loopi((MATF_VOLUME|MATF_INDEX)+1) if(materialslots[i].loaded) { linkslotshader(materialslots[i]); linkvslotshader(materialslots[i]); } } Texture *loadthumbnail(Slot &slot) { if(slot.thumbnail) return slot.thumbnail; if(!slot.variants) { slot.thumbnail = notexture; return slot.thumbnail; } VSlot &vslot = *slot.variants; linkslotshader(slot, false); linkvslotshader(vslot, false); vector name; if(vslot.colorscale == vec(1, 1, 1)) addname(name, slot, slot.sts[0], false, ""); else { defformatstring(prefix)("", vslot.colorscale.x, vslot.colorscale.y, vslot.colorscale.z); addname(name, slot, slot.sts[0], false, prefix); } int glow = -1; if(slot.texmask&(1<= 0) { defformatstring(prefix)("", vslot.glowcolor.x, vslot.glowcolor.y, vslot.glowcolor.z); addname(name, slot, slot.sts[glow], true, prefix); } } VSlot *layer = vslot.layer ? &lookupvslot(vslot.layer, false) : NULL; if(layer) { if(layer->colorscale == vec(1, 1, 1)) addname(name, *layer->slot, layer->slot->sts[0], true, ""); else { defformatstring(prefix)("", vslot.colorscale.x, vslot.colorscale.y, vslot.colorscale.z); addname(name, *layer->slot, layer->slot->sts[0], true, prefix); } } name.add('\0'); Texture *t = textures.access(path(name.getbuf())); if(t) slot.thumbnail = t; else { ImageData s, g, l; texturedata(s, NULL, &slot.sts[0], false); if(glow >= 0) texturedata(g, NULL, &slot.sts[glow], false); if(layer) texturedata(l, NULL, &layer->slot->sts[0], false); if(!s.data) t = slot.thumbnail = notexture; else { if(vslot.colorscale != vec(1, 1, 1)) texmad(s, vslot.colorscale, vec(0, 0, 0)); int xs = s.w, ys = s.h; if(s.w > 64 || s.h > 64) scaleimage(s, min(s.w, 64), min(s.h, 64)); if(g.data) { if(g.w != s.w || g.h != s.h) scaleimage(g, s.w, s.h); addglow(s, g, vslot.glowcolor); } if(l.data) { if(layer->colorscale != vec(1, 1, 1)) texmad(l, layer->colorscale, vec(0, 0, 0)); if(l.w != s.w/2 || l.h != s.h/2) scaleimage(l, s.w/2, s.h/2); forcergbimage(s); forcergbimage(l); uchar *dstrow = &s.data[s.pitch*l.h + s.bpp*l.w], *srcrow = l.data; loop(y, l.h) { for(uchar *dst = dstrow, *src = srcrow, *end = &srcrow[l.w*l.bpp]; src < end; dst += s.bpp, src += l.bpp) loopk(3) dst[k] = src[k]; dstrow += s.pitch; srcrow += l.pitch; } } t = newtexture(NULL, name.getbuf(), s, 0, false, false, true); t->xs = xs; t->ys = ys; slot.thumbnail = t; } } return t; } void loadlayermasks() { loopv(slots) { Slot &slot = *slots[i]; if(slot.loaded && slot.layermaskname && !slot.layermask) { slot.layermask = new ImageData; texturedata(*slot.layermask, slot.layermaskname); if(!slot.layermask->data) DELETEP(slot.layermask); } } } // environment mapped reflections void forcecubemapload(GLuint tex) { extern int ati_cubemap_bug; if(!ati_cubemap_bug || !tex) return; glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); cubemapshader->set(); GLenum tex2d = glIsEnabled(GL_TEXTURE_2D), depthtest = glIsEnabled(GL_DEPTH_TEST), blend = glIsEnabled(GL_BLEND); if(tex2d) glDisable(GL_TEXTURE_2D); if(depthtest) glDisable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_CUBE_MAP_ARB); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, tex); if(!blend) glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBegin(GL_POINTS); loopi(3) { glColor4f(1, 1, 1, 0); glTexCoord3f(0, 0, 1); glVertex2f(0, 0); } glEnd(); if(!blend) glDisable(GL_BLEND); glDisable(GL_TEXTURE_CUBE_MAP_ARB); if(depthtest) glEnable(GL_DEPTH_TEST); if(tex2d) glEnable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } cubemapside cubemapsides[6] = { { GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB, "lf", true, true, true }, { GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB, "rt", false, false, true }, { GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB, "ft", true, false, false }, { GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB, "bk", false, true, false }, { GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB, "dn", false, false, true }, { GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB, "up", false, false, true }, }; VARFP(envmapsize, 4, 7, 10, setupmaterials()); Texture *cubemaploadwildcard(Texture *t, const char *name, bool mipit, bool msg, bool transient = false) { if(!hasCM) return NULL; string tname; if(!name) copystring(tname, t->name); else { copystring(tname, name); t = textures.access(path(tname)); if(t) { if(!transient && t->type&Texture::TRANSIENT) t->type &= ~Texture::TRANSIENT; return t; } } char *wildcard = strchr(tname, '*'); ImageData surface[6]; string sname; if(!wildcard) copystring(sname, tname); int tsize = 0, compress = 0; loopi(6) { if(wildcard) { copystring(sname, tname, wildcard-tname+1); concatstring(sname, cubemapsides[i].name); concatstring(sname, wildcard+1); } ImageData &s = surface[i]; texturedata(s, sname, NULL, msg, &compress); if(!s.data) return NULL; if(s.w != s.h) { if(msg) conoutf(CON_ERROR, "cubemap texture %s does not have square size", sname); return NULL; } if(s.compressed ? s.compressed!=surface[0].compressed || s.w!=surface[0].w || s.h!=surface[0].h || s.levels!=surface[0].levels : surface[0].compressed || s.bpp!=surface[0].bpp) { if(msg) conoutf(CON_ERROR, "cubemap texture %s doesn't match other sides' format", sname); return NULL; } tsize = max(tsize, max(s.w, s.h)); } if(name) { char *key = newstring(tname); t = &textures[key]; t->name = key; } t->type = Texture::CUBEMAP; if(transient) t->type |= Texture::TRANSIENT; GLenum format; if(surface[0].compressed) { format = uncompressedformat(surface[0].compressed); t->bpp = formatsize(format); t->type |= Texture::COMPRESSED; } else { format = texformat(surface[0].bpp); t->bpp = surface[0].bpp; } if(alphaformat(format)) t->type |= Texture::ALPHA; t->mipmap = mipit; t->clamp = 3; t->xs = t->ys = tsize; t->w = t->h = min(1<w, t->h, mipit, false, GL_TEXTURE_CUBE_MAP_ARB, compress, t->w, t->h); GLenum component = format; if(!surface[0].compressed) { component = compressedformat(format, t->w, t->h, compress); switch(component) { case GL_RGB: component = GL_RGB5; break; } } glGenTextures(1, &t->id); loopi(6) { ImageData &s = surface[i]; cubemapside &side = cubemapsides[i]; texreorient(s, side.flipx, side.flipy, side.swapxy); if(s.compressed) { int w = s.w, h = s.h, levels = s.levels, level = 0; uchar *data = s.data; while(levels > 1 && (w > t->w || h > t->h)) { data += s.calclevelsize(level++); levels--; if(w > 1) w /= 2; if(h > 1) h /= 2; } createcompressedtexture(!i ? t->id : 0, w, h, data, s.align, s.bpp, levels, 3, mipit ? 2 : 1, s.compressed, side.target); } else { createtexture(!i ? t->id : 0, t->w, t->h, s.data, 3, mipit ? 2 : 1, component, side.target, s.w, s.h, s.pitch, false, format); } } forcecubemapload(t->id); return t; } Texture *cubemapload(const char *name, bool mipit, bool msg, bool transient) { if(!hasCM) return NULL; string pname; copystring(pname, makerelpath("packages", name)); path(pname); Texture *t = NULL; if(!strchr(pname, '*')) { defformatstring(jpgname)("%s_*.jpg", pname); t = cubemaploadwildcard(NULL, jpgname, mipit, false, transient); if(!t) { defformatstring(pngname)("%s_*.png", pname); t = cubemaploadwildcard(NULL, pngname, mipit, false, transient); if(!t && msg) conoutf(CON_ERROR, "could not load envmap %s", name); } } else t = cubemaploadwildcard(NULL, pname, mipit, msg, transient); return t; } VAR(envmapradius, 0, 128, 10000); struct envmap { int radius, size, blur; vec o; GLuint tex; }; static vector envmaps; static Texture *skyenvmap = NULL; void clearenvmaps() { if(skyenvmap) { if(skyenvmap->type&Texture::TRANSIENT) cleanuptexture(skyenvmap); skyenvmap = NULL; } loopv(envmaps) glDeleteTextures(1, &envmaps[i].tex); envmaps.shrink(0); } VAR(aaenvmap, 0, 2, 4); GLuint genenvmap(const vec &o, int envmapsize, int blur) { int rendersize = 1<<(envmapsize+aaenvmap), sizelimit = min(hwcubetexsize, min(screen->w, screen->h)); if(maxtexsize) sizelimit = min(sizelimit, maxtexsize); while(rendersize > sizelimit) rendersize /= 2; int texsize = min(rendersize, 1< texsize) { scaletexture(src, rendersize, rendersize, 3, 3*rendersize, dst, texsize, texsize); swap(src, dst); } if(blur > 0) { blurtexture(blur, 3, texsize, texsize, src, dst); swap(src, dst); } createtexture(tex, texsize, texsize, src, 3, 2, GL_RGB5, side.target); } glFrontFace(GL_CW); delete[] pixels; glViewport(0, 0, screen->w, screen->h); clientkeepalive(); forcecubemapload(tex); return tex; } void initenvmaps() { if(!hasCM) return; clearenvmaps(); extern char *skybox; skyenvmap = skybox[0] ? cubemapload(skybox, true, false, true) : NULL; const vector &ents = entities::getents(); loopv(ents) { const extentity &ent = *ents[i]; if(ent.type != ET_ENVMAP) continue; envmap &em = envmaps.add(); em.radius = ent.attr1 ? clamp(int(ent.attr1), 0, 10000) : envmapradius; em.size = ent.attr2 ? clamp(int(ent.attr2), 4, 9) : 0; em.blur = ent.attr3 ? clamp(int(ent.attr3), 1, 2) : 0; em.o = ent.o; em.tex = 0; } } void genenvmaps() { if(envmaps.empty()) return; renderprogress(0, "generating environment maps..."); int lastprogress = SDL_GetTicks(); loopv(envmaps) { envmap &em = envmaps[i]; em.tex = genenvmap(em.o, em.size ? min(em.size, envmapsize) : envmapsize, em.blur); if(renderedframe) continue; int millis = SDL_GetTicks(); if(millis - lastprogress >= 250) { renderprogress(float(i+1)/envmaps.length(), "generating environment maps...", 0, true); lastprogress = millis; } } } ushort closestenvmap(const vec &o) { ushort minemid = EMID_SKY; float mindist = 1e16f; loopv(envmaps) { envmap &em = envmaps[i]; float dist = em.o.dist(o); if(dist < em.radius && dist < mindist) { minemid = EMID_RESERVED + i; mindist = dist; } } return minemid; } ushort closestenvmap(int orient, int x, int y, int z, int size) { vec loc(x, y, z); int dim = dimension(orient); if(dimcoord(orient)) loc[dim] += size; loc[R[dim]] += size/2; loc[C[dim]] += size/2; return closestenvmap(loc); } GLuint lookupenvmap(Slot &slot) { loopv(slot.sts) if(slot.sts[i].type==TEX_ENVMAP && slot.sts[i].t) return slot.sts[i].t->id; return skyenvmap ? skyenvmap->id : 0; } GLuint lookupenvmap(ushort emid) { if(emid==EMID_SKY || emid==EMID_CUSTOM) return skyenvmap ? skyenvmap->id : 0; if(emid==EMID_NONE || !envmaps.inrange(emid-EMID_RESERVED)) return 0; GLuint tex = envmaps[emid-EMID_RESERVED].tex; return tex ? tex : (skyenvmap ? skyenvmap->id : 0); } void cleanuptexture(Texture *t) { DELETEA(t->alphamask); if(t->id) { glDeleteTextures(1, &t->id); t->id = 0; } if(t->type&Texture::TRANSIENT) textures.remove(t->name); } void cleanuptextures() { clearenvmaps(); loopv(slots) slots[i]->cleanup(); loopv(vslots) vslots[i]->cleanup(); loopi((MATF_VOLUME|MATF_INDEX)+1) materialslots[i].cleanup(); enumerate(textures, Texture, tex, cleanuptexture(&tex)); } bool reloadtexture(const char *name) { Texture *t = textures.access(path(name, true)); if(t) return reloadtexture(*t); return true; } bool reloadtexture(Texture &tex) { if(tex.id) return true; switch(tex.type&Texture::TYPE) { case Texture::IMAGE: { int compress = 0; ImageData s; if(!texturedata(s, tex.name, NULL, true, &compress) || !newtexture(&tex, NULL, s, tex.clamp, tex.mipmap, false, false, compress)) return false; break; } case Texture::CUBEMAP: if(!cubemaploadwildcard(&tex, NULL, tex.mipmap, true)) return false; break; } return true; } void reloadtex(char *name) { Texture *t = textures.access(path(name, true)); if(!t) { conoutf(CON_ERROR, "texture %s is not loaded", name); return; } if(t->type&Texture::TRANSIENT) { conoutf(CON_ERROR, "can't reload transient texture %s", name); return; } DELETEA(t->alphamask); Texture oldtex = *t; t->id = 0; if(!reloadtexture(*t)) { if(t->id) glDeleteTextures(1, &t->id); *t = oldtex; conoutf(CON_ERROR, "failed to reload texture %s", name); } } COMMAND(reloadtex, "s"); void reloadtextures() { int reloaded = 0; enumerate(textures, Texture, tex, { loadprogress = float(++reloaded)/textures.numelems; reloadtexture(tex); }); loadprogress = 0; } enum { DDSD_CAPS = 0x00000001, DDSD_HEIGHT = 0x00000002, DDSD_WIDTH = 0x00000004, DDSD_PITCH = 0x00000008, DDSD_PIXELFORMAT = 0x00001000, DDSD_MIPMAPCOUNT = 0x00020000, DDSD_LINEARSIZE = 0x00080000, DDSD_BACKBUFFERCOUNT = 0x00800000, DDPF_ALPHAPIXELS = 0x00000001, DDPF_FOURCC = 0x00000004, DDPF_INDEXED = 0x00000020, DDPF_ALPHA = 0x00000002, DDPF_RGB = 0x00000040, DDPF_COMPRESSED = 0x00000080, DDPF_LUMINANCE = 0x00020000, DDSCAPS_COMPLEX = 0x00000008, DDSCAPS_TEXTURE = 0x00001000, DDSCAPS_MIPMAP = 0x00400000, DDSCAPS2_CUBEMAP = 0x00000200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000, DDSCAPS2_VOLUME = 0x00200000, FOURCC_DXT1 = 0x31545844, FOURCC_DXT2 = 0x32545844, FOURCC_DXT3 = 0x33545844, FOURCC_DXT4 = 0x34545844, FOURCC_DXT5 = 0x35545844 }; struct DDCOLORKEY { uint dwColorSpaceLowValue, dwColorSpaceHighValue; }; struct DDPIXELFORMAT { uint dwSize, dwFlags, dwFourCC; union { uint dwRGBBitCount, dwYUVBitCount, dwZBufferBitDepth, dwAlphaBitDepth, dwLuminanceBitCount, dwBumpBitCount, dwPrivateFormatBitCount; }; union { uint dwRBitMask, dwYBitMask, dwStencilBitDepth, dwLuminanceBitMask, dwBumpDuBitMask, dwOperations; }; union { uint dwGBitMask, dwUBitMask, dwZBitMask, dwBumpDvBitMask; struct { ushort wFlipMSTypes, wBltMSTypes; } MultiSampleCaps; }; union { uint dwBBitMask, dwVBitMask, dwStencilBitMask, dwBumpLuminanceBitMask; }; union { uint dwRGBAlphaBitMask, dwYUVAlphaBitMask, dwLuminanceAlphaBitMask, dwRGBZBitMask, dwYUVZBitMask; }; }; struct DDSCAPS2 { uint dwCaps, dwCaps2, dwCaps3, dwCaps4; }; struct DDSURFACEDESC2 { uint dwSize, dwFlags, dwHeight, dwWidth; union { int lPitch; uint dwLinearSize; }; uint dwBackBufferCount; union { uint dwMipMapCount, dwRefreshRate, dwSrcVBHandle; }; uint dwAlphaBitDepth, dwReserved, lpSurface; union { DDCOLORKEY ddckCKDestOverlay; uint dwEmptyFaceColor; }; DDCOLORKEY ddckCKDestBlt, ddckCKSrcOverlay, ddckCKSrcBlt; union { DDPIXELFORMAT ddpfPixelFormat; uint dwFVF; }; DDSCAPS2 ddsCaps; uint dwTextureStage; }; bool loaddds(const char *filename, ImageData &image) { stream *f = openfile(filename, "rb"); if(!f) return false; GLenum format = GL_FALSE; uchar magic[4]; if(f->read(magic, 4) != 4 || memcmp(magic, "DDS ", 4)) { delete f; return false; } DDSURFACEDESC2 d; if(f->read(&d, sizeof(d)) != sizeof(d)) { delete f; return false; } lilswap((uint *)&d, sizeof(d)/sizeof(uint)); if(d.dwSize != sizeof(DDSURFACEDESC2) || d.ddpfPixelFormat.dwSize != sizeof(DDPIXELFORMAT)) { delete f; return false; } if(d.ddpfPixelFormat.dwFlags & DDPF_FOURCC) { switch(d.ddpfPixelFormat.dwFourCC) { case FOURCC_DXT1: format = d.ddpfPixelFormat.dwFlags & DDPF_ALPHAPIXELS ? GL_COMPRESSED_RGBA_S3TC_DXT1_EXT : GL_COMPRESSED_RGB_S3TC_DXT1_EXT; break; case FOURCC_DXT2: case FOURCC_DXT3: format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; case FOURCC_DXT4: case FOURCC_DXT5: format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; } } if(!format) { delete f; return false; } if(dbgdds) conoutf(CON_DEBUG, "%s: format 0x%X, %d x %d, %d mipmaps", filename, format, d.dwWidth, d.dwHeight, d.dwMipMapCount); int bpp = 0; switch(format) { case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: bpp = 8; break; case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: bpp = 16; break; } image.setdata(NULL, d.dwWidth, d.dwHeight, bpp, d.dwMipMapCount, 4, format); int size = image.calcsize(); if(f->read(image.data, size) != size) { delete f; image.cleanup(); return false; } delete f; return true; } void gendds(char *infile, char *outfile) { if(!hasS3TC || usetexcompress <= 1) { conoutf(CON_ERROR, "OpenGL driver does not support S3TC texture compression"); return; } glHint(GL_TEXTURE_COMPRESSION_HINT_ARB, GL_NICEST); defformatstring(cfile)("%s", infile); extern void reloadtex(char *name); Texture *t = textures.access(path(cfile)); if(t) reloadtex(cfile); t = textureload(cfile); if(t==notexture) { conoutf(CON_ERROR, "failed loading %s", infile); return; } glBindTexture(GL_TEXTURE_2D, t->id); GLint compressed = 0, format = 0, width = 0, height = 0; glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_COMPRESSED_ARB, &compressed); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &format); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height); if(!compressed) { conoutf(CON_ERROR, "failed compressing %s", infile); return; } int fourcc = 0; switch(format) { case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: fourcc = FOURCC_DXT1; conoutf("compressed as DXT1"); break; case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: fourcc = FOURCC_DXT1; conoutf("compressed as DXT1a"); break; case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: fourcc = FOURCC_DXT3; conoutf("compressed as DXT3"); break; case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: fourcc = FOURCC_DXT5; conoutf("compressed as DXT5"); break; default: conoutf(CON_ERROR, "failed compressing %s: unknown format: 0x%X", infile, format); break; return; } if(!outfile[0]) { static string buf; copystring(buf, infile); int len = strlen(buf); if(len > 4 && buf[len-4]=='.') memcpy(&buf[len-4], ".dds", 4); else concatstring(buf, ".dds"); outfile = buf; } stream *f = openfile(path(outfile, true), "wb"); if(!f) { conoutf(CON_ERROR, "failed writing to %s", outfile); return; } int csize = 0; for(int lw = width, lh = height, level = 0;;) { GLint size = 0; glGetTexLevelParameteriv(GL_TEXTURE_2D, level++, GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB, &size); csize += size; if(max(lw, lh) <= 1) break; if(lw > 1) lw /= 2; if(lh > 1) lh /= 2; } DDSURFACEDESC2 d; memset(&d, 0, sizeof(d)); d.dwSize = sizeof(DDSURFACEDESC2); d.dwWidth = width; d.dwHeight = height; d.dwLinearSize = csize; d.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_LINEARSIZE | DDSD_MIPMAPCOUNT; d.ddsCaps.dwCaps = DDSCAPS_TEXTURE | DDSCAPS_COMPLEX | DDSCAPS_MIPMAP; d.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT); d.ddpfPixelFormat.dwFlags = DDPF_FOURCC | (format!=GL_COMPRESSED_RGB_S3TC_DXT1_EXT ? DDPF_ALPHAPIXELS : 0); d.ddpfPixelFormat.dwFourCC = fourcc; uchar *data = new uchar[csize], *dst = data; for(int lw = width, lh = height;;) { GLint size; glGetTexLevelParameteriv(GL_TEXTURE_2D, d.dwMipMapCount, GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB, &size); glGetCompressedTexImage_(GL_TEXTURE_2D, d.dwMipMapCount++, dst); dst += size; if(max(lw, lh) <= 1) break; if(lw > 1) lw /= 2; if(lh > 1) lh /= 2; } lilswap((uint *)&d, sizeof(d)/sizeof(uint)); f->write("DDS ", 4); f->write(&d, sizeof(d)); f->write(data, csize); delete f; delete[] data; conoutf("wrote DDS file %s", outfile); setuptexcompress(); } COMMAND(gendds, "ss"); void writepngchunk(stream *f, const char *type, uchar *data = NULL, uint len = 0) { f->putbig(len); f->write(type, 4); f->write(data, len); uint crc = crc32(0, Z_NULL, 0); crc = crc32(crc, (const Bytef *)type, 4); if(data) crc = crc32(crc, data, len); f->putbig(crc); } VARP(compresspng, 0, 9, 9); void savepng(const char *filename, ImageData &image, bool flip) { uchar ctype = 0; switch(image.bpp) { case 1: ctype = 0; break; case 2: ctype = 4; break; case 3: ctype = 2; break; case 4: ctype = 6; break; default: conoutf(CON_ERROR, "failed saving png to %s", filename); return; } stream *f = openfile(filename, "wb"); if(!f) { conoutf(CON_ERROR, "could not write to %s", filename); return; } uchar signature[] = { 137, 80, 78, 71, 13, 10, 26, 10 }; f->write(signature, sizeof(signature)); struct pngihdr { uint width, height; uchar bitdepth, colortype, compress, filter, interlace; } ihdr = { bigswap(image.w), bigswap(image.h), 8, ctype, 0, 0, 0 }; writepngchunk(f, "IHDR", (uchar *)&ihdr, 13); stream::offset idat = f->tell(); uint len = 0; f->write("\0\0\0\0IDAT", 8); uint crc = crc32(0, Z_NULL, 0); crc = crc32(crc, (const Bytef *)"IDAT", 4); z_stream z; z.zalloc = NULL; z.zfree = NULL; z.opaque = NULL; if(deflateInit(&z, compresspng) != Z_OK) goto error; uchar buf[1<<12]; z.next_out = (Bytef *)buf; z.avail_out = sizeof(buf); loopi(image.h) { uchar filter = 0; loopj(2) { z.next_in = j ? (Bytef *)image.data + (flip ? image.h-i-1 : i)*image.pitch : (Bytef *)&filter; z.avail_in = j ? image.w*image.bpp : 1; while(z.avail_in > 0) { if(deflate(&z, Z_NO_FLUSH) != Z_OK) goto cleanuperror; #define FLUSHZ do { \ int flush = sizeof(buf) - z.avail_out; \ crc = crc32(crc, buf, flush); \ len += flush; \ f->write(buf, flush); \ z.next_out = (Bytef *)buf; \ z.avail_out = sizeof(buf); \ } while(0) FLUSHZ; } } } for(;;) { int err = deflate(&z, Z_FINISH); if(err != Z_OK && err != Z_STREAM_END) goto cleanuperror; FLUSHZ; if(err == Z_STREAM_END) break; } deflateEnd(&z); f->seek(idat, SEEK_SET); f->putbig(len); f->seek(0, SEEK_END); f->putbig(crc); writepngchunk(f, "IEND"); delete f; return; cleanuperror: deflateEnd(&z); error: delete f; conoutf(CON_ERROR, "failed saving png to %s", filename); } struct tgaheader { uchar identsize; uchar cmaptype; uchar imagetype; uchar cmaporigin[2]; uchar cmapsize[2]; uchar cmapentrysize; uchar xorigin[2]; uchar yorigin[2]; uchar width[2]; uchar height[2]; uchar pixelsize; uchar descbyte; }; VARP(compresstga, 0, 1, 1); void savetga(const char *filename, ImageData &image, bool flip) { switch(image.bpp) { case 3: case 4: break; default: conoutf(CON_ERROR, "failed saving tga to %s", filename); return; } stream *f = openfile(filename, "wb"); if(!f) { conoutf(CON_ERROR, "could not write to %s", filename); return; } tgaheader hdr; memset(&hdr, 0, sizeof(hdr)); hdr.pixelsize = image.bpp*8; hdr.width[0] = image.w&0xFF; hdr.width[1] = (image.w>>8)&0xFF; hdr.height[0] = image.h&0xFF; hdr.height[1] = (image.h>>8)&0xFF; hdr.imagetype = compresstga ? 10 : 2; f->write(&hdr, sizeof(hdr)); uchar buf[128*4]; loopi(image.h) { uchar *src = image.data + (flip ? i : image.h - i - 1)*image.pitch; for(int remaining = image.w; remaining > 0;) { int raw = 1; if(compresstga) { int run = 1; for(uchar *scan = src; run < min(remaining, 128); run++) { scan += image.bpp; if(src[0]!=scan[0] || src[1]!=scan[1] || src[2]!=scan[2] || (image.bpp==4 && src[3]!=scan[3])) break; } if(run > 1) { f->putchar(0x80 | (run-1)); f->putchar(src[2]); f->putchar(src[1]); f->putchar(src[0]); if(image.bpp==4) f->putchar(src[3]); src += run*image.bpp; remaining -= run; if(remaining <= 0) break; } for(uchar *scan = src; raw < min(remaining, 128); raw++) { scan += image.bpp; if(src[0]==scan[0] && src[1]==scan[1] && src[2]==scan[2] && (image.bpp!=4 || src[3]==scan[3])) break; } f->putchar(raw - 1); } else raw = min(remaining, 128); uchar *dst = buf; loopj(raw) { dst[0] = src[2]; dst[1] = src[1]; dst[2] = src[0]; if(image.bpp==4) dst[3] = src[3]; dst += image.bpp; src += image.bpp; } f->write(buf, raw*image.bpp); remaining -= raw; } } delete f; } enum { IMG_BMP = 0, IMG_TGA = 1, IMG_PNG = 2, NUMIMG }; VARP(screenshotformat, 0, IMG_PNG, NUMIMG-1); const char *imageexts[NUMIMG] = { ".bmp", ".tga", ".png" }; int guessimageformat(const char *filename, int format = IMG_BMP) { int len = strlen(filename); loopi(NUMIMG) { int extlen = strlen(imageexts[i]); if(len >= extlen && !strcasecmp(&filename[len-extlen], imageexts[i])) return i; } return format; } void saveimage(const char *filename, int format, ImageData &image, bool flip = false) { switch(format) { case IMG_PNG: savepng(filename, image, flip); break; case IMG_TGA: savetga(filename, image, flip); break; default: { ImageData flipped(image.w, image.h, image.bpp, image.data); if(flip) texflip(flipped); SDL_Surface *s = wrapsurface(flipped.data, flipped.w, flipped.h, flipped.bpp); if(!s) break; stream *f = openfile(filename, "wb"); if(f) { SDL_SaveBMP_RW(s, f->rwops(), 1); delete f; } SDL_FreeSurface(s); break; } } } bool loadimage(const char *filename, ImageData &image) { SDL_Surface *s = loadsurface(path(filename, true)); if(!s) return false; image.wrap(s); return true; } SVARP(screenshotdir, ""); void screenshot(char *filename) { static string buf; int format = -1; copystring(buf, screenshotdir); if(screenshotdir[0]) { int len = strlen(buf); if(buf[len] != '/' && buf[len] != '\\' && len+1 < (int)sizeof(buf)) { buf[len] = '/'; buf[len+1] = '\0'; } const char *dir = findfile(buf, "w"); if(!fileexists(dir, "w")) createdir(dir); } if(filename[0]) { concatstring(buf, filename); format = guessimageformat(buf, -1); } else { defformatstring(name)("screenshot_%d", totalmillis); concatstring(buf, name); } if(format < 0) { format = screenshotformat; concatstring(buf, imageexts[format]); } ImageData image(screen->w, screen->h, 3); glPixelStorei(GL_PACK_ALIGNMENT, texalign(image.data, screen->w, 3)); glReadPixels(0, 0, screen->w, screen->h, GL_RGB, GL_UNSIGNED_BYTE, image.data); saveimage(path(buf), format, image, true); } COMMAND(screenshot, "s"); void flipnormalmapy(char *destfile, char *normalfile) // jpg/png /tga-> tga { ImageData ns; if(!loadimage(normalfile, ns)) return; ImageData d(ns.w, ns.h, 3); readwritetex(d, ns, dst[0] = src[0]; dst[1] = 255 - src[1]; dst[2] = src[2]; ); saveimage(destfile, guessimageformat(destfile, IMG_TGA), d); } void mergenormalmaps(char *heightfile, char *normalfile) // jpg/png/tga + tga -> tga { ImageData hs, ns; if(!loadimage(heightfile, hs) || !loadimage(normalfile, ns) || hs.w != ns.w || hs.h != ns.h) return; ImageData d(ns.w, ns.h, 3); read2writetex(d, hs, srch, ns, srcn, *(bvec *)dst = bvec(((bvec *)srcn)->tovec().mul(2).add(((bvec *)srch)->tovec()).normalize()); ); saveimage(normalfile, guessimageformat(normalfile, IMG_TGA), d); } COMMAND(flipnormalmapy, "ss"); COMMAND(mergenormalmaps, "ss"); sauerbraten-0.0.20130203.dfsg/engine/lightmap.cpp0000644000175000017500000027267312071421015021165 0ustar vincentvincent#include "engine.h" #define MAXLIGHTMAPTASKS 4096 #define LIGHTMAPBUFSIZE (2*1024*1024) struct lightmapinfo; struct lightmaptask; struct lightmapworker { uchar *buf; int bufstart, bufused; lightmapinfo *firstlightmap, *lastlightmap, *curlightmaps; cube *c; cubeext *ext; uchar *colorbuf; bvec *raybuf; uchar *ambient, *blur; vec *colordata, *raydata; int type, bpp, w, h, orient, rotate; VSlot *vslot; Slot *slot; vector lights; ShadowRayCache *shadowraycache; BlendMapCache *blendmapcache; bool needspace, doneworking; SDL_cond *spacecond; SDL_Thread *thread; lightmapworker(); ~lightmapworker(); void reset(); bool setupthread(); void cleanupthread(); static int work(void *data); }; struct lightmapinfo { lightmapinfo *next; cube *c; uchar *colorbuf; bvec *raybuf; bool packed; int type, w, h, bpp, bufsize, surface, layers; }; struct lightmaptask { ivec o; int size, usefaces, progress; cube *c; cubeext *ext; lightmapinfo *lightmaps; lightmapworker *worker; }; struct lightmapext { cube *c; cubeext *ext; }; static vector lightmapworkers; static vector lightmaptasks[2]; static vector lightmapexts; static int packidx = 0, allocidx = 0; static SDL_mutex *lightlock = NULL, *tasklock = NULL; static SDL_cond *fullcond = NULL, *emptycond = NULL; int lightmapping = 0; vector lightmaps; VARR(lightprecision, 1, 32, 1024); VARR(lighterror, 1, 8, 16); VARR(bumperror, 1, 3, 16); VARR(lightlod, 0, 0, 10); bvec ambientcolor(0x19, 0x19, 0x19), skylightcolor(0, 0, 0); HVARFR(ambient, 1, 0x191919, 0xFFFFFF, { if(ambient <= 255) ambient |= (ambient<<8) | (ambient<<16); ambientcolor = bvec((ambient>>16)&0xFF, (ambient>>8)&0xFF, ambient&0xFF); }); HVARFR(skylight, 0, 0, 0xFFFFFF, { if(skylight <= 255) skylight |= (skylight<<8) | (skylight<<16); skylightcolor = bvec((skylight>>16)&0xFF, (skylight>>8)&0xFF, skylight&0xFF); }); extern void setupsunlight(); bvec sunlightcolor(0, 0, 0); HVARFR(sunlight, 0, 0, 0xFFFFFF, { if(sunlight <= 255) sunlight |= (sunlight<<8) | (sunlight<<16); sunlightcolor = bvec((sunlight>>16)&0xFF, (sunlight>>8)&0xFF, sunlight&0xFF); setupsunlight(); }); FVARFR(sunlightscale, 0, 1, 16, setupsunlight()); vec sunlightdir(0, 0, 1); extern void setsunlightdir(); VARFR(sunlightyaw, 0, 0, 360, setsunlightdir()); VARFR(sunlightpitch, -90, 90, 90, setsunlightdir()); void setsunlightdir() { sunlightdir = vec(sunlightyaw*RAD, sunlightpitch*RAD); loopk(3) if(fabs(sunlightdir[k]) < 1e-5f) sunlightdir[k] = 0; sunlightdir.normalize(); setupsunlight(); } entity sunlightent; void setupsunlight() { memset(&sunlightent, 0, sizeof(sunlightent)); sunlightent.type = ET_LIGHT; sunlightent.attr1 = 0; sunlightent.attr2 = int(sunlightcolor.x*sunlightscale); sunlightent.attr3 = int(sunlightcolor.y*sunlightscale); sunlightent.attr4 = int(sunlightcolor.z*sunlightscale); float dist = min(min(sunlightdir.x ? 1/fabs(sunlightdir.x) : 1e16f, sunlightdir.y ? 1/fabs(sunlightdir.y) : 1e16f), sunlightdir.z ? 1/fabs(sunlightdir.z) : 1e16f); sunlightent.o = vec(sunlightdir).mul(dist*worldsize).add(vec(worldsize/2, worldsize/2, worldsize/2)); } VARR(skytexturelight, 0, 1, 1); static const surfaceinfo brightsurfaces[6] = { brightsurface, brightsurface, brightsurface, brightsurface, brightsurface, brightsurface }; void brightencube(cube &c) { if(!c.ext) newcubeext(c, 0, false); memcpy(c.ext->surfaces, brightsurfaces, sizeof(brightsurfaces)); } void setsurfaces(cube &c, const surfaceinfo *surfs, const vertinfo *verts, int numverts) { if(!c.ext || c.ext->maxverts < numverts) newcubeext(c, numverts, false); memcpy(c.ext->surfaces, surfs, sizeof(c.ext->surfaces)); memcpy(c.ext->verts(), verts, numverts*sizeof(vertinfo)); } void setsurface(cube &c, int orient, const surfaceinfo &src, const vertinfo *srcverts, int numsrcverts) { int dstoffset = 0; if(!c.ext) newcubeext(c, numsrcverts, true); else { int numbefore = 0, beforeoffset = 0; loopi(orient) { surfaceinfo &surf = c.ext->surfaces[i]; int numverts = surf.totalverts(); if(!numverts) continue; numbefore += numverts; beforeoffset = surf.verts + numverts; } int numafter = 0, afteroffset = c.ext->maxverts; for(int i = 5; i > orient; i--) { surfaceinfo &surf = c.ext->surfaces[i]; int numverts = surf.totalverts(); if(!numverts) continue; numafter += numverts; afteroffset = surf.verts; } if(afteroffset - beforeoffset >= numsrcverts) dstoffset = beforeoffset; else { cubeext *ext = c.ext; if(numbefore + numsrcverts + numafter > c.ext->maxverts) { ext = growcubeext(c.ext, numbefore + numsrcverts + numafter); memcpy(ext->surfaces, c.ext->surfaces, sizeof(ext->surfaces)); } int offset = 0; if(numbefore == beforeoffset) { if(numbefore && c.ext != ext) memcpy(ext->verts(), c.ext->verts(), numbefore*sizeof(vertinfo)); offset = numbefore; } else loopi(orient) { surfaceinfo &surf = ext->surfaces[i]; int numverts = surf.totalverts(); if(!numverts) continue; memmove(ext->verts() + offset, c.ext->verts() + surf.verts, numverts*sizeof(vertinfo)); surf.verts = offset; offset += numverts; } dstoffset = offset; offset += numsrcverts; if(numafter && offset > afteroffset) { offset += numafter; for(int i = 5; i > orient; i--) { surfaceinfo &surf = ext->surfaces[i]; int numverts = surf.totalverts(); if(!numverts) continue; offset -= numverts; memmove(ext->verts() + offset, c.ext->verts() + surf.verts, numverts*sizeof(vertinfo)); surf.verts = offset; } } if(c.ext != ext) setcubeext(c, ext); } } surfaceinfo &dst = c.ext->surfaces[orient]; dst = src; dst.verts = dstoffset; if(srcverts) memcpy(c.ext->verts() + dstoffset, srcverts, numsrcverts*sizeof(vertinfo)); } // quality parameters, set by the calclight arg VARN(lmshadows, lmshadows_, 0, 2, 2); VARN(lmaa, lmaa_, 0, 3, 3); VARN(lerptjoints, lerptjoints_, 0, 1, 1); static int lmshadows = 2, lmaa = 3, lerptjoints = 1; static uint progress = 0, taskprogress = 0; static GLuint progresstex = 0; static int progresstexticks = 0, progresslightmap = -1; bool calclight_canceled = false; volatile bool check_calclight_progress = false; void check_calclight_canceled() { if(interceptkey(SDLK_ESCAPE)) { calclight_canceled = true; loopv(lightmapworkers) lightmapworkers[i]->doneworking = true; } if(!calclight_canceled) check_calclight_progress = false; } void show_calclight_progress() { float bar1 = float(progress) / float(allocnodes); defformatstring(text1)("%d%% using %d textures", int(bar1 * 100), lightmaps.length()); if(LM_PACKW <= hwtexsize && !progresstex) { glGenTextures(1, &progresstex); createtexture(progresstex, LM_PACKW, LM_PACKH, NULL, 3, 1, GL_RGB); } // only update once a sec (4 * 250 ms ticks) to not kill performance if(progresstex && !calclight_canceled && progresslightmap >= 0 && !(progresstexticks++ % 4)) { if(tasklock) SDL_LockMutex(tasklock); LightMap &lm = lightmaps[progresslightmap]; uchar *data = lm.data; int bpp = lm.bpp; if(tasklock) SDL_UnlockMutex(tasklock); glBindTexture(GL_TEXTURE_2D, progresstex); glPixelStorei(GL_UNPACK_ALIGNMENT, texalign(data, LM_PACKW, bpp)); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, LM_PACKW, LM_PACKH, bpp > 3 ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, data); } renderprogress(bar1, text1, progresstexticks ? progresstex : 0); } #define CHECK_PROGRESS_LOCKED(exit, before, after) CHECK_CALCLIGHT_PROGRESS_LOCKED(exit, show_calclight_progress, before, after) #define CHECK_PROGRESS(exit) CHECK_PROGRESS_LOCKED(exit, , ) bool PackNode::insert(ushort &tx, ushort &ty, ushort tw, ushort th) { if((available < tw && available < th) || w < tw || h < th) return false; if(child1) { bool inserted = child1->insert(tx, ty, tw, th) || child2->insert(tx, ty, tw, th); available = max(child1->available, child2->available); if(!available) clear(); return inserted; } if(w == tw && h == th) { available = 0; tx = x; ty = y; return true; } if(w - tw > h - th) { child1 = new PackNode(x, y, tw, h); child2 = new PackNode(x + tw, y, w - tw, h); } else { child1 = new PackNode(x, y, w, th); child2 = new PackNode(x, y + th, w, h - th); } bool inserted = child1->insert(tx, ty, tw, th); available = max(child1->available, child2->available); return inserted; } bool LightMap::insert(ushort &tx, ushort &ty, uchar *src, ushort tw, ushort th) { if((type&LM_TYPE) != LM_BUMPMAP1 && !packroot.insert(tx, ty, tw, th)) return false; copy(tx, ty, src, tw, th); return true; } void LightMap::copy(ushort tx, ushort ty, uchar *src, ushort tw, ushort th) { uchar *dst = data + bpp * tx + ty * bpp * LM_PACKW; loopi(th) { memcpy(dst, src, bpp * tw); dst += bpp * LM_PACKW; src += bpp * tw; } ++lightmaps; lumels += tw * th; } static void insertunlit(int i) { LightMap &l = lightmaps[i]; if((l.type&LM_TYPE) == LM_BUMPMAP1) { l.unlitx = l.unlity = -1; return; } ushort x, y; uchar unlit[4] = { ambientcolor[0], ambientcolor[1], ambientcolor[2], 255 }; if(l.insert(x, y, unlit, 1, 1)) { if((l.type&LM_TYPE) == LM_BUMPMAP0) { bvec front(128, 128, 255); ASSERT(lightmaps[i+1].insert(x, y, front.v, 1, 1)); } l.unlitx = x; l.unlity = y; } } struct layoutinfo { ushort x, y, lmid; uchar w, h; }; static void insertlightmap(lightmapinfo &li, layoutinfo &si) { loopv(lightmaps) { if(lightmaps[i].type == li.type && lightmaps[i].insert(si.x, si.y, li.colorbuf, si.w, si.h)) { si.lmid = i + LMID_RESERVED; if((li.type&LM_TYPE) == LM_BUMPMAP0) ASSERT(lightmaps[i+1].insert(si.x, si.y, (uchar *)li.raybuf, si.w, si.h)); return; } } progresslightmap = lightmaps.length(); si.lmid = lightmaps.length() + LMID_RESERVED; LightMap &l = lightmaps.add(); l.type = li.type; l.bpp = li.bpp; l.data = new uchar[li.bpp*LM_PACKW*LM_PACKH]; memset(l.data, 0, li.bpp*LM_PACKW*LM_PACKH); ASSERT(l.insert(si.x, si.y, li.colorbuf, si.w, si.h)); if((li.type&LM_TYPE) == LM_BUMPMAP0) { LightMap &r = lightmaps.add(); r.type = LM_BUMPMAP1 | (li.type&~LM_TYPE); r.bpp = 3; r.data = new uchar[3*LM_PACKW*LM_PACKH]; memset(r.data, 0, 3*LM_PACKW*LM_PACKH); ASSERT(r.insert(si.x, si.y, (uchar *)li.raybuf, si.w, si.h)); } } static void copylightmap(lightmapinfo &li, layoutinfo &si) { lightmaps[si.lmid-LMID_RESERVED].copy(si.x, si.y, li.colorbuf, si.w, si.h); if((li.type&LM_TYPE)==LM_BUMPMAP0 && lightmaps.inrange(si.lmid+1-LMID_RESERVED)) lightmaps[si.lmid+1-LMID_RESERVED].copy(si.x, si.y, (uchar *)li.raybuf, si.w, si.h); } static inline bool htcmp(const lightmapinfo &k, const layoutinfo &v) { int kw = k.w, kh = k.h; if(kw != v.w || kh != v.h) return false; LightMap &vlm = lightmaps[v.lmid - LMID_RESERVED]; int ktype = k.type; if(ktype != vlm.type) return false; int kbpp = k.bpp; const uchar *kcolor = k.colorbuf, *vcolor = vlm.data + kbpp*(v.x + v.y*LM_PACKW); loopi(kh) { if(memcmp(kcolor, vcolor, kbpp*kw)) return false; kcolor += kbpp*kw; vcolor += kbpp*LM_PACKW; } if((ktype&LM_TYPE) != LM_BUMPMAP0) return true; const bvec *kdir = k.raybuf, *vdir = (const bvec *)lightmaps[v.lmid+1 - LMID_RESERVED].data; loopi(kh) { if(memcmp(kdir, vdir, kw*sizeof(bvec))) return false; kdir += kw; vdir += LM_PACKW; } return true; } static inline uint hthash(const lightmapinfo &k) { int kw = k.w, kh = k.h, kbpp = k.bpp; uint hash = kw + (kh<<8); const uchar *color = k.colorbuf; loopi(kw*kh) { hash ^= color[0] + (color[1] << 4) + (color[2] << 8); color += kbpp; } return hash; } static hashset compressed; VAR(lightcompress, 0, 3, 6); static bool packlightmap(lightmapinfo &l, layoutinfo &surface) { surface.w = l.w; surface.h = l.h; if((int)l.w <= lightcompress && (int)l.h <= lightcompress) { layoutinfo *val = compressed.access(l); if(!val) { insertlightmap(l, surface); compressed[l] = surface; } else { surface.x = val->x; surface.y = val->y; surface.lmid = val->lmid; return false; } } else insertlightmap(l, surface); return true; } static void updatelightmap(const layoutinfo &surface) { if(max(LM_PACKW, LM_PACKH) > hwtexsize) return; LightMap &lm = lightmaps[surface.lmid-LMID_RESERVED]; if(lm.tex < 0) { lm.offsetx = lm.offsety = 0; lm.tex = lightmaptexs.length(); LightMapTexture &tex = lightmaptexs.add(); tex.type = renderpath==R_FIXEDFUNCTION ? (lm.type&~LM_TYPE) | LM_DIFFUSE : lm.type; tex.w = LM_PACKW; tex.h = LM_PACKH; tex.unlitx = lm.unlitx; tex.unlity = lm.unlity; glGenTextures(1, &tex.id); createtexture(tex.id, tex.w, tex.h, NULL, 3, 1, tex.type&LM_ALPHA ? GL_RGBA : GL_RGB); if(renderpath!=R_FIXEDFUNCTION && (lm.type&LM_TYPE)==LM_BUMPMAP0 && lightmaps.inrange(surface.lmid+1-LMID_RESERVED)) { LightMap &lm2 = lightmaps[surface.lmid+1-LMID_RESERVED]; lm2.offsetx = lm2.offsety = 0; lm2.tex = lightmaptexs.length(); LightMapTexture &tex2 = lightmaptexs.add(); tex2.type = (lm.type&~LM_TYPE) | LM_BUMPMAP0; tex2.w = LM_PACKW; tex2.h = LM_PACKH; tex2.unlitx = lm2.unlitx; tex2.unlity = lm2.unlity; glGenTextures(1, &tex2.id); createtexture(tex2.id, tex2.w, tex2.h, NULL, 3, 1, GL_RGB); } } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ROW_LENGTH, LM_PACKW); glBindTexture(GL_TEXTURE_2D, lightmaptexs[lm.tex].id); glTexSubImage2D(GL_TEXTURE_2D, 0, lm.offsetx + surface.x, lm.offsety + surface.y, surface.w, surface.h, lm.type&LM_ALPHA ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, &lm.data[(surface.y*LM_PACKW + surface.x)*lm.bpp]); if(renderpath!=R_FIXEDFUNCTION && (lm.type&LM_TYPE)==LM_BUMPMAP0 && lightmaps.inrange(surface.lmid+1-LMID_RESERVED)) { LightMap &lm2 = lightmaps[surface.lmid+1-LMID_RESERVED]; glBindTexture(GL_TEXTURE_2D, lightmaptexs[lm2.tex].id); glTexSubImage2D(GL_TEXTURE_2D, 0, lm2.offsetx + surface.x, lm2.offsety + surface.y, surface.w, surface.h, GL_RGB, GL_UNSIGNED_BYTE, &lm2.data[(surface.y*LM_PACKW + surface.x)*3]); } glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); } static uint generatelumel(lightmapworker *w, const float tolerance, uint lightmask, const vector &lights, const vec &target, const vec &normal, vec &sample, int x, int y) { vec avgray(0, 0, 0); float r = 0, g = 0, b = 0; uint lightused = 0; loopv(lights) { if(lightmask&(1<type==ET_SPOTLIGHT) { vec spot = vec(light.attached->o).sub(light.o).normalize(); float maxatten = sincos360[clamp(int(light.attached->attr1), 1, 89)].x, spotatten = (ray.dot(spot) - maxatten) / (1 - maxatten); if(spotatten <= 0) continue; attenuation *= spotatten; } if(lmshadows && mag) { float dist = shadowray(w->shadowraycache, light.o, ray, mag - tolerance, RAY_SHADOW | (lmshadows > 1 ? RAY_ALPHAPOLY : 0)); if(dist < mag - tolerance) continue; } lightused |= 1<type&LM_TYPE) { case LM_BUMPMAP0: intensity = attenuation; avgray.add(ray.mul(-attenuation)); break; default: intensity = angle * attenuation; break; } r += intensity * float(light.attr2); g += intensity * float(light.attr3); b += intensity * float(light.attr4); } if(sunlight) { float angle = sunlightdir.dot(normal); if(angle > 0 && (!lmshadows || shadowray(w->shadowraycache, vec(sunlightdir).mul(tolerance).add(target), sunlightdir, 1e16f, RAY_SHADOW | (lmshadows > 1 ? RAY_ALPHAPOLY : 0) | (skytexturelight ? RAY_SKIPSKY : 0)) > 1e15f)) { float intensity; switch(w->type&LM_TYPE) { case LM_BUMPMAP0: intensity = 1; avgray.add(sunlightdir); break; default: intensity = angle; break; } r += intensity * (sunlightcolor.x*sunlightscale); g += intensity * (sunlightcolor.y*sunlightscale); b += intensity * (sunlightcolor.z*sunlightscale); } } switch(w->type&LM_TYPE) { case LM_BUMPMAP0: if(avgray.iszero()) break; // transform to tangent space extern vec orientation_tangent[6][3]; extern vec orientation_binormal[6][3]; vec S(orientation_tangent[w->rotate][dimension(w->orient)]), T(orientation_binormal[w->rotate][dimension(w->orient)]); normal.orthonormalize(S, T); avgray.normalize(); w->raydata[y*w->w+x].add(vec(S.dot(avgray)/S.magnitude(), T.dot(avgray)/T.magnitude(), normal.dot(avgray))); break; } sample.x = min(255.0f, max(r, float(ambientcolor[0]))); sample.y = min(255.0f, max(g, float(ambientcolor[1]))); sample.z = min(255.0f, max(b, float(ambientcolor[2]))); return lightused; } static bool lumelsample(const vec &sample, int aasample, int stride) { if(sample.x >= int(ambientcolor[0])+1 || sample.y >= int(ambientcolor[1])+1 || sample.z >= int(ambientcolor[2])+1) return true; #define NCHECK(n) \ if((n).x >= int(ambientcolor[0])+1 || (n).y >= int(ambientcolor[1])+1 || (n).z >= int(ambientcolor[2])+1) \ return true; const vec *n = &sample - stride - aasample; NCHECK(n[0]); NCHECK(n[aasample]); NCHECK(n[2*aasample]); n += stride; NCHECK(n[0]); NCHECK(n[2*aasample]); n += stride; NCHECK(n[0]); NCHECK(n[aasample]); NCHECK(n[2*aasample]); return false; } static void calcskylight(lightmapworker *w, const vec &o, const vec &normal, float tolerance, uchar *skylight, int flags = RAY_ALPHAPOLY, extentity *t = NULL) { static const vec rays[17] = { vec(cosf(21*RAD)*cosf(50*RAD), sinf(21*RAD)*cosf(50*RAD), sinf(50*RAD)), vec(cosf(111*RAD)*cosf(50*RAD), sinf(111*RAD)*cosf(50*RAD), sinf(50*RAD)), vec(cosf(201*RAD)*cosf(50*RAD), sinf(201*RAD)*cosf(50*RAD), sinf(50*RAD)), vec(cosf(291*RAD)*cosf(50*RAD), sinf(291*RAD)*cosf(50*RAD), sinf(50*RAD)), vec(cosf(66*RAD)*cosf(70*RAD), sinf(66*RAD)*cosf(70*RAD), sinf(70*RAD)), vec(cosf(156*RAD)*cosf(70*RAD), sinf(156*RAD)*cosf(70*RAD), sinf(70*RAD)), vec(cosf(246*RAD)*cosf(70*RAD), sinf(246*RAD)*cosf(70*RAD), sinf(70*RAD)), vec(cosf(336*RAD)*cosf(70*RAD), sinf(336*RAD)*cosf(70*RAD), sinf(70*RAD)), vec(0, 0, 1), vec(cosf(43*RAD)*cosf(60*RAD), sinf(43*RAD)*cosf(60*RAD), sinf(60*RAD)), vec(cosf(133*RAD)*cosf(60*RAD), sinf(133*RAD)*cosf(60*RAD), sinf(60*RAD)), vec(cosf(223*RAD)*cosf(60*RAD), sinf(223*RAD)*cosf(60*RAD), sinf(60*RAD)), vec(cosf(313*RAD)*cosf(60*RAD), sinf(313*RAD)*cosf(60*RAD), sinf(60*RAD)), vec(cosf(88*RAD)*cosf(80*RAD), sinf(88*RAD)*cosf(80*RAD), sinf(80*RAD)), vec(cosf(178*RAD)*cosf(80*RAD), sinf(178*RAD)*cosf(80*RAD), sinf(80*RAD)), vec(cosf(268*RAD)*cosf(80*RAD), sinf(268*RAD)*cosf(80*RAD), sinf(80*RAD)), vec(cosf(358*RAD)*cosf(80*RAD), sinf(358*RAD)*cosf(80*RAD), sinf(80*RAD)), }; flags |= RAY_SHADOW; if(skytexturelight) flags |= RAY_SKIPSKY; int hit = 0; if(w) loopi(17) { if(normal.dot(rays[i])>=0 && shadowray(w->shadowraycache, vec(rays[i]).mul(tolerance).add(o), rays[i], 1e16f, flags, t)>1e15f) hit++; } else loopi(17) { if(normal.dot(rays[i])>=0 && shadowray(vec(rays[i]).mul(tolerance).add(o), rays[i], 1e16f, flags, t)>1e15f) hit++; } loopk(3) skylight[k] = uchar(ambientcolor[k] + (max(skylightcolor[k], ambientcolor[k]) - ambientcolor[k])*hit/17.0f); } static inline bool hasskylight() { return skylightcolor[0]>ambientcolor[0] || skylightcolor[1]>ambientcolor[1] || skylightcolor[2]>ambientcolor[2]; } VARR(blurlms, 0, 0, 2); VARR(blurskylight, 0, 0, 2); static inline void generatealpha(lightmapworker *w, float tolerance, const vec &pos, uchar &alpha) { alpha = lookupblendmap(w->blendmapcache, pos); if(w->slot->layermask) { static const int sdim[] = { 1, 0, 0 }, tdim[] = { 2, 2, 1 }; int dim = dimension(w->orient); float k = 8.0f/w->vslot->scale, s = (pos[sdim[dim]] * k - w->vslot->xoffset) / w->slot->layermaskscale, t = (pos[tdim[dim]] * (dim <= 1 ? -k : k) - w->vslot->yoffset) / w->slot->layermaskscale; if((w->rotate&5)==1) swap(s, t); if(w->rotate>=2 && w->rotate<=4) s = -s; if((w->rotate>=1 && w->rotate<=2) || w->rotate==5) t = -t; const ImageData &mask = *w->slot->layermask; int mx = int(floor(s))%mask.w, my = int(floor(t))%mask.h; if(mx < 0) mx += mask.w; if(my < 0) my += mask.h; uchar maskval = mask.data[mask.bpp*(mx + 1) - 1 + mask.pitch*my]; switch(w->slot->layermaskmode) { case 2: alpha = min(alpha, maskval); break; case 3: alpha = max(alpha, maskval); break; case 4: alpha = min(alpha, uchar(0xFF - maskval)); break; case 5: alpha = max(alpha, uchar(0xFF - maskval)); break; default: alpha = maskval; break; } } } VAR(edgetolerance, 1, 4, 64); VAR(adaptivesample, 0, 2, 2); enum { NO_SURFACE = 0, SURFACE_AMBIENT_BOTTOM, SURFACE_AMBIENT_TOP, SURFACE_LIGHTMAP_BOTTOM, SURFACE_LIGHTMAP_TOP, SURFACE_LIGHTMAP_BLEND }; #define SURFACE_AMBIENT SURFACE_AMBIENT_BOTTOM #define SURFACE_LIGHTMAP SURFACE_LIGHTMAP_BOTTOM static bool generatelightmap(lightmapworker *w, float lpu, const lerpvert *lv, int numv, vec origin1, const vec &xstep1, const vec &ystep1, vec origin2, const vec &xstep2, const vec &ystep2, float side0, float sidestep) { static const float aacoords[8][2] = { {0.0f, 0.0f}, {-0.5f, -0.5f}, {0.0f, -0.5f}, {-0.5f, 0.0f}, {0.3f, -0.6f}, {0.6f, 0.3f}, {-0.3f, 0.6f}, {-0.6f, -0.3f}, }; float tolerance = 0.5 / lpu; uint lightmask = 0, lightused = 0; vec offsets1[8], offsets2[8]; loopi(8) { offsets1[i] = vec(xstep1).mul(aacoords[i][0]).add(vec(ystep1).mul(aacoords[i][1])); offsets2[i] = vec(xstep2).mul(aacoords[i][0]).add(vec(ystep2).mul(aacoords[i][1])); } if((w->type&LM_TYPE) == LM_BUMPMAP0) memset(w->raydata, 0, (LM_MAXW + 4)*(LM_MAXH + 4)*sizeof(vec)); origin1.sub(vec(ystep1).add(xstep1).mul(blurlms)); origin2.sub(vec(ystep2).add(xstep2).mul(blurlms)); int aasample = min(1 << lmaa, 4); int stride = aasample*(w->w+1); vec *sample = w->colordata; uchar *skylight = w->ambient; lerpbounds start, end; initlerpbounds(-blurlms, -blurlms, lv, numv, start, end); float sidex = side0 + blurlms*sidestep; for(int y = 0; y < w->h; ++y, sidex += sidestep) { vec normal, nstep; lerpnormal(-blurlms, y - blurlms, lv, numv, start, end, normal, nstep); for(int x = 0; x < w->w; ++x, normal.add(nstep), skylight += w->bpp) { #define EDGE_TOLERANCE(x, y) \ (x < blurlms \ || x+1 > w->w - blurlms \ || y < blurlms \ || y+1 > w->h - blurlms \ ? edgetolerance : 1) float t = EDGE_TOLERANCE(x, y) * tolerance; vec u = x < sidex ? vec(xstep1).mul(x).add(vec(ystep1).mul(y)).add(origin1) : vec(xstep2).mul(x).add(vec(ystep2).mul(y)).add(origin2); lightused |= generatelumel(w, t, 0, w->lights, u, vec(normal).normalize(), *sample, x, y); if(hasskylight()) { if((w->type&LM_TYPE)==LM_BUMPMAP0 || !adaptivesample || sample->xyz 1 ? RAY_ALPHAPOLY : 0); else loopk(3) skylight[k] = max(skylightcolor[k], ambientcolor[k]); } else loopk(3) skylight[k] = ambientcolor[k]; if(w->type&LM_ALPHA) generatealpha(w, t, u, skylight[3]); sample += aasample; } sample += aasample; } if(adaptivesample > 1 && min(w->w, w->h) >= 2) lightmask = ~lightused; sample = w->colordata; initlerpbounds(-blurlms, -blurlms, lv, numv, start, end); sidex = side0 + blurlms*sidestep; for(int y = 0; y < w->h; ++y, sidex += sidestep) { vec normal, nstep; lerpnormal(-blurlms, y - blurlms, lv, numv, start, end, normal, nstep); for(int x = 0; x < w->w; ++x, normal.add(nstep)) { vec ¢er = *sample++; if(adaptivesample && x > 0 && x+1 < w->w && y > 0 && y+1 < w->h && !lumelsample(center, aasample, stride)) loopi(aasample-1) *sample++ = center; else { #define AA_EDGE_TOLERANCE(x, y, i) EDGE_TOLERANCE(x + aacoords[i][0], y + aacoords[i][1]) vec u = x < sidex ? vec(xstep1).mul(x).add(vec(ystep1).mul(y)).add(origin1) : vec(xstep2).mul(x).add(vec(ystep2).mul(y)).add(origin2); const vec *offsets = x < sidex ? offsets1 : offsets2; vec n = vec(normal).normalize(); loopi(aasample-1) generatelumel(w, AA_EDGE_TOLERANCE(x, y, i+1) * tolerance, lightmask, w->lights, vec(u).add(offsets[i+1]), n, *sample++, x, y); if(lmaa == 3) { loopi(4) { vec s; generatelumel(w, AA_EDGE_TOLERANCE(x, y, i+4) * tolerance, lightmask, w->lights, vec(u).add(offsets[i+4]), n, s, x, y); center.add(s); } center.div(5); } } } if(aasample > 1) { vec u = w->w < sidex ? vec(xstep1).mul(w->w).add(vec(ystep1).mul(y)).add(origin1) : vec(xstep2).mul(w->w).add(vec(ystep2).mul(y)).add(origin2); const vec *offsets = w->w < sidex ? offsets1 : offsets2; vec n = vec(normal).normalize(); generatelumel(w, edgetolerance * tolerance, lightmask, w->lights, vec(u).add(offsets[1]), n, sample[1], w->w-1, y); if(aasample > 2) generatelumel(w, edgetolerance * tolerance, lightmask, w->lights, vec(u).add(offsets[3]), n, sample[3], w->w-1, y); } sample += aasample; } if(aasample > 1) { vec normal, nstep; lerpnormal(-blurlms, w->h - blurlms, lv, numv, start, end, normal, nstep); for(int x = 0; x <= w->w; ++x, normal.add(nstep)) { vec u = x < sidex ? vec(xstep1).mul(x).add(vec(ystep1).mul(w->h)).add(origin1) : vec(xstep2).mul(x).add(vec(ystep2).mul(w->h)).add(origin2); const vec *offsets = x < sidex ? offsets1 : offsets2; vec n = vec(normal).normalize(); generatelumel(w, edgetolerance * tolerance, lightmask, w->lights, vec(u).add(offsets[1]), n, sample[1], min(x, w->w-1), w->h-1); if(aasample > 2) generatelumel(w, edgetolerance * tolerance, lightmask, w->lights, vec(u).add(offsets[2]), n, sample[2], min(x, w->w-1), w->h-1); sample += aasample; } } return true; } static int finishlightmap(lightmapworker *w) { if(hasskylight() && blurskylight && (w->w>1 || w->h>1)) { blurtexture(blurskylight, w->bpp, w->w, w->h, w->blur, w->ambient); swap(w->blur, w->ambient); } vec *sample = w->colordata; int aasample = min(1 << lmaa, 4), stride = aasample*(w->w+1); float weight = 1.0f / (1.0f + 4.0f*lmaa), cweight = weight * (lmaa == 3 ? 5.0f : 1.0f); uchar *skylight = w->ambient; vec *ray = w->raydata; uchar *dstcolor = blurlms && (w->w > 1 || w->h > 1) ? w->blur : w->colorbuf; uchar mincolor[4] = { 255, 255, 255, 255 }, maxcolor[4] = { 0, 0, 0, 0 }; bvec *dstray = blurlms && (w->w > 1 || w->h > 1) ? (bvec *)w->raydata : w->raybuf; bvec minray(255, 255, 255), maxray(0, 0, 0); loop(y, w->h) { loop(x, w->w) { vec l(0, 0, 0); const vec ¢er = *sample++; loopi(aasample-1) l.add(*sample++); if(aasample > 1) { l.add(sample[1]); if(aasample > 2) l.add(sample[3]); } vec *next = sample + stride - aasample; if(aasample > 1) { l.add(next[1]); if(aasample > 2) l.add(next[2]); l.add(next[aasample+1]); } int r = int(center.x*cweight + l.x*weight), g = int(center.y*cweight + l.y*weight), b = int(center.z*cweight + l.z*weight), ar = skylight[0], ag = skylight[1], ab = skylight[2]; dstcolor[0] = max(ar, r); dstcolor[1] = max(ag, g); dstcolor[2] = max(ab, b); loopk(3) { mincolor[k] = min(mincolor[k], dstcolor[k]); maxcolor[k] = max(maxcolor[k], dstcolor[k]); } if(w->type&LM_ALPHA) { dstcolor[3] = skylight[3]; mincolor[3] = min(mincolor[3], dstcolor[3]); maxcolor[3] = max(maxcolor[3], dstcolor[3]); } if((w->type&LM_TYPE) == LM_BUMPMAP0) { if(ray->iszero()) dstray[0] = bvec(128, 128, 255); else { // bias the normals towards the amount of ambient/skylight in the lumel // this is necessary to prevent the light values in shaders from dropping too far below the skylight (to the ambient) if N.L is small ray->normalize(); int l = max(r, max(g, b)), a = max(ar, max(ag, ab)); ray->mul(max(l-a, 0)); ray->z += a; dstray[0] = bvec(ray->normalize()); } loopk(3) { minray[k] = min(minray[k], dstray[0][k]); maxray[k] = max(maxray[k], dstray[0][k]); } ray++; dstray++; } dstcolor += w->bpp; skylight += w->bpp; } sample += aasample; } if(int(maxcolor[0]) - int(mincolor[0]) <= lighterror && int(maxcolor[1]) - int(mincolor[1]) <= lighterror && int(maxcolor[2]) - int(mincolor[2]) <= lighterror && mincolor[3] >= maxcolor[3]) { uchar color[3]; loopk(3) color[k] = (int(maxcolor[k]) + int(mincolor[k])) / 2; if(color[0] <= int(ambientcolor[0]) + lighterror && color[1] <= int(ambientcolor[1]) + lighterror && color[2] <= int(ambientcolor[2]) + lighterror && (maxcolor[3]==0 || mincolor[3]==255)) return mincolor[3]==255 ? SURFACE_AMBIENT_TOP : SURFACE_AMBIENT_BOTTOM; if((w->type&LM_TYPE) != LM_BUMPMAP0 || (int(maxray.x) - int(minray.x) <= bumperror && int(maxray.y) - int(minray.z) <= bumperror && int(maxray.z) - int(minray.z) <= bumperror)) { memcpy(w->colorbuf, color, 3); if(w->type&LM_ALPHA) w->colorbuf[3] = mincolor[3]; if((w->type&LM_TYPE) == LM_BUMPMAP0) { loopk(3) w->raybuf[0][k] = uchar((int(maxray[k])+int(minray[k]))/2); } w->lastlightmap->w = w->w = 1; w->lastlightmap->h = w->h = 1; } } if(blurlms && (w->w>1 || w->h>1)) { blurtexture(blurlms, w->bpp, w->w, w->h, w->colorbuf, w->blur, blurlms); if((w->type&LM_TYPE) == LM_BUMPMAP0) blurnormals(blurlms, w->w, w->h, w->raybuf, (const bvec *)w->raydata, blurlms); w->lastlightmap->w = (w->w -= 2*blurlms); w->lastlightmap->h = (w->h -= 2*blurlms); } if(mincolor[3]==255) return SURFACE_LIGHTMAP_TOP; else if(maxcolor[3]==0) return SURFACE_LIGHTMAP_BOTTOM; else return SURFACE_LIGHTMAP_BLEND; } static int previewlightmapalpha(lightmapworker *w, float lpu, const vec &origin1, const vec &xstep1, const vec &ystep1, const vec &origin2, const vec &xstep2, const vec &ystep2, float side0, float sidestep) { extern int fullbrightlevel; float tolerance = 0.5 / lpu; uchar *dst = w->colorbuf; uchar minalpha = 255, maxalpha = 0; float sidex = side0; for(int y = 0; y < w->h; ++y, sidex += sidestep) { for(int x = 0; x < w->w; ++x, dst += 4) { vec u = x < sidex ? vec(xstep1).mul(x).add(vec(ystep1).mul(y)).add(origin1) : vec(xstep2).mul(x).add(vec(ystep2).mul(y)).add(origin2); loopk(3) dst[k] = fullbrightlevel; generatealpha(w, tolerance, u, dst[3]); minalpha = min(minalpha, dst[3]); maxalpha = max(maxalpha, dst[3]); } } if(minalpha==255) return SURFACE_AMBIENT_TOP; if(maxalpha==0) return SURFACE_AMBIENT_BOTTOM; if(minalpha==maxalpha) w->w = w->h = 1; if((w->type&LM_TYPE) == LM_BUMPMAP0) loopi(w->w*w->h) w->raybuf[i] = bvec(128, 128, 255); return SURFACE_LIGHTMAP_BLEND; } static void clearsurfaces(cube *c) { loopi(8) { if(c[i].ext) { loopj(6) { surfaceinfo &surf = c[i].ext->surfaces[j]; if(!surf.used()) continue; surf.clear(); int numverts = surf.numverts&MAXFACEVERTS; if(numverts) { if(!(c[i].merged&(1<verts() + surf.verts; loopk(numverts) { vertinfo &v = verts[k]; v.u = 0; v.v = 0; v.norm = 0; } } } } if(c[i].children) clearsurfaces(c[i].children); } } #define LIGHTCACHESIZE 1024 static struct lightcacheentry { int x, y; vector lights; } lightcache[LIGHTCACHESIZE]; #define LIGHTCACHEHASH(x, y) (((((x)^(y))<<5) + (((x)^(y))>>5)) & (LIGHTCACHESIZE - 1)) VARF(lightcachesize, 4, 6, 12, clearlightcache()); void clearlightcache(int id) { if(id >= 0) { const extentity &light = *entities::getents()[id]; int radius = light.attr1; if(radius) { for(int x = int(max(light.o.x-radius, 0.0f))>>lightcachesize, ex = int(min(light.o.x+radius, worldsize-1.0f))>>lightcachesize; x <= ex; x++) for(int y = int(max(light.o.y-radius, 0.0f))>>lightcachesize, ey = int(min(light.o.y+radius, worldsize-1.0f))>>lightcachesize; y <= ey; y++) { lightcacheentry &lce = lightcache[LIGHTCACHEHASH(x, y)]; if(lce.x != x || lce.y != y) continue; lce.x = -1; lce.lights.setsize(0); } return; } } for(lightcacheentry *lce = lightcache; lce < &lightcache[LIGHTCACHESIZE]; lce++) { lce->x = -1; lce->lights.setsize(0); } } const vector &checklightcache(int x, int y) { x >>= lightcachesize; y >>= lightcachesize; lightcacheentry &lce = lightcache[LIGHTCACHEHASH(x, y)]; if(lce.x == x && lce.y == y) return lce.lights; lce.lights.setsize(0); int csize = 1< &ents = entities::getents(); loopv(ents) { const extentity &light = *ents[i]; switch(light.type) { case ET_LIGHT: { int radius = light.attr1; if(radius > 0) { if(light.o.x + radius < cx || light.o.x - radius > cx + csize || light.o.y + radius < cy || light.o.y - radius > cy + csize) continue; } break; } default: continue; } lce.lights.add(i); } lce.x = x; lce.y = y; return lce.lights; } static inline void addlight(lightmapworker *w, const extentity &light, int cx, int cy, int cz, int size, const vec *v, const vec *n, int numv) { int radius = light.attr1; if(radius > 0) { if(light.o.x + radius < cx || light.o.x - radius > cx + size || light.o.y + radius < cy || light.o.y - radius > cy + size || light.o.z + radius < cz || light.o.z - radius > cz + size) return; } loopi(4) { vec p(light.o); p.sub(v[i]); float dist = p.dot(n[i]); if(dist >= 0 && (!radius || dist < radius)) { w->lights.add(&light); break; } } } static bool findlights(lightmapworker *w, int cx, int cy, int cz, int size, const vec *v, const vec *n, int numv, const Slot &slot, const VSlot &vslot) { w->lights.setsize(0); const vector &ents = entities::getents(); static volatile bool usinglightcache = false; if(size <= 1< &lights = checklightcache(cx, cy); loopv(lights) { const extentity &light = *ents[lights[i]]; switch(light.type) { case ET_LIGHT: addlight(w, light, cx, cy, cz, size, v, n, numv); break; } } if(lightlock) { usinglightcache = false; SDL_UnlockMutex(lightlock); } } else loopv(ents) { const extentity &light = *ents[i]; switch(light.type) { case ET_LIGHT: addlight(w, light, cx, cy, cz, size, v, n, numv); break; } } if(vslot.layer && (setblendmaporigin(w->blendmapcache, ivec(cx, cy, cz), size) || slot.layermask)) return true; return w->lights.length() || hasskylight() || sunlight; } static int packlightmaps(lightmapworker *w = NULL) { int numpacked = 0; for(; packidx < lightmaptasks[0].length(); packidx++, numpacked++) { lightmaptask &t = lightmaptasks[0][packidx]; if(!t.lightmaps) break; if(t.ext && t.c->ext != t.ext) { lightmapext &e = lightmapexts.add(); e.c = t.c; e.ext = t.ext; } progress = t.progress; lightmapinfo *l = t.lightmaps; if(l == (lightmapinfo *)-1) continue; int space = 0; for(; l && l->c == t.c; l = l->next) { l->packed = true; space += l->bufsize; if(l->surface < 0 || !t.ext) continue; surfaceinfo &surf = t.ext->surfaces[l->surface]; layoutinfo layout; packlightmap(*l, layout); int numverts = surf.numverts&MAXFACEVERTS; vertinfo *verts = t.ext->verts() + surf.verts; if(l->layers&LAYER_DUP) { if(l->type&LM_ALPHA) surf.lmid[0] = layout.lmid; else { surf.lmid[1] = layout.lmid; verts += numverts; } } else { if(l->layers&LAYER_TOP) surf.lmid[0] = layout.lmid; if(l->layers&LAYER_BOTTOM) surf.lmid[1] = layout.lmid; } ushort offsetx = layout.x*((USHRT_MAX+1)/LM_PACKW), offsety = layout.y*((USHRT_MAX+1)/LM_PACKH); loopk(numverts) { vertinfo &v = verts[k]; v.u += offsetx; v.v += offsety; } } if(t.worker == w) { w->bufused -= space; w->bufstart = (w->bufstart + space)%LIGHTMAPBUFSIZE; w->firstlightmap = l; if(!l) { w->lastlightmap = NULL; w->bufstart = w->bufused = 0; } } if(t.worker->needspace) SDL_CondSignal(t.worker->spacecond); } return numpacked; } static lightmapinfo *alloclightmap(lightmapworker *w) { int needspace1 = sizeof(lightmapinfo) + w->w*w->h*w->bpp, needspace2 = (w->type&LM_TYPE) == LM_BUMPMAP0 ? w->w*w->h*3 : 0, needspace = needspace1 + needspace2, bufend = (w->bufstart + w->bufused)%LIGHTMAPBUFSIZE, availspace = LIGHTMAPBUFSIZE - w->bufused, availspace1 = min(availspace, LIGHTMAPBUFSIZE - bufend), availspace2 = min(availspace, w->bufstart); if(availspace < needspace || (max(availspace1, availspace2) < needspace && (availspace1 < needspace1 || availspace2 < needspace2))) { if(tasklock) SDL_LockMutex(tasklock); while(!w->doneworking) { lightmapinfo *l = w->firstlightmap; for(; l && l->packed; l = l->next) { w->bufused -= l->bufsize; w->bufstart = (w->bufstart + l->bufsize)%LIGHTMAPBUFSIZE; } w->firstlightmap = l; if(!l) { w->lastlightmap = NULL; w->bufstart = w->bufused = 0; } bufend = (w->bufstart + w->bufused)%LIGHTMAPBUFSIZE; availspace = LIGHTMAPBUFSIZE - w->bufused; availspace1 = min(availspace, LIGHTMAPBUFSIZE - bufend); availspace2 = min(availspace, w->bufstart); if(availspace >= needspace && (max(availspace1, availspace2) >= needspace || (availspace1 >= needspace1 && availspace2 >= needspace2))) break; if(packlightmaps(w)) continue; if(!w->spacecond || !tasklock) break; w->needspace = true; SDL_CondWait(w->spacecond, tasklock); w->needspace = false; } if(tasklock) SDL_UnlockMutex(tasklock); } int usedspace = needspace; lightmapinfo *l = NULL; if(availspace1 >= needspace1) { l = (lightmapinfo *)&w->buf[bufend]; w->colorbuf = (uchar *)(l + 1); if((w->type&LM_TYPE) != LM_BUMPMAP0) w->raybuf = NULL; else if(availspace1 >= needspace) w->raybuf = (bvec *)&w->buf[bufend + needspace1]; else { w->raybuf = (bvec *)w->buf; usedspace += availspace1 - needspace1; } } else if(availspace2 >= needspace) { usedspace += availspace1; l = (lightmapinfo *)w->buf; w->colorbuf = (uchar *)(l + 1); w->raybuf = (w->type&LM_TYPE) == LM_BUMPMAP0 ? (bvec *)&w->buf[needspace1] : NULL; } else return NULL; w->bufused += usedspace; l->next = NULL; l->c = w->c; l->type = w->type; l->w = w->w; l->h = w->h; l->bpp = w->bpp; l->colorbuf = w->colorbuf; l->raybuf = w->raybuf; l->packed = false; l->bufsize = usedspace; l->surface = -1; l->layers = 0; if(!w->firstlightmap) w->firstlightmap = l; if(w->lastlightmap) w->lastlightmap->next = l; w->lastlightmap = l; if(!w->curlightmaps) w->curlightmaps = l; return l; } static void freelightmap(lightmapworker *w) { lightmapinfo *l = w->lastlightmap; if(!l || l->surface >= 0) return; if(w->firstlightmap == w->lastlightmap) { w->firstlightmap = w->lastlightmap = w->curlightmaps = NULL; w->bufstart = w->bufused = 0; } else { w->bufused -= l->bufsize - sizeof(lightmapinfo); l->bufsize = sizeof(lightmapinfo); l->packed = true; } if(w->curlightmaps == l) w->curlightmaps = NULL; } static int setupsurface(lightmapworker *w, plane planes[2], int numplanes, const vec *p, const vec *n, int numverts, vertinfo *litverts, bool preview = false) { vec u, v, t; vec2 c[MAXFACEVERTS]; u = vec(p[2]).sub(p[0]).normalize(); v.cross(planes[0], u); c[0] = vec2(0, 0); if(numplanes >= 2) t.cross(planes[1], u); else t = v; vec r1 = vec(p[1]).sub(p[0]); c[1] = vec2(r1.dot(u), min(r1.dot(v), 0.0f)); c[2] = vec2(vec(p[2]).sub(p[0]).dot(u), 0); for(int i = 3; i < numverts; i++) { vec r = vec(p[i]).sub(p[0]); c[i] = vec2(r.dot(u), max(r.dot(t), 0.0f)); } float carea = 1e16f; vec2 cx(0, 0), cy(0, 0), co(0, 0), cmin(0, 0), cmax(0, 0); loopi(numverts) { vec2 px = vec2(c[i+1 < numverts ? i+1 : 0]).sub(c[i]); float len = px.squaredlen(); if(!len) continue; px.mul(1/sqrtf(len)); vec2 py(-px.y, px.x), pmin(0, 0), pmax(0, 0); if(numplanes >= 2 && (i == 0 || i >= 3)) px.neg(); loopj(numverts) { vec2 rj = vec2(c[j]).sub(c[i]), pj(rj.dot(px), rj.dot(py)); pmin.x = min(pmin.x, pj.x); pmin.y = min(pmin.y, pj.y); pmax.x = max(pmax.x, pj.x); pmax.y = max(pmax.y, pj.y); } float area = (pmax.x-pmin.x)*(pmax.y-pmin.y); if(area < carea) { carea = area; cx = px; cy = py; co = c[i]; cmin = pmin; cmax = pmax; } } int scale = int(min(cmax.x - cmin.x, cmax.y - cmin.y)); float lpu = 16.0f / float(lightlod && scale < (1 << lightlod) ? max(lightprecision / 2, 1) : lightprecision); int lw = clamp(int(ceil((cmax.x - cmin.x + 1)*lpu)), LM_MINW, LM_MAXW), lh = clamp(int(ceil((cmax.y - cmin.y + 1)*lpu)), LM_MINH, LM_MAXH); w->w = lw; w->h = lh; if(!preview) { w->w += 2*blurlms; w->h += 2*blurlms; } if(!alloclightmap(w)) return NO_SURFACE; vec2 cscale = vec2(cmax).sub(cmin).div(vec2(lw-1, lh-1)), comin = vec2(cx).mul(cmin.x).add(vec2(cy).mul(cmin.y)).add(co); loopi(numverts) { vec2 ri = vec2(c[i]).sub(comin); c[i] = vec2(ri.dot(cx)/cscale.x, ri.dot(cy)/cscale.y); } vec xstep1 = vec(v).mul(cx.y).add(vec(u).mul(cx.x)).mul(cscale.x), ystep1 = vec(v).mul(cy.y).add(vec(u).mul(cy.x)).mul(cscale.y), origin1 = vec(v).mul(comin.y).add(vec(u).mul(comin.x)).add(p[0]), xstep2 = xstep1, ystep2 = ystep1, origin2 = origin1; float side0 = LM_MAXW + 1, sidestep = 0; if(numplanes >= 2) { xstep2 = vec(t).mul(cx.y).add(vec(u).mul(cx.x)).mul(cscale.x); ystep2 = vec(t).mul(cy.y).add(vec(u).mul(cy.x)).mul(cscale.y); origin2 = vec(t).mul(comin.y).add(vec(u).mul(comin.x)).add(p[0]); if(cx.y) { side0 = comin.y/-(cx.y*cscale.x); sidestep = cy.y*cscale.y/-(cx.y*cscale.x); } else if(cy.y) { side0 = ceil(comin.y/-(cy.y*cscale.y))*(LM_MAXW + 1); sidestep = -(LM_MAXW + 1); if(cy.y < 0) { side0 = (LM_MAXW + 1) - side0; sidestep = -sidestep; } } else side0 = comin.y <= 0 ? LM_MAXW + 1 : -1; } int surftype = NO_SURFACE; if(preview) { surftype = previewlightmapalpha(w, lpu, origin1, xstep1, ystep1, origin2, xstep2, ystep2, side0, sidestep); } else { lerpvert lv[MAXFACEVERTS]; int numv = numverts; calclerpverts(c, n, lv, numv); if(!generatelightmap(w, lpu, lv, numv, origin1, xstep1, ystep1, origin2, xstep2, ystep2, side0, sidestep)) return NO_SURFACE; surftype = finishlightmap(w); } if(surftypew) texscale.x *= float(w->w - 1) / (lw - 1); if(lh != w->h) texscale.y *= float(w->h - 1) / (lh - 1); loopk(numverts) { litverts[k].u = ushort(floor(clamp(c[k].x*texscale.x, 0.0f, float(USHRT_MAX)))); litverts[k].v = ushort(floor(clamp(c[k].y*texscale.y, 0.0f, float(USHRT_MAX)))); } return surftype; } static void removelmalpha(lightmapworker *w) { if(!(w->type&LM_ALPHA)) return; for(uchar *dst = w->colorbuf, *src = w->colorbuf, *end = &src[w->w*w->h*4]; src < end; dst += 3, src += 4) { dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; } w->type &= ~LM_ALPHA; w->bpp = 3; w->lastlightmap->type = w->type; w->lastlightmap->bpp = w->bpp; } static lightmapinfo *setupsurfaces(lightmapworker *w, lightmaptask &task) { cube &c = *task.c; const ivec &co = task.o; int size = task.size, usefacemask = task.usefaces; w->curlightmaps = NULL; w->c = &c; surfaceinfo surfaces[6]; vertinfo litverts[6*2*MAXFACEVERTS]; int numlitverts = 0; memset(surfaces, 0, sizeof(surfaces)); loopi(6) { int usefaces = usefacemask&0xF; usefacemask >>= 4; if(!usefaces) { if(!c.ext) continue; surfaceinfo &surf = surfaces[i]; surf = c.ext->surfaces[i]; int numverts = surf.totalverts(); if(numverts) { memcpy(&litverts[numlitverts], c.ext->verts() + surf.verts, numverts*sizeof(vertinfo)); surf.verts = numlitverts; numlitverts += numverts; } continue; } VSlot &vslot = lookupvslot(c.texture[i], false), *layer = vslot.layer && !(c.material&MAT_ALPHA) ? &lookupvslot(vslot.layer, false) : NULL; Shader *shader = vslot.slot->shader; int shadertype = shader->type; if(layer) shadertype |= layer->slot->shader->type; surfaceinfo &surf = surfaces[i]; vertinfo *curlitverts = &litverts[numlitverts]; int numverts = c.ext ? c.ext->surfaces[i].numverts&MAXFACEVERTS : 0; ivec mo(co); int msz = size, convex = 0; if(numverts) { vertinfo *verts = c.ext->verts() + c.ext->surfaces[i].verts; loopj(numverts) curlitverts[j].set(verts[j].getxyz()); if(c.merged&(1<slot = vslot.slot; w->vslot = &vslot; w->type = shader->type&SHADER_NORMALSLMS ? LM_BUMPMAP0 : LM_DIFFUSE; if(layer) w->type |= LM_ALPHA; w->bpp = w->type&LM_ALPHA ? 4 : 3; w->orient = i; w->rotate = vslot.rotation; int surftype = setupsurface(w, planes, numplanes, pos, n, numverts, curlitverts); switch(surftype) { case SURFACE_LIGHTMAP_BOTTOM: if((shader->type^layer->slot->shader->type)&SHADER_NORMALSLMS || (shader->type&SHADER_NORMALSLMS && vslot.rotation!=layer->rotation)) { freelightmap(w); break; } // fall through case SURFACE_LIGHTMAP_BLEND: case SURFACE_LIGHTMAP_TOP: { if(!(surf.numverts&MAXFACEVERTS)) { surf.verts = numlitverts; surf.numverts |= numverts; numlitverts += numverts; } w->lastlightmap->surface = i; w->lastlightmap->layers = (surftype==SURFACE_LIGHTMAP_BOTTOM ? LAYER_BOTTOM : LAYER_TOP); if(surftype==SURFACE_LIGHTMAP_BLEND) { surf.numverts |= LAYER_BLEND; w->lastlightmap->layers = LAYER_TOP; if((shader->type^layer->slot->shader->type)&SHADER_NORMALSLMS || (shader->type&SHADER_NORMALSLMS && vslot.rotation!=layer->rotation)) break; w->lastlightmap->layers |= LAYER_BOTTOM; } else { if(surftype==SURFACE_LIGHTMAP_BOTTOM) { surf.numverts |= LAYER_BOTTOM; w->lastlightmap->layers = LAYER_BOTTOM; } else { surf.numverts |= LAYER_TOP; w->lastlightmap->layers = LAYER_TOP; } if(w->type&LM_ALPHA) removelmalpha(w); } continue; } case SURFACE_AMBIENT_BOTTOM: freelightmap(w); surf.numverts |= layer ? LAYER_BOTTOM : LAYER_TOP; continue; case SURFACE_AMBIENT_TOP: freelightmap(w); surf.numverts |= LAYER_TOP; continue; default: freelightmap(w); continue; } w->slot = layer->slot; w->vslot = layer; w->type = layer->slot->shader->type&SHADER_NORMALSLMS ? LM_BUMPMAP0 : LM_DIFFUSE; w->bpp = 3; w->rotate = layer->rotation; vertinfo *blendverts = surf.numverts&MAXFACEVERTS ? &curlitverts[numverts] : curlitverts; switch(setupsurface(w, planes, numplanes, pos, n, numverts, blendverts)) { case SURFACE_LIGHTMAP_TOP: { if(!(surf.numverts&MAXFACEVERTS)) { surf.verts = numlitverts; surf.numverts |= numverts; numlitverts += numverts; } else if(!(surf.numverts&LAYER_DUP)) { surf.numverts |= LAYER_DUP; w->lastlightmap->layers |= LAYER_DUP; loopk(numverts) { vertinfo &src = curlitverts[k]; vertinfo &dst = blendverts[k]; dst.setxyz(src.getxyz()); dst.norm = src.norm; } numlitverts += numverts; } surf.numverts |= LAYER_BOTTOM; w->lastlightmap->layers |= LAYER_BOTTOM; w->lastlightmap->surface = i; break; } case SURFACE_AMBIENT_TOP: { freelightmap(w); surf.numverts |= LAYER_BOTTOM; break; } default: freelightmap(w); break; } } loopk(6) { surfaceinfo &surf = surfaces[k]; if(surf.used()) { cubeext *ext = c.ext && c.ext->maxverts >= numlitverts ? c.ext : growcubeext(c.ext, numlitverts); memcpy(ext->surfaces, surfaces, sizeof(ext->surfaces)); memcpy(ext->verts(), litverts, numlitverts*sizeof(vertinfo)); task.ext = ext; break; } } return w->curlightmaps ? w->curlightmaps : (lightmapinfo *)-1; } int lightmapworker::work(void *data) { lightmapworker *w = (lightmapworker *)data; SDL_LockMutex(tasklock); while(!w->doneworking) { if(allocidx < lightmaptasks[0].length()) { lightmaptask &t = lightmaptasks[0][allocidx++]; t.worker = w; SDL_UnlockMutex(tasklock); lightmapinfo *l = setupsurfaces(w, t); SDL_LockMutex(tasklock); t.lightmaps = l; packlightmaps(w); } else { if(packidx >= lightmaptasks[0].length()) SDL_CondSignal(emptycond); SDL_CondWait(fullcond, tasklock); } } SDL_UnlockMutex(tasklock); return 0; } static bool processtasks(bool finish = false) { if(tasklock) SDL_LockMutex(tasklock); while(finish || lightmaptasks[1].length()) { if(packidx >= lightmaptasks[0].length()) { if(lightmaptasks[1].empty()) break; lightmaptasks[0].setsize(0); lightmaptasks[0].move(lightmaptasks[1]); packidx = allocidx = 0; if(fullcond) SDL_CondBroadcast(fullcond); } else if(lightmapping > 1) { SDL_CondWaitTimeout(emptycond, tasklock, 250); CHECK_PROGRESS_LOCKED({ SDL_UnlockMutex(tasklock); return false; }, SDL_UnlockMutex(tasklock), SDL_LockMutex(tasklock)); } else { while(allocidx < lightmaptasks[0].length()) { lightmaptask &t = lightmaptasks[0][allocidx++]; t.worker = lightmapworkers[0]; t.lightmaps = setupsurfaces(lightmapworkers[0], t); packlightmaps(lightmapworkers[0]); CHECK_PROGRESS(return false); } } } if(tasklock) SDL_UnlockMutex(tasklock); return true; } static void generatelightmaps(cube *c, int cx, int cy, int cz, int size) { CHECK_PROGRESS(return); taskprogress++; loopi(8) { ivec o(i, cx, cy, cz, size); if(c[i].children) generatelightmaps(c[i].children, o.x, o.y, o.z, size >> 1); else if(!isempty(c[i])) { if(c[i].ext) { loopj(6) { surfaceinfo &surf = c[i].ext->surfaces[j]; if(surf.lmid[0] >= LMID_RESERVED || surf.lmid[1] >= LMID_RESERVED) goto nextcube; surf.clear(); } } int usefacemask = 0; loopj(6) if(c[i].texture[j] != DEFAULT_SKY && (!(c[i].merged&(1<surfaces[j].numverts&MAXFACEVERTS))) { usefacemask |= visibletris(c[i], j, o.x, o.y, o.z, size)<<(4*j); } if(usefacemask) { lightmaptask &t = lightmaptasks[1].add(); t.o = o; t.size = size; t.usefaces = usefacemask; t.c = &c[i]; t.ext = NULL; t.lightmaps = NULL; t.progress = taskprogress; if(lightmaptasks[1].length() >= MAXLIGHTMAPTASKS && !processtasks()) return; } } nextcube:; } } static bool previewblends(lightmapworker *w, cube &c, const ivec &co, int size) { if(isempty(c) || c.material&MAT_ALPHA) return false; int usefacemask = 0; loopi(6) if(c.texture[i] != DEFAULT_SKY && lookupvslot(c.texture[i], false).layer) usefacemask |= visibletris(c, i, co.x, co.y, co.z, size)<<(4*i); if(!usefacemask) return false; if(!setblendmaporigin(w->blendmapcache, co, size)) { if(!c.ext) return false; bool blends = false; loopi(6) if(c.ext->surfaces[i].numverts&LAYER_BOTTOM) { c.ext->surfaces[i].brighten(); blends = true; } return blends; } w->firstlightmap = w->lastlightmap = w->curlightmaps = NULL; w->bufstart = w->bufused = 0; w->c = &c; surfaceinfo surfaces[6]; vertinfo litverts[6*2*MAXFACEVERTS]; int numlitverts = 0; memcpy(surfaces, c.ext ? c.ext->surfaces : brightsurfaces, sizeof(surfaces)); loopi(6) { int usefaces = usefacemask&0xF; usefacemask >>= 4; if(!usefaces) { surfaceinfo &surf = surfaces[i]; int numverts = surf.totalverts(); if(numverts) { memcpy(&litverts[numlitverts], c.ext->verts() + surf.verts, numverts*sizeof(vertinfo)); surf.verts = numlitverts; numlitverts += numverts; } continue; } VSlot &vslot = lookupvslot(c.texture[i], false), &layer = lookupvslot(vslot.layer, false); Shader *shader = vslot.slot->shader; int shadertype = shader->type | layer.slot->shader->type; vertinfo *curlitverts = &litverts[numlitverts]; int numverts = 0; ivec v[4]; genfaceverts(c, i, v); int convex = flataxisface(c, i) ? 0 : faceconvexity(v), order = usefaces&4 || convex < 0 ? 1 : 0; ivec vo = ivec(co).mask(0xFFF).shl(3); curlitverts[numverts++].set(v[order].mul(size).add(vo)); if(usefaces&1) curlitverts[numverts++].set(v[order+1].mul(size).add(vo)); curlitverts[numverts++].set(v[order+2].mul(size).add(vo)); if(usefaces&2) curlitverts[numverts++].set(v[(order+3)&3].mul(size).add(vo)); vec pos[4], n[4], po = ivec(co).mask(~0xFFF).tovec(); loopj(numverts) pos[j] = curlitverts[j].getxyz().tovec().mul(1.0f/8).add(po); plane planes[2]; int numplanes = 0; planes[numplanes++].toplane(pos[0], pos[1], pos[2]); if(numverts < 4 || !convex) loopk(numverts) n[k] = planes[0]; else { planes[numplanes++].toplane(pos[0], pos[2], pos[3]); vec avg = vec(planes[0]).add(planes[1]).normalize(); n[0] = avg; n[1] = planes[0]; n[2] = avg; for(int k = 3; k < numverts; k++) n[k] = planes[1]; } surfaceinfo &surf = surfaces[i]; w->slot = vslot.slot; w->vslot = &vslot; w->type = shadertype&SHADER_NORMALSLMS ? LM_BUMPMAP0|LM_ALPHA : LM_DIFFUSE|LM_ALPHA; w->bpp = 4; w->orient = i; w->rotate = vslot.rotation; int surftype = setupsurface(w, planes, numplanes, pos, n, numverts, curlitverts, true); switch(surftype) { case SURFACE_AMBIENT_TOP: surf = brightsurface; continue; case SURFACE_AMBIENT_BOTTOM: surf = brightbottomsurface; continue; case SURFACE_LIGHTMAP_BLEND: { if(surf.numverts == (LAYER_BLEND|numverts) && surf.lmid[0] == surf.lmid[1] && (surf.numverts&MAXFACEVERTS) == numverts && !memcmp(curlitverts, c.ext->verts() + surf.verts, numverts*sizeof(vertinfo)) && lightmaps.inrange(surf.lmid[0]-LMID_RESERVED) && lightmaps[surf.lmid[0]-LMID_RESERVED].type==w->type) { vertinfo *oldverts = c.ext->verts() + surf.verts; layoutinfo layout; layout.w = w->w; layout.h = w->h; layout.x = (oldverts[0].x - curlitverts[0].x)/((USHRT_MAX+1)/LM_PACKW); layout.y = (oldverts[0].y - curlitverts[0].y)/((USHRT_MAX+1)/LM_PACKH); if(LM_PACKW - layout.x >= w->w && LM_PACKH - layout.y >= w->h) { layout.lmid = surf.lmid[0]; copylightmap(*w->lastlightmap, layout); updatelightmap(layout); surf.verts = numlitverts; numlitverts += numverts; continue; } } surf.verts = numlitverts; surf.numverts = LAYER_BLEND|numverts; numlitverts += numverts; layoutinfo layout; if(packlightmap(*w->lastlightmap, layout)) updatelightmap(layout); surf.lmid[0] = surf.lmid[1] = layout.lmid; ushort offsetx = layout.x*((USHRT_MAX+1)/LM_PACKW), offsety = layout.y*((USHRT_MAX+1)/LM_PACKH); loopk(numverts) { vertinfo &v = curlitverts[k]; v.u += offsetx; v.v += offsety; } continue; } } } setsurfaces(c, surfaces, litverts, numlitverts); return true; } static bool previewblends(lightmapworker *w, cube *c, const ivec &co, int size, const ivec &bo, const ivec &bs) { bool changed = false; loopoctabox(co, size, bo, bs) { ivec o(i, co.x, co.y, co.z, size); cubeext *ext = c[i].ext; if(ext && ext->va && ext->va->hasmerges) { changed = true; destroyva(ext->va); ext->va = NULL; invalidatemerges(c[i], co, size, true); } if(c[i].children ? previewblends(w, c[i].children, o, size/2, bo, bs) : previewblends(w, c[i], o, size)) { changed = true; ext = c[i].ext; if(ext && ext->va) { destroyva(ext->va); ext->va = NULL; } } } return changed; } void previewblends(const ivec &bo, const ivec &bs) { loadlayermasks(); if(lightmapworkers.empty()) lightmapworkers.add(new lightmapworker); lightmapworkers[0]->reset(); if(previewblends(lightmapworkers[0], worldroot, ivec(0, 0, 0), worldsize/2, bo, bs)) commitchanges(true); } void cleanuplightmaps() { loopv(lightmaps) { LightMap &lm = lightmaps[i]; lm.tex = lm.offsetx = lm.offsety = -1; } loopv(lightmaptexs) glDeleteTextures(1, &lightmaptexs[i].id); lightmaptexs.shrink(0); if(progresstex) { glDeleteTextures(1, &progresstex); progresstex = 0; } } void resetlightmaps(bool fullclean) { cleanuplightmaps(); lightmaps.shrink(0); compressed.clear(); clearlightcache(); if(fullclean) while(lightmapworkers.length()) delete lightmapworkers.pop(); } lightmapworker::lightmapworker() { buf = new uchar[LIGHTMAPBUFSIZE]; bufstart = bufused = 0; firstlightmap = lastlightmap = curlightmaps = NULL; ambient = new uchar[4*(LM_MAXW + 4)*(LM_MAXH + 4)]; blur = new uchar[4*(LM_MAXW + 4)*(LM_MAXH + 4)]; colordata = new vec[4*(LM_MAXW+1 + 4)*(LM_MAXH+1 + 4)]; raydata = new vec[(LM_MAXW + 4)*(LM_MAXH + 4)]; shadowraycache = newshadowraycache(); blendmapcache = newblendmapcache(); needspace = doneworking = false; spacecond = NULL; thread = NULL; } lightmapworker::~lightmapworker() { cleanupthread(); delete[] buf; delete[] ambient; delete[] blur; delete[] colordata; delete[] raydata; freeshadowraycache(shadowraycache); freeblendmapcache(blendmapcache); } void lightmapworker::cleanupthread() { if(spacecond) { SDL_DestroyCond(spacecond); spacecond = NULL; } thread = NULL; } void lightmapworker::reset() { bufstart = bufused = 0; firstlightmap = lastlightmap = curlightmaps = NULL; needspace = doneworking = false; resetshadowraycache(shadowraycache); } bool lightmapworker::setupthread() { if(!spacecond) spacecond = SDL_CreateCond(); if(!spacecond) return false; thread = SDL_CreateThread(work, this); return thread!=NULL; } static Uint32 calclighttimer(Uint32 interval, void *param) { check_calclight_progress = true; return interval; } bool setlightmapquality(int quality) { switch(quality) { case 1: lmshadows = 2; lmaa = 3; lerptjoints = 1; break; case 0: lmshadows = lmshadows_; lmaa = lmaa_; lerptjoints = lerptjoints_; break; case -1: lmshadows = 1; lmaa = 0; lerptjoints = 0; break; default: return false; } return true; } VARP(lightthreads, 0, 0, 16); #define ALLOCLOCK(name, init) { if(lightmapping > 1) name = init(); if(!name) lightmapping = 1; } #define FREELOCK(name, destroy) { if(name) { destroy(name); name = NULL; } } static void cleanuplocks() { FREELOCK(lightlock, SDL_DestroyMutex); FREELOCK(tasklock, SDL_DestroyMutex); FREELOCK(fullcond, SDL_DestroyCond); FREELOCK(emptycond, SDL_DestroyCond); } static void setupthreads(int numthreads) { loopi(2) lightmaptasks[i].setsize(0); lightmapexts.setsize(0); packidx = allocidx = 0; lightmapping = numthreads; if(lightmapping > 1) { ALLOCLOCK(lightlock, SDL_CreateMutex); ALLOCLOCK(tasklock, SDL_CreateMutex); ALLOCLOCK(fullcond, SDL_CreateCond); ALLOCLOCK(emptycond, SDL_CreateCond); } while(lightmapworkers.length() < lightmapping) lightmapworkers.add(new lightmapworker); loopi(lightmapping) { lightmapworker *w = lightmapworkers[i]; w->reset(); if(lightmapping <= 1 || w->setupthread()) continue; w->cleanupthread(); lightmapping = i >= 1 ? max(i, 2) : 1; break; } if(lightmapping <= 1) cleanuplocks(); } static void cleanupthreads() { processtasks(true); if(lightmapping > 1) { SDL_LockMutex(tasklock); loopv(lightmapworkers) lightmapworkers[i]->doneworking = true; SDL_CondBroadcast(fullcond); loopv(lightmapworkers) { lightmapworker *w = lightmapworkers[i]; if(w->needspace && w->spacecond) SDL_CondSignal(w->spacecond); } SDL_UnlockMutex(tasklock); loopv(lightmapworkers) { lightmapworker *w = lightmapworkers[i]; if(w->thread) SDL_WaitThread(w->thread, NULL); } } loopv(lightmapexts) { lightmapext &e = lightmapexts[i]; setcubeext(*e.c, e.ext); } loopv(lightmapworkers) lightmapworkers[i]->cleanupthread(); cleanuplocks(); lightmapping = 0; } void calclight(int *quality) { if(!setlightmapquality(*quality)) { conoutf(CON_ERROR, "valid range for calclight quality is -1..1"); return; } renderbackground("computing lightmaps... (esc to abort)"); mpremip(true); optimizeblendmap(); loadlayermasks(); int numthreads = lightthreads > 0 ? lightthreads : numcpus; if(numthreads > 1) preloadusedmapmodels(false, true); resetlightmaps(false); clearsurfaces(worldroot); taskprogress = progress = 0; progresstexticks = 0; progresslightmap = -1; calclight_canceled = false; check_calclight_progress = false; SDL_TimerID timer = SDL_AddTimer(250, calclighttimer, NULL); Uint32 start = SDL_GetTicks(); calcnormals(lerptjoints > 0); show_calclight_progress(); setupthreads(numthreads); generatelightmaps(worldroot, 0, 0, 0, worldsize >> 1); cleanupthreads(); clearnormals(); Uint32 end = SDL_GetTicks(); if(timer) SDL_RemoveTimer(timer); uint total = 0, lumels = 0; loopv(lightmaps) { insertunlit(i); if(!editmode) lightmaps[i].finalize(); total += lightmaps[i].lightmaps; lumels += lightmaps[i].lumels; } if(!editmode) compressed.clear(); initlights(); renderbackground("lighting done..."); allchanged(); if(calclight_canceled) conoutf("calclight aborted"); else conoutf("generated %d lightmaps using %d%% of %d textures (%.1f seconds)", total, lightmaps.length() ? lumels * 100 / (lightmaps.length() * LM_PACKW * LM_PACKH) : 0, lightmaps.length(), (end - start) / 1000.0f); } COMMAND(calclight, "i"); VAR(patchnormals, 0, 0, 1); void patchlight(int *quality) { if(noedit(true)) return; if(!setlightmapquality(*quality)) { conoutf(CON_ERROR, "valid range for patchlight quality is -1..1"); return; } renderbackground("patching lightmaps... (esc to abort)"); loadlayermasks(); int numthreads = lightthreads > 0 ? lightthreads : numcpus; if(numthreads > 1) preloadusedmapmodels(false, true); cleanuplightmaps(); taskprogress = progress = 0; progresstexticks = 0; progresslightmap = -1; int total = 0, lumels = 0; loopv(lightmaps) { if((lightmaps[i].type&LM_TYPE) != LM_BUMPMAP1) progresslightmap = i; total -= lightmaps[i].lightmaps; lumels -= lightmaps[i].lumels; } calclight_canceled = false; check_calclight_progress = false; SDL_TimerID timer = SDL_AddTimer(250, calclighttimer, NULL); if(patchnormals) renderprogress(0, "computing normals..."); Uint32 start = SDL_GetTicks(); if(patchnormals) calcnormals(lerptjoints > 0); show_calclight_progress(); setupthreads(numthreads); generatelightmaps(worldroot, 0, 0, 0, worldsize >> 1); cleanupthreads(); if(patchnormals) clearnormals(); Uint32 end = SDL_GetTicks(); if(timer) SDL_RemoveTimer(timer); loopv(lightmaps) { total += lightmaps[i].lightmaps; lumels += lightmaps[i].lumels; } initlights(); renderbackground("lighting done..."); allchanged(); if(calclight_canceled) conoutf("patchlight aborted"); else conoutf("patched %d lightmaps using %d%% of %d textures (%.1f seconds)", total, lightmaps.length() ? lumels * 100 / (lightmaps.length() * LM_PACKW * LM_PACKH) : 0, lightmaps.length(), (end - start) / 1000.0f); } COMMAND(patchlight, "i"); void clearlightmaps() { if(noedit(true)) return; renderprogress(0, "clearing lightmaps..."); resetlightmaps(false); clearsurfaces(worldroot); initlights(); allchanged(); } COMMAND(clearlightmaps, ""); void setfullbrightlevel(int fullbrightlevel) { if(lightmaptexs.length() > LMID_BRIGHT) { uchar bright[3] = { uchar(fullbrightlevel), uchar(fullbrightlevel), uchar(fullbrightlevel) }; createtexture(lightmaptexs[LMID_BRIGHT].id, 1, 1, bright, 0, 1); } initlights(); } VARF(fullbright, 0, 0, 1, if(lightmaptexs.length()) { initlights(); lightents(); }); VARF(fullbrightlevel, 0, 128, 255, setfullbrightlevel(fullbrightlevel)); vector lightmaptexs; static void rotatenormals(LightMap &lmlv, int x, int y, int w, int h, int rotate) { bool flipx = rotate>=2 && rotate<=4, flipy = (rotate>=1 && rotate<=2) || rotate==5, swapxy = (rotate&5)==1; uchar *lv = lmlv.data + 3*(y*LM_PACKW + x); int stride = 3*(LM_PACKW-w); loopi(h) { loopj(w) { if(flipx) lv[0] = 255 - lv[0]; if(flipy) lv[1] = 255 - lv[1]; if(swapxy) swap(lv[0], lv[1]); lv += 3; } lv += stride; } } static void rotatenormals(cube *c) { loopi(8) { cube &ch = c[i]; if(ch.children) { rotatenormals(ch.children); continue; } else if(!ch.ext) continue; loopj(6) if(lightmaps.inrange(ch.ext->surfaces[j].lmid[0]+1-LMID_RESERVED)) { VSlot &vslot = lookupvslot(ch.texture[j], false); if(!vslot.rotation) continue; surfaceinfo &surface = ch.ext->surfaces[j]; int numverts = surface.numverts&MAXFACEVERTS; if(!numverts) continue; LightMap &lmlv = lightmaps[surface.lmid[0]+1-LMID_RESERVED]; if((lmlv.type&LM_TYPE)!=LM_BUMPMAP1) continue; ushort x1 = USHRT_MAX, y1 = USHRT_MAX, x2 = 0, y2 = 0; vertinfo *verts = ch.ext->verts() + surface.verts; loopk(numverts) { vertinfo &v = verts[k]; x1 = min(x1, v.u); y1 = min(y1, v.u); x2 = max(x2, v.u); y2 = max(y2, v.v); } if(x1 > x2 || y1 > y2) continue; x1 /= (USHRT_MAX+1)/LM_PACKW; y1 /= (USHRT_MAX+1)/LM_PACKH; x2 /= (USHRT_MAX+1)/LM_PACKW; y2 /= (USHRT_MAX+1)/LM_PACKH; rotatenormals(lmlv, x1, y1, x2-x1, y1-y1, vslot.rotation < 4 ? 4-vslot.rotation : vslot.rotation); } } } void fixlightmapnormals() { rotatenormals(worldroot); } void fixrotatedlightmaps(cube &c, const ivec &co, int size) { if(c.children) { loopi(8) fixrotatedlightmaps(c.children[i], ivec(i, co.x, co.y, co.z, size>>1), size>>1); return; } if(!c.ext) return; loopi(6) { if(c.merged&(1<surfaces[i]; int numverts = surf.numverts&MAXFACEVERTS; if(numverts!=4 || (surf.lmid[0] < LMID_RESERVED && surf.lmid[1] < LMID_RESERVED)) continue; vertinfo *verts = c.ext->verts() + surf.verts; int vis = visibletris(c, i, co.x, co.y, co.z, size); if(!vis || vis==3) continue; if((verts[0].u != verts[1].u || verts[0].v != verts[1].v) && (verts[0].u != verts[3].u || verts[0].v != verts[3].v) && (verts[2].u != verts[1].u || verts[2].v != verts[1].v) && (verts[2].u != verts[3].u || verts[2].v != verts[3].v)) continue; if(vis&4) { vertinfo tmp = verts[0]; verts[0].x = verts[1].x; verts[0].y = verts[1].y; verts[0].z = verts[1].z; verts[1].x = verts[2].x; verts[1].y = verts[2].y; verts[1].z = verts[2].z; verts[2].x = verts[3].x; verts[2].y = verts[3].y; verts[2].z = verts[3].z; verts[3].x = tmp.x; verts[3].y = tmp.y; verts[3].z = tmp.z; if(surf.numverts&LAYER_DUP) loopk(4) { vertinfo &v = verts[k], &b = verts[k+4]; b.x = v.x; b.y = v.y; b.z = v.z; } } surf.numverts = (surf.numverts & ~MAXFACEVERTS) | 3; if(vis&2) { verts[1] = verts[2]; verts[2] = verts[3]; if(surf.numverts&LAYER_DUP) { verts[3] = verts[4]; verts[4] = verts[6]; verts[5] = verts[7]; } } else if(surf.numverts&LAYER_DUP) { verts[3] = verts[4]; verts[4] = verts[5]; verts[5] = verts[6]; } } } void fixrotatedlightmaps() { loopi(8) fixrotatedlightmaps(worldroot[i], ivec(i, 0, 0, 0, worldsize>>1), worldsize>>1); } static void convertlightmap(LightMap &lmc, LightMap &lmlv, uchar *dst, size_t stride) { const uchar *c = lmc.data; const bvec *lv = (const bvec *)lmlv.data; loopi(LM_PACKH) { uchar *dstrow = dst; loopj(LM_PACKW) { int z = int(lv->z)*2 - 255, r = (int(c[0]) * z) / 255, g = (int(c[1]) * z) / 255, b = (int(c[2]) * z) / 255; dstrow[0] = max(r, int(ambientcolor[0])); dstrow[1] = max(g, int(ambientcolor[1])); dstrow[2] = max(b, int(ambientcolor[2])); if(lmc.bpp==4) dstrow[3] = c[3]; c += lmc.bpp; lv++; dstrow += lmc.bpp; } dst += stride; } } static void copylightmap(LightMap &lm, uchar *dst, size_t stride) { const uchar *c = lm.data; loopi(LM_PACKH) { memcpy(dst, c, lm.bpp*LM_PACKW); c += lm.bpp*LM_PACKW; dst += stride; } } VARF(convertlms, 0, 1, 1, { cleanuplightmaps(); initlights(); allchanged(); }); void genreservedlightmaptexs() { while(lightmaptexs.length() < LMID_RESERVED) { LightMapTexture &tex = lightmaptexs.add(); tex.type = renderpath != R_FIXEDFUNCTION && lightmaptexs.length()&1 ? LM_DIFFUSE : LM_BUMPMAP1; glGenTextures(1, &tex.id); } uchar unlit[3] = { ambientcolor[0], ambientcolor[1], ambientcolor[2] }; createtexture(lightmaptexs[LMID_AMBIENT].id, 1, 1, unlit, 0, 1); bvec front(128, 128, 255); createtexture(lightmaptexs[LMID_AMBIENT1].id, 1, 1, &front, 0, 1); uchar bright[3] = { uchar(fullbrightlevel), uchar(fullbrightlevel), uchar(fullbrightlevel) }; createtexture(lightmaptexs[LMID_BRIGHT].id, 1, 1, bright, 0, 1); createtexture(lightmaptexs[LMID_BRIGHT1].id, 1, 1, &front, 0, 1); uchar dark[3] = { 0, 0, 0 }; createtexture(lightmaptexs[LMID_DARK].id, 1, 1, dark, 0, 1); createtexture(lightmaptexs[LMID_DARK1].id, 1, 1, &front, 0, 1); } static void findunlit(int i) { LightMap &lm = lightmaps[i]; if(lm.unlitx>=0) return; else if((lm.type&LM_TYPE)==LM_BUMPMAP0) { if(i+1>=lightmaps.length() || (lightmaps[i+1].type&LM_TYPE)!=LM_BUMPMAP1) return; } else if((lm.type&LM_TYPE)!=LM_DIFFUSE) return; uchar *data = lm.data; loop(y, 2) loop(x, LM_PACKW) { if(!data[0] && !data[1] && !data[2]) { memcpy(data, ambientcolor.v, 3); if((lm.type&LM_TYPE)==LM_BUMPMAP0) ((bvec *)lightmaps[i+1].data)[y*LM_PACKW + x] = bvec(128, 128, 255); lm.unlitx = x; lm.unlity = y; return; } if(data[0]==ambientcolor[0] && data[1]==ambientcolor[1] && data[2]==ambientcolor[2]) { if((lm.type&LM_TYPE)!=LM_BUMPMAP0 || ((bvec *)lightmaps[i+1].data)[y*LM_PACKW + x] == bvec(128, 128, 255)) { lm.unlitx = x; lm.unlity = y; return; } } data += lm.bpp; } } VARF(roundlightmaptex, 0, 4, 16, { cleanuplightmaps(); initlights(); allchanged(); }); VARF(batchlightmaps, 0, 4, 256, { cleanuplightmaps(); initlights(); allchanged(); }); void genlightmaptexs(int flagmask, int flagval) { if(lightmaptexs.length() < LMID_RESERVED) genreservedlightmaptexs(); int remaining[3] = { 0, 0, 0 }, total = 0; loopv(lightmaps) { LightMap &lm = lightmaps[i]; if(lm.tex >= 0 || (lm.type&flagmask)!=flagval) continue; int type = lm.type&LM_TYPE; remaining[type]++; total++; if(lm.unlitx < 0) findunlit(i); } if(renderpath==R_FIXEDFUNCTION) { remaining[LM_DIFFUSE] += remaining[LM_BUMPMAP0]; remaining[LM_BUMPMAP0] = remaining[LM_BUMPMAP1] = 0; } int sizelimit = (maxtexsize ? min(maxtexsize, hwtexsize) : hwtexsize)/max(LM_PACKW, LM_PACKH); sizelimit = min(batchlightmaps, sizelimit*sizelimit); while(total) { int type = LM_DIFFUSE; LightMap *firstlm = NULL; loopv(lightmaps) { LightMap &lm = lightmaps[i]; if(lm.tex >= 0 || (lm.type&flagmask) != flagval) continue; if(renderpath != R_FIXEDFUNCTION) type = lm.type&LM_TYPE; else if((lm.type&LM_TYPE) == LM_BUMPMAP1) continue; firstlm = &lm; break; } if(!firstlm) break; int used = 0, uselimit = min(remaining[type], sizelimit); do used++; while((1<type; tex.w = LM_PACKW<<((used+1)/2); tex.h = LM_PACKH<<(used/2); int bpp = firstlm->bpp; uchar *data = used || (renderpath == R_FIXEDFUNCTION && (firstlm->type&LM_TYPE) == LM_BUMPMAP0 && convertlms) ? new uchar[bpp*tex.w*tex.h] : NULL; int offsetx = 0, offsety = 0; loopv(lightmaps) { LightMap &lm = lightmaps[i]; if(lm.tex >= 0 || (lm.type&flagmask) != flagval || (renderpath==R_FIXEDFUNCTION ? (lm.type&LM_TYPE) == LM_BUMPMAP1 : (lm.type&LM_TYPE) != type)) continue; lm.tex = lightmaptexs.length()-1; lm.offsetx = offsetx; lm.offsety = offsety; if(tex.unlitx < 0 && lm.unlitx >= 0) { tex.unlitx = offsetx + lm.unlitx; tex.unlity = offsety + lm.unlity; } if(data) { if(renderpath == R_FIXEDFUNCTION && (lm.type&LM_TYPE) == LM_BUMPMAP0 && convertlms) convertlightmap(lm, lightmaps[i+1], &data[bpp*(offsety*tex.w + offsetx)], bpp*tex.w); else copylightmap(lm, &data[bpp*(offsety*tex.w + offsetx)], bpp*tex.w); } offsetx += LM_PACKW; if(offsetx >= tex.w) { offsetx = 0; offsety += LM_PACKH; } if(offsety >= tex.h) break; } glGenTextures(1, &tex.id); createtexture(tex.id, tex.w, tex.h, data ? data : firstlm->data, 3, 1, bpp==4 ? GL_RGBA : GL_RGB); if(data) delete[] data; } } bool brightengeom = false, shouldlightents = false; void clearlights() { clearlightcache(); const vector &ents = entities::getents(); loopv(ents) { extentity &e = *ents[i]; e.light.color = vec(1, 1, 1); e.light.dir = vec(0, 0, 1); } shouldlightents = false; if(nolights) return; genlightmaptexs(LM_ALPHA, 0); genlightmaptexs(LM_ALPHA, LM_ALPHA); brightengeom = true; } void lightent(extentity &e, float height) { if(e.type==ET_LIGHT) return; float ambient = 0.0f; if(e.type==ET_MAPMODEL) { model *m = loadmodel(NULL, e.attr2); if(m) height = m->above()*0.75f; } else if(e.type>=ET_GAMESPECIFIC) ambient = 0.4f; vec target(e.o.x, e.o.y, e.o.z + height); lightreaching(target, e.light.color, e.light.dir, false, &e, ambient); } void lightents(bool force) { if(!force && !shouldlightents) return; const vector &ents = entities::getents(); loopv(ents) lightent(*ents[i]); shouldlightents = false; } void initlights() { if(nolights || (fullbright && editmode) || lightmaps.empty()) { clearlights(); return; } clearlightcache(); genlightmaptexs(LM_ALPHA, 0); genlightmaptexs(LM_ALPHA, LM_ALPHA); brightengeom = false; shouldlightents = true; } static inline void fastskylight(const vec &o, float tolerance, uchar *skylight, int flags = RAY_ALPHAPOLY, extentity *t = NULL, bool fast = false) { flags |= RAY_SHADOW; if(skytexturelight) flags |= RAY_SKIPSKY; if(fast) { static const vec ray(0, 0, 1); if(shadowray(vec(ray).mul(tolerance).add(o), ray, 1e16f, flags, t)>1e15f) memcpy(skylight, skylightcolor.v, 3); else memcpy(skylight, ambientcolor.v, 3); } else { static const vec rays[5] = { vec(cosf(66*RAD)*cosf(65*RAD), sinf(66*RAD)*cosf(65*RAD), sinf(65*RAD)), vec(cosf(156*RAD)*cosf(65*RAD), sinf(156*RAD)*cosf(65*RAD), sinf(65*RAD)), vec(cosf(246*RAD)*cosf(65*RAD), sinf(246*RAD)*cosf(65*RAD), sinf(65*RAD)), vec(cosf(336*RAD)*cosf(65*RAD), sinf(336*RAD)*cosf(65*RAD), sinf(65*RAD)), vec(0, 0, 1), }; int hit = 0; loopi(5) if(shadowray(vec(rays[i]).mul(tolerance).add(o), rays[i], 1e16f, flags, t)>1e15f) hit++; loopk(3) skylight[k] = uchar(ambientcolor[k] + (max(skylightcolor[k], ambientcolor[k]) - ambientcolor[k])*hit/5.0f); } } void lightreaching(const vec &target, vec &color, vec &dir, bool fast, extentity *t, float ambient) { if(nolights || (fullbright && editmode) || lightmaps.empty()) { color = vec(1, 1, 1); dir = vec(0, 0, 1); return; } color = dir = vec(0, 0, 0); const vector &ents = entities::getents(); const vector &lights = checklightcache(int(target.x), int(target.y)); loopv(lights) { extentity &e = *ents[lights[i]]; if(e.type != ET_LIGHT) continue; vec ray(target); ray.sub(e.o); float mag = ray.magnitude(); if(e.attr1 && mag >= float(e.attr1)) continue; if(mag < 1e-4f) ray = vec(0, 0, -1); else { ray.div(mag); if(shadowray(e.o, ray, mag, RAY_SHADOW | RAY_POLY, t) < mag) continue; } float intensity = 1; if(e.attr1) intensity -= mag / float(e.attr1); if(e.attached && e.attached->type==ET_SPOTLIGHT) { vec spot = vec(e.attached->o).sub(e.o).normalize(); float maxatten = sincos360[clamp(int(e.attached->attr1), 1, 89)].x, spotatten = (ray.dot(spot) - maxatten) / (1 - maxatten); if(spotatten <= 0) continue; intensity *= spotatten; } //if(target==player->o) //{ // conoutf(CON_DEBUG, "%d - %f %f", i, intensity, mag); //} vec lightcol = vec(e.attr2, e.attr3, e.attr4).mul(1.0f/255); color.add(vec(lightcol).mul(intensity)); dir.add(vec(ray).mul(-intensity*lightcol.x*lightcol.y*lightcol.z)); } if(sunlight && shadowray(target, sunlightdir, 1e16f, RAY_SHADOW | RAY_POLY | (skytexturelight ? RAY_SKIPSKY : 0), t) > 1e15f) { vec lightcol = vec(sunlightcolor.x, sunlightcolor.y, sunlightcolor.z).mul(sunlightscale/255); color.add(lightcol); dir.add(vec(sunlightdir).mul(lightcol.x*lightcol.y*lightcol.z)); } if(hasskylight()) { uchar skylight[3]; if(t) calcskylight(NULL, target, vec(0, 0, 0), 0.5f, skylight, RAY_POLY, t); else fastskylight(target, 0.5f, skylight, RAY_POLY, t, fast); loopk(3) color[k] = min(1.5f, max(max(skylight[k]/255.0f, ambient), color[k])); } else loopk(3) color[k] = min(1.5f, max(max(ambientcolor[k]/255.0f, ambient), color[k])); if(dir.iszero()) dir = vec(0, 0, 1); else dir.normalize(); } entity *brightestlight(const vec &target, const vec &dir) { if(sunlight && sunlightdir.dot(dir) > 0 && shadowray(target, sunlightdir, 1e16f, RAY_SHADOW | RAY_POLY | (skytexturelight ? RAY_SKIPSKY : 0)) > 1e15f) return &sunlightent; const vector &ents = entities::getents(); const vector &lights = checklightcache(int(target.x), int(target.y)); extentity *brightest = NULL; float bintensity = 0; loopv(lights) { extentity &e = *ents[lights[i]]; if(e.type != ET_LIGHT || vec(e.o).sub(target).dot(dir)<0) continue; vec ray(target); ray.sub(e.o); float mag = ray.magnitude(); if(e.attr1 && mag >= float(e.attr1)) continue; ray.div(mag); if(shadowray(e.o, ray, mag, RAY_SHADOW | RAY_POLY) < mag) continue; float intensity = 1; if(e.attr1) intensity -= mag / float(e.attr1); if(e.attached && e.attached->type==ET_SPOTLIGHT) { vec spot = vec(e.attached->o).sub(e.o).normalize(); float maxatten = sincos360[clamp(int(e.attached->attr1), 1, 89)].x, spotatten = (ray.dot(spot) - maxatten) / (1 - maxatten); if(spotatten <= 0) continue; intensity *= spotatten; } if(!brightest || intensity > bintensity) { brightest = &e; bintensity = intensity; } } return brightest; } void dumplms() { loopv(lightmaps) { ImageData temp(LM_PACKW, LM_PACKH, lightmaps[i].bpp, lightmaps[i].data); const char *map = game::getclientmap(), *name = strrchr(map, '/'); defformatstring(buf)("lightmap_%s_%d.png", name ? name+1 : map, i); savepng(buf, temp, true); } } COMMAND(dumplms, ""); sauerbraten-0.0.20130203.dfsg/engine/movie.cpp0000644000175000017500000012723512021204010020455 0ustar vincentvincent// Feedback on playing videos: // quicktime - ok // vlc - ok // xine - ok // mplayer - ok // totem - ok // avidemux - ok - 3Apr09-RockKeyman:had to swap UV channels as it showed up blue // kino - ok #include "engine.h" #include "SDL_mixer.h" VAR(dbgmovie, 0, 0, 1); struct aviindexentry { int frame, type, size; uint offset; aviindexentry() {} aviindexentry(int frame, int type, int size, uint offset) : frame(frame), type(type), size(size), offset(offset) {} }; struct avisegmentinfo { stream::offset offset, videoindexoffset, soundindexoffset; int firstindex; uint videoindexsize, soundindexsize, indexframes, videoframes, soundframes; avisegmentinfo() {} avisegmentinfo(stream::offset offset, int firstindex) : offset(offset), videoindexoffset(0), soundindexoffset(0), firstindex(firstindex), videoindexsize(0), soundindexsize(0), indexframes(0), videoframes(0), soundframes(0) {} }; struct aviwriter { stream *f; uchar *yuv; uint videoframes; stream::offset totalsize; const uint videow, videoh, videofps; string filename; int soundfrequency, soundchannels; Uint16 soundformat; vector index; vector segments; stream::offset fileframesoffset, fileextframesoffset, filevideooffset, filesoundoffset, superindexvideooffset, superindexsoundoffset; enum { MAX_CHUNK_DEPTH = 16, MAX_SUPER_INDEX = 1024 }; stream::offset chunkoffsets[MAX_CHUNK_DEPTH]; int chunkdepth; aviindexentry &addindex(int frame, int type, int size) { avisegmentinfo &seg = segments.last(); int i = index.length(); while(--i >= seg.firstindex) { aviindexentry &e = index[i]; if(frame > e.frame || (frame == e.frame && type <= e.type)) break; } return index.insert(i + 1, aviindexentry(frame, type, size, uint(totalsize - chunkoffsets[chunkdepth]))); } double filespaceguess() { return double(totalsize); } void startchunk(const char *fcc, uint size = 0) { f->write(fcc, 4); f->putlil(size); totalsize += 4 + 4; chunkoffsets[++chunkdepth] = totalsize; totalsize += size; } void listchunk(const char *fcc, const char *lfcc) { startchunk(fcc); f->write(lfcc, 4); totalsize += 4; } void endchunk() { assert(chunkdepth >= 0); --chunkdepth; } void endlistchunk() { assert(chunkdepth >= 0); int size = int(totalsize - chunkoffsets[chunkdepth]); f->seek(-4 - size, SEEK_CUR); f->putlil(size); f->seek(0, SEEK_END); if(size & 1) { f->putchar(0x00); totalsize++; } endchunk(); } void writechunk(const char *fcc, const void *data, uint len) // simplify startchunk()/endchunk() to avoid f->seek() { f->write(fcc, 4); f->putlil(len); f->write(data, len); totalsize += 4 + 4 + len; if(len & 1) { f->putchar(0x00); totalsize++; } } void close() { if(!f) return; flushsegment(); uint soundindexes = 0, videoindexes = 0, soundframes = 0, videoframes = 0, indexframes = 0; loopv(segments) { avisegmentinfo &seg = segments[i]; if(seg.soundindexsize) soundindexes++; videoindexes++; soundframes += seg.soundframes; videoframes += seg.videoframes; indexframes += seg.indexframes; } if(dbgmovie) conoutf(CON_DEBUG, "fileframes: sound=%d, video=%d+%d(dups)\n", soundframes, videoframes, indexframes-videoframes); f->seek(fileframesoffset, SEEK_SET); f->putlil(segments[0].indexframes); f->seek(filevideooffset, SEEK_SET); f->putlil(segments[0].videoframes); if(segments[0].soundframes > 0) { f->seek(filesoundoffset, SEEK_SET); f->putlil(segments[0].soundframes); } f->seek(fileextframesoffset, SEEK_SET); f->putlil(indexframes); // total video frames f->seek(superindexvideooffset + 2 + 2, SEEK_SET); f->putlil(videoindexes); f->seek(superindexvideooffset + 2 + 2 + 4 + 4 + 4 + 4 + 4, SEEK_SET); loopv(segments) { avisegmentinfo &seg = segments[i]; f->putlil(seg.videoindexoffset&stream::offset(0xFFFFFFFFU)); f->putlil(seg.videoindexoffset>>32); f->putlil(seg.videoindexsize); f->putlil(seg.indexframes); } if(soundindexes > 0) { f->seek(superindexsoundoffset + 2 + 2, SEEK_SET); f->putlil(soundindexes); f->seek(superindexsoundoffset + 2 + 2 + 4 + 4 + 4 + 4 + 4, SEEK_SET); loopv(segments) { avisegmentinfo &seg = segments[i]; if(!seg.soundindexsize) continue; f->putlil(seg.soundindexoffset&stream::offset(0xFFFFFFFFU)); f->putlil(seg.soundindexoffset>>32); f->putlil(seg.soundindexsize); f->putlil(seg.soundframes); } } f->seek(0, SEEK_END); DELETEP(f); } aviwriter(const char *name, uint w, uint h, uint fps, bool sound) : f(NULL), yuv(NULL), videoframes(0), totalsize(0), videow(w&~1), videoh(h&~1), videofps(fps), soundfrequency(0),soundchannels(0),soundformat(0) { copystring(filename, name); path(filename); if(!strrchr(filename, '.')) concatstring(filename, ".avi"); extern bool nosound; // sound.cpp if(sound && !nosound) { Mix_QuerySpec(&soundfrequency, &soundformat, &soundchannels); const char *desc; switch(soundformat) { case AUDIO_U8: desc = "u8"; break; case AUDIO_S8: desc = "s8"; break; case AUDIO_U16LSB: desc = "u16l"; break; case AUDIO_U16MSB: desc = "u16b"; break; case AUDIO_S16LSB: desc = "s16l"; break; case AUDIO_S16MSB: desc = "s16b"; break; default: desc = "unkn"; } if(dbgmovie) conoutf(CON_DEBUG, "soundspec: %dhz %s x %d", soundfrequency, desc, soundchannels); } } ~aviwriter() { close(); if(yuv) delete [] yuv; } bool open() { f = openfile(filename, "wb"); if(!f) return false; chunkdepth = -1; listchunk("RIFF", "AVI "); listchunk("LIST", "hdrl"); startchunk("avih", 56); f->putlil(1000000 / videofps); // microsecsperframe f->putlil(0); // maxbytespersec f->putlil(0); // reserved f->putlil(0x10 | 0x20); // flags - hasindex|mustuseindex fileframesoffset = f->tell(); f->putlil(0); // totalvideoframes f->putlil(0); // initialframes f->putlil(soundfrequency > 0 ? 2 : 1); // streams f->putlil(0); // buffersize f->putlil(videow); // video width f->putlil(videoh); // video height loopi(4) f->putlil(0); // reserved endchunk(); // avih listchunk("LIST", "strl"); startchunk("strh", 56); f->write("vids", 4); // fcctype f->write("I420", 4); // fcchandler f->putlil(0); // flags f->putlil(0); // priority f->putlil(0); // initialframes f->putlil(1); // scale f->putlil(videofps); // rate f->putlil(0); // start filevideooffset = f->tell(); f->putlil(0); // length f->putlil(videow*videoh*3/2); // suggested buffersize f->putlil(0); // quality f->putlil(0); // samplesize f->putlil(0); // frame left f->putlil(0); // frame top f->putlil(videow); // frame right f->putlil(videoh); // frame bottom endchunk(); // strh startchunk("strf", 40); f->putlil(40); //headersize f->putlil(videow); // width f->putlil(videoh); // height f->putlil(3); // planes f->putlil(12); // bitcount f->write("I420", 4); // compression f->putlil(videow*videoh*3/2); // imagesize f->putlil(0); // xres f->putlil(0); // yres; f->putlil(0); // colorsused f->putlil(0); // colorsrequired endchunk(); // strf startchunk("indx", 24 + 16*MAX_SUPER_INDEX); superindexvideooffset = f->tell(); f->putlil(4); // longs per entry f->putlil(0); // index of indexes f->putlil(0); // entries in use f->write("00dc", 4); // chunk id f->putlil(0); // reserved 1 f->putlil(0); // reserved 2 f->putlil(0); // reserved 3 loopi(MAX_SUPER_INDEX) { f->putlil(0); // offset low f->putlil(0); // offset high f->putlil(0); // size f->putlil(0); // duration } endchunk(); // indx startchunk("vprp", 68); f->putlil(0); // video format token f->putlil(0); // video standard f->putlil(videofps); // vertical refresh rate f->putlil(videow); // horizontal total f->putlil(videoh); // vertical total int gcd = screen->w, rem = screen->h; while(rem > 0) { gcd %= rem; swap(gcd, rem); } f->putlil(screen->h/gcd); // aspect denominator f->putlil(screen->w/gcd); // aspect numerator f->putlil(videow); // frame width f->putlil(videoh); // frame height f->putlil(1); // fields per frame f->putlil(videoh); // compressed bitmap height f->putlil(videow); // compressed bitmap width f->putlil(videoh); // valid bitmap height f->putlil(videow); // valid bitmap width f->putlil(0); // valid bitmap x offset f->putlil(0); // valid bitmap y offset f->putlil(0); // video x offset f->putlil(0); // video y start endchunk(); // vprp endlistchunk(); // LIST strl if(soundfrequency > 0) { const int bps = (soundformat==AUDIO_U8 || soundformat == AUDIO_S8) ? 1 : 2; listchunk("LIST", "strl"); startchunk("strh", 56); f->write("auds", 4); // fcctype f->putlil(1); // fcchandler - normally 4cc, but audio is a special case f->putlil(0); // flags f->putlil(0); // priority f->putlil(0); // initialframes f->putlil(1); // scale f->putlil(soundfrequency); // rate f->putlil(0); // start filesoundoffset = f->tell(); f->putlil(0); // length f->putlil(soundfrequency*bps*soundchannels/2); // suggested buffer size (this is a half second) f->putlil(0); // quality f->putlil(bps*soundchannels); // samplesize f->putlil(0); // frame left f->putlil(0); // frame top f->putlil(0); // frame right f->putlil(0); // frame bottom endchunk(); // strh startchunk("strf", 18); f->putlil(1); // format (uncompressed PCM) f->putlil(soundchannels); // channels f->putlil(soundfrequency); // sampleframes per second f->putlil(soundfrequency*bps*soundchannels); // average bytes per second f->putlil(bps*soundchannels); // block align <-- guess f->putlil(bps*8); // bits per sample f->putlil(0); // size endchunk(); //strf startchunk("indx", 24 + 16*MAX_SUPER_INDEX); superindexsoundoffset = f->tell(); f->putlil(4); // longs per entry f->putlil(0); // index of indexes f->putlil(0); // entries in use f->write("01wb", 4); // chunk id f->putlil(0); // reserved 1 f->putlil(0); // reserved 2 f->putlil(0); // reserved 3 loopi(MAX_SUPER_INDEX) { f->putlil(0); // offset low f->putlil(0); // offset high f->putlil(0); // size f->putlil(0); // duration } endchunk(); // indx endlistchunk(); // LIST strl } listchunk("LIST", "odml"); startchunk("dmlh", 4); fileextframesoffset = f->tell(); f->putlil(0); endchunk(); // dmlh endlistchunk(); // LIST odml listchunk("LIST", "INFO"); const char *software = "Cube 2: Sauerbraten"; writechunk("ISFT", software, strlen(software)+1); endlistchunk(); // LIST INFO endlistchunk(); // LIST hdrl nextsegment(); return true; } static inline void boxsample(const uchar *src, const uint stride, const uint area, const uint w, uint h, const uint xlow, const uint xhigh, const uint ylow, const uint yhigh, uint &bdst, uint &gdst, uint &rdst) { const uchar *end = &src[w<<2]; uint bt = 0, gt = 0, rt = 0; for(const uchar *cur = &src[4]; cur < end; cur += 4) { bt += cur[0]; gt += cur[1]; rt += cur[2]; } bt = ylow*(bt + ((src[0]*xlow + end[0]*xhigh)>>12)); gt = ylow*(gt + ((src[1]*xlow + end[1]*xhigh)>>12)); rt = ylow*(rt + ((src[2]*xlow + end[2]*xhigh)>>12)); if(h) { for(src += stride, end += stride; --h; src += stride, end += stride) { uint b = 0, g = 0, r = 0; for(const uchar *cur = &src[4]; cur < end; cur += 4) { b += cur[0]; g += cur[1]; r += cur[2]; } bt += (b<<12) + src[0]*xlow + end[0]*xhigh; gt += (g<<12) + src[1]*xlow + end[1]*xhigh; rt += (r<<12) + src[2]*xlow + end[2]*xhigh; } uint b = 0, g = 0, r = 0; for(const uchar *cur = &src[4]; cur < end; cur += 4) { b += cur[0]; g += cur[1]; r += cur[2]; } bt += yhigh*(b + ((src[0]*xlow + end[0]*xhigh)>>12)); gt += yhigh*(g + ((src[1]*xlow + end[1]*xhigh)>>12)); rt += yhigh*(r + ((src[2]*xlow + end[2]*xhigh)>>12)); } bdst = (bt*area)>>24; gdst = (gt*area)>>24; rdst = (rt*area)>>24; } void scaleyuv(const uchar *pixels, uint srcw, uint srch) { const int flip = -1; const uint planesize = videow * videoh; if(!yuv) yuv = new uchar[(planesize*3)/2]; uchar *yplane = yuv, *uplane = yuv + planesize, *vplane = yuv + planesize + planesize/4; const int ystride = flip*int(videow), uvstride = flip*int(videow)/2; if(flip < 0) { yplane -= int(videoh-1)*ystride; uplane -= int(videoh/2-1)*uvstride; vplane -= int(videoh/2-1)*uvstride; } const uint stride = srcw<<2; srcw &= ~1; srch &= ~1; const uint wfrac = (srcw<<12)/videow, hfrac = (srch<<12)/videoh, area = ((ullong)planesize<<12)/(srcw*srch + 1), dw = videow*wfrac, dh = videoh*hfrac; for(uint y = 0; y < dh;) { uint yn = y + hfrac - 1, yi = y>>12, h = (yn>>12) - yi, ylow = ((yn|(-int(h)>>24))&0xFFFU) + 1 - (y&0xFFFU), yhigh = (yn&0xFFFU) + 1; y += hfrac; uint y2n = y + hfrac - 1, y2i = y>>12, h2 = (y2n>>12) - y2i, y2low = ((y2n|(-int(h2)>>24))&0xFFFU) + 1 - (y&0xFFFU), y2high = (y2n&0xFFFU) + 1; y += hfrac; const uchar *src = &pixels[yi*stride], *src2 = &pixels[y2i*stride]; uchar *ydst = yplane, *ydst2 = yplane + ystride, *udst = uplane, *vdst = vplane; for(uint x = 0; x < dw;) { uint xn = x + wfrac - 1, xi = x>>12, w = (xn>>12) - xi, xlow = ((w+0xFFFU)&0x1000U) - (x&0xFFFU), xhigh = (xn&0xFFFU) + 1; x += wfrac; uint x2n = x + wfrac - 1, x2i = x>>12, w2 = (x2n>>12) - x2i, x2low = ((w2+0xFFFU)&0x1000U) - (x&0xFFFU), x2high = (x2n&0xFFFU) + 1; x += wfrac; uint b1, g1, r1, b2, g2, r2, b3, g3, r3, b4, g4, r4; boxsample(&src[xi<<2], stride, area, w, h, xlow, xhigh, ylow, yhigh, b1, g1, r1); boxsample(&src[x2i<<2], stride, area, w2, h, x2low, x2high, ylow, yhigh, b2, g2, r2); boxsample(&src2[xi<<2], stride, area, w, h2, xlow, xhigh, y2low, y2high, b3, g3, r3); boxsample(&src2[x2i<<2], stride, area, w2, h2, x2low, x2high, y2low, y2high, b4, g4, r4); // Y = 16 + 65.481*R + 128.553*G + 24.966*B // Cb = 128 - 37.797*R - 74.203*G + 112.0*B // Cr = 128 + 112.0*R - 93.786*G - 18.214*B *ydst++ = ((16<<12) + 1052*r1 + 2065*g1 + 401*b1)>>12; *ydst++ = ((16<<12) + 1052*r2 + 2065*g2 + 401*b2)>>12; *ydst2++ = ((16<<12) + 1052*r3 + 2065*g3 + 401*b3)>>12;; *ydst2++ = ((16<<12) + 1052*r4 + 2065*g4 + 401*b4)>>12;; const uint b = b1 + b2 + b3 + b4, g = g1 + g2 + g3 + g4, r = r1 + r2 + r3 + r4; // note: weights here are scaled by 1<<10, as opposed to 1<<12, since r/g/b are already *4 *udst++ = ((128<<12) - 152*r - 298*g + 450*b)>>12; *vdst++ = ((128<<12) + 450*r - 377*g - 73*b)>>12; } yplane += 2*ystride; uplane += uvstride; vplane += uvstride; } } void encodeyuv(const uchar *pixels) { const int flip = -1; const uint planesize = videow * videoh; if(!yuv) yuv = new uchar[(planesize*3)/2]; uchar *yplane = yuv, *uplane = yuv + planesize, *vplane = yuv + planesize + planesize/4; const int ystride = flip*int(videow), uvstride = flip*int(videow)/2; if(flip < 0) { yplane -= int(videoh-1)*ystride; uplane -= int(videoh/2-1)*uvstride; vplane -= int(videoh/2-1)*uvstride; } const uint stride = videow<<2; const uchar *src = pixels, *yend = src + videoh*stride; while(src < yend) { const uchar *src2 = src + stride, *xend = src2; uchar *ydst = yplane, *ydst2 = yplane + ystride, *udst = uplane, *vdst = vplane; while(src < xend) { const uint b1 = src[0], g1 = src[1], r1 = src[2], b2 = src[4], g2 = src[5], r2 = src[6], b3 = src2[0], g3 = src2[1], r3 = src2[2], b4 = src2[4], g4 = src2[5], r4 = src2[6]; // Y = 16 + 65.481*R + 128.553*G + 24.966*B // Cb = 128 - 37.797*R - 74.203*G + 112.0*B // Cr = 128 + 112.0*R - 93.786*G - 18.214*B *ydst++ = ((16<<12) + 1052*r1 + 2065*g1 + 401*b1)>>12; *ydst++ = ((16<<12) + 1052*r2 + 2065*g2 + 401*b2)>>12; *ydst2++ = ((16<<12) + 1052*r3 + 2065*g3 + 401*b3)>>12;; *ydst2++ = ((16<<12) + 1052*r4 + 2065*g4 + 401*b4)>>12;; const uint b = b1 + b2 + b3 + b4, g = g1 + g2 + g3 + g4, r = r1 + r2 + r3 + r4; // note: weights here are scaled by 1<<10, as opposed to 1<<12, since r/g/b are already *4 *udst++ = ((128<<12) - 152*r - 298*g + 450*b)>>12; *vdst++ = ((128<<12) + 450*r - 377*g - 73*b)>>12; src += 8; src2 += 8; } src = src2; yplane += 2*ystride; uplane += uvstride; vplane += uvstride; } } void compressyuv(const uchar *pixels) { const int flip = -1; const uint planesize = videow * videoh; if(!yuv) yuv = new uchar[(planesize*3)/2]; uchar *yplane = yuv, *uplane = yuv + planesize, *vplane = yuv + planesize + planesize/4; const int ystride = flip*int(videow), uvstride = flip*int(videow)/2; if(flip < 0) { yplane -= int(videoh-1)*ystride; uplane -= int(videoh/2-1)*uvstride; vplane -= int(videoh/2-1)*uvstride; } const uint stride = videow<<2; const uchar *src = pixels, *yend = src + videoh*stride; while(src < yend) { const uchar *src2 = src + stride, *xend = src2; uchar *ydst = yplane, *ydst2 = yplane + ystride, *udst = uplane, *vdst = vplane; while(src < xend) { *ydst++ = src[0]; *ydst++ = src[4]; *ydst2++ = src2[0]; *ydst2++ = src2[4]; *udst++ = (uint(src[1]) + uint(src[5]) + uint(src2[1]) + uint(src2[5])) >> 2; *vdst++ = (uint(src[2]) + uint(src[6]) + uint(src2[2]) + uint(src2[6])) >> 2; src += 8; src2 += 8; } src = src2; yplane += 2*ystride; uplane += uvstride; vplane += uvstride; } } bool writesound(uchar *data, uint framesize, uint frame) { // do conversion in-place to little endian format // note that xoring by half the range yields the same bit pattern as subtracting the range regardless of signedness // ... so can toggle signedness just by xoring the high byte with 0x80 switch(soundformat) { case AUDIO_U8: for(uchar *dst = data, *end = &data[framesize]; dst < end; dst++) *dst ^= 0x80; break; case AUDIO_S8: break; case AUDIO_U16LSB: for(uchar *dst = &data[1], *end = &data[framesize]; dst < end; dst += 2) *dst ^= 0x80; break; case AUDIO_U16MSB: for(ushort *dst = (ushort *)data, *end = (ushort *)&data[framesize]; dst < end; dst++) #if SDL_BYTEORDER == SDL_BIG_ENDIAN *dst = endianswap(*dst) ^ 0x0080; #else *dst = endianswap(*dst) ^ 0x8000; #endif break; case AUDIO_S16LSB: break; case AUDIO_S16MSB: endianswap((short *)data, framesize/2); break; } if(totalsize - segments.last().offset + framesize > 1000*1000*1000 && !nextsegment()) return false; addindex(frame, 1, framesize); writechunk("01wb", data, framesize); return true; } enum { VID_RGB = 0, VID_YUV, VID_YUV420 }; void flushsegment() { endlistchunk(); // LIST movi avisegmentinfo &seg = segments.last(); uint indexframes = 0, videoframes = 0, soundframes = 0; for(int i = seg.firstindex; i < index.length(); i++) { aviindexentry &e = index[i]; if(e.type) soundframes++; else { if(i == seg.firstindex || e.offset != index[i-1].offset) videoframes++; indexframes++; } } if(segments.length() == 1) { startchunk("idx1", index.length()*16); loopv(index) { aviindexentry &entry = index[i]; // printf("%3d %s %08x\n", i, (entry.type==1)?"s":"v", entry.offset); f->write(entry.type ? "01wb" : "00dc", 4); // chunkid f->putlil(0x10); // flags - KEYFRAME f->putlil(entry.offset); // offset (relative to movi) f->putlil(entry.size); // size } endchunk(); } seg.videoframes = videoframes; seg.videoindexoffset = totalsize; startchunk("ix00", 24 + indexframes*8); f->putlil(2); // longs per entry f->putlil(0x0100); // index of chunks f->putlil(indexframes); // entries in use f->write("00dc", 4); // chunk id f->putlil(seg.offset&stream::offset(0xFFFFFFFFU)); // offset low f->putlil(seg.offset>>32); // offset high f->putlil(0); // reserved 3 for(int i = seg.firstindex; i < index.length(); i++) { aviindexentry &e = index[i]; if(e.type) continue; f->putlil(e.offset + 4 + 4); f->putlil(e.size); } endchunk(); // ix00 seg.videoindexsize = uint(totalsize - seg.videoindexoffset); if(soundframes) { seg.soundframes = soundframes; seg.soundindexoffset = totalsize; startchunk("ix01", 24 + soundframes*8); f->putlil(2); // longs per entry f->putlil(0x0100); // index of chunks f->putlil(soundframes); // entries in use f->write("01wb", 4); // chunk id f->putlil(seg.offset&stream::offset(0xFFFFFFFFU)); // offset low f->putlil(seg.offset>>32); // offset high f->putlil(0); // reserved 3 for(int i = seg.firstindex; i < index.length(); i++) { aviindexentry &e = index[i]; if(!e.type) continue; f->putlil(e.offset + 4 + 4); f->putlil(e.size); } endchunk(); // ix01 seg.soundindexsize = uint(totalsize - seg.soundindexoffset); } endlistchunk(); // RIFF AVI/AVIX } bool nextsegment() { if(segments.length()) { if(segments.length() >= MAX_SUPER_INDEX) return false; flushsegment(); listchunk("RIFF", "AVIX"); } listchunk("LIST", "movi"); segments.add(avisegmentinfo(chunkoffsets[chunkdepth], index.length())); return true; } bool writevideoframe(const uchar *pixels, uint srcw, uint srch, int format, uint frame) { if(frame < videoframes) return true; switch(format) { case VID_RGB: if(srcw != videow || srch != videoh) scaleyuv(pixels, srcw, srch); else encodeyuv(pixels); break; case VID_YUV: compressyuv(pixels); break; } const uint framesize = (videow * videoh * 3) / 2; if(totalsize - segments.last().offset + framesize > 1000*1000*1000 && !nextsegment()) return false; while(videoframes <= frame) addindex(videoframes++, 0, framesize); writechunk("00dc", format == VID_YUV420 ? pixels : yuv, framesize); return true; } }; VAR(movieaccelblit, 0, 0, 1); VAR(movieaccelyuv, 0, 1, 1); VARP(movieaccel, 0, 1, 1); VARP(moviesync, 0, 0, 1); FVARP(movieminquality, 0, 0, 1); namespace recorder { static enum { REC_OK = 0, REC_USERHALT, REC_TOOSLOW, REC_FILERROR } state = REC_OK; static aviwriter *file = NULL; static int starttime = 0; static int stats[1000]; static int statsindex = 0; static uint dps = 0; // dropped frames per sample enum { MAXSOUNDBUFFERS = 128 }; // sounds queue up until there is a video frame, so at low fps you'll need a bigger queue struct soundbuffer { uchar *sound; uint size, maxsize; uint frame; soundbuffer() : sound(NULL), maxsize(0) {} ~soundbuffer() { cleanup(); } void load(uchar *stream, uint len, uint fnum) { if(len > maxsize) { DELETEA(sound); sound = new uchar[len]; maxsize = len; } size = len; frame = fnum; memcpy(sound, stream, len); } void cleanup() { DELETEA(sound); maxsize = 0; } }; static queue soundbuffers; static SDL_mutex *soundlock = NULL; enum { MAXVIDEOBUFFERS = 2 }; // double buffer struct videobuffer { uchar *video; uint w, h, bpp, frame; int format; videobuffer() : video(NULL){} ~videobuffer() { cleanup(); } void init(int nw, int nh, int nbpp) { DELETEA(video); w = nw; h = nh; bpp = nbpp; video = new uchar[w*h*bpp]; format = -1; } void cleanup() { DELETEA(video); } }; static queue videobuffers; static uint lastframe = ~0U; static GLuint scalefb = 0, scaletex[2] = { 0, 0 }; static uint scalew = 0, scaleh = 0; static GLuint encodefb = 0, encoderb = 0; static SDL_Thread *thread = NULL; static SDL_mutex *videolock = NULL; static SDL_cond *shouldencode = NULL, *shouldread = NULL; bool isrecording() { return file != NULL; } float calcquality() { return 1.0f - float(dps)/float(dps+file->videofps); // strictly speaking should lock to read dps - 1.0=perfect, 0.5=half of frames are beingdropped } int gettime() { return inbetweenframes ? getclockmillis() : totalmillis; } int videoencoder(void *data) // runs on a separate thread { for(int numvid = 0, numsound = 0;;) { SDL_LockMutex(videolock); for(; numvid > 0; numvid--) videobuffers.remove(); SDL_CondSignal(shouldread); while(videobuffers.empty() && state == REC_OK) SDL_CondWait(shouldencode, videolock); if(state != REC_OK) { SDL_UnlockMutex(videolock); break; } videobuffer &m = videobuffers.removing(); numvid++; SDL_UnlockMutex(videolock); if(file->soundfrequency > 0) { // chug data from lock protected buffer to avoid holding lock while writing to file SDL_LockMutex(soundlock); for(; numsound > 0; numsound--) soundbuffers.remove(); for(; numsound < soundbuffers.length(); numsound++) { soundbuffer &s = soundbuffers.removing(numsound); if(s.frame > m.frame) break; // sync with video } SDL_UnlockMutex(soundlock); loopi(numsound) { soundbuffer &s = soundbuffers.removing(i); if(!file->writesound(s.sound, s.size, s.frame)) state = REC_FILERROR; } } int duplicates = m.frame - (int)file->videoframes + 1; if(duplicates > 0) // determine how many frames have been dropped over the sample window { dps -= stats[statsindex]; stats[statsindex] = duplicates-1; dps += stats[statsindex]; statsindex = (statsindex+1)%file->videofps; } //printf("frame %d->%d (%d dps): sound = %d bytes\n", file->videoframes, nextframenum, dps, m.soundlength); if(calcquality() < movieminquality) state = REC_TOOSLOW; else if(!file->writevideoframe(m.video, m.w, m.h, m.format, m.frame)) state = REC_FILERROR; m.frame = ~0U; } return 0; } void soundencoder(void *udata, Uint8 *stream, int len) // callback occurs on a separate thread { SDL_LockMutex(soundlock); if(soundbuffers.full()) { if(movieminquality >= 1) state = REC_TOOSLOW; } else if(state == REC_OK) { uint nextframe = (max(gettime() - starttime, 0)*file->videofps)/1000; soundbuffer &s = soundbuffers.add(); s.load((uchar *)stream, len, nextframe); } SDL_UnlockMutex(soundlock); } void start(const char *filename, int videofps, int videow, int videoh, bool sound) { if(file) return; useshaderbyname("moviergb"); useshaderbyname("movieyuv"); useshaderbyname("moviey"); useshaderbyname("movieu"); useshaderbyname("moviev"); int fps, bestdiff, worstdiff; getfps(fps, bestdiff, worstdiff); if(videofps > fps) conoutf(CON_WARN, "frame rate may be too low to capture at %d fps", videofps); if(videow%2) videow += 1; if(videoh%2) videoh += 1; file = new aviwriter(filename, videow, videoh, videofps, sound); if(!file->open()) { conoutf(CON_ERROR, "unable to create file %s", filename); DELETEP(file); return; } conoutf("movie recording to: %s %dx%d @ %dfps%s", file->filename, file->videow, file->videoh, file->videofps, (file->soundfrequency>0)?" + sound":""); starttime = gettime(); loopi(file->videofps) stats[i] = 0; statsindex = 0; dps = 0; lastframe = ~0U; videobuffers.clear(); loopi(MAXVIDEOBUFFERS) { uint w = screen->w, h = screen->w; videobuffers.data[i].init(w, h, 4); videobuffers.data[i].frame = ~0U; } soundbuffers.clear(); soundlock = SDL_CreateMutex(); videolock = SDL_CreateMutex(); shouldencode = SDL_CreateCond(); shouldread = SDL_CreateCond(); thread = SDL_CreateThread(videoencoder, NULL); if(file->soundfrequency > 0) Mix_SetPostMix(soundencoder, NULL); } void cleanup() { if(scalefb) { glDeleteFramebuffers_(1, &scalefb); scalefb = 0; } if(scaletex[0] || scaletex[1]) { glDeleteTextures(2, scaletex); memset(scaletex, 0, sizeof(scaletex)); } scalew = scaleh = 0; if(encodefb) { glDeleteFramebuffers_(1, &encodefb); encodefb = 0; } if(encoderb) { glDeleteRenderbuffers_(1, &encoderb); encoderb = 0; } } void stop() { if(!file) return; if(state == REC_OK) state = REC_USERHALT; if(file->soundfrequency > 0) Mix_SetPostMix(NULL, NULL); SDL_LockMutex(videolock); // wakeup thread enough to kill it SDL_CondSignal(shouldencode); SDL_UnlockMutex(videolock); SDL_WaitThread(thread, NULL); // block until thread is finished cleanup(); loopi(MAXVIDEOBUFFERS) videobuffers.data[i].cleanup(); loopi(MAXSOUNDBUFFERS) soundbuffers.data[i].cleanup(); SDL_DestroyMutex(soundlock); SDL_DestroyMutex(videolock); SDL_DestroyCond(shouldencode); SDL_DestroyCond(shouldread); soundlock = videolock = NULL; shouldencode = shouldread = NULL; thread = NULL; static const char *mesgs[] = { "ok", "stopped", "computer too slow", "file error"}; conoutf("movie recording halted: %s, %d frames", mesgs[state], file->videoframes); DELETEP(file); state = REC_OK; } void drawquad(float tw, float th, float x, float y, float w, float h) { glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(tw, 0); glVertex2f(x+w, y); glTexCoord2f(0, th); glVertex2f(x, y+h); glTexCoord2f(tw, th); glVertex2f(x+w, y+h); glEnd(); } void readbuffer(videobuffer &m, uint nextframe) { bool accelyuv = movieaccelyuv && renderpath!=R_FIXEDFUNCTION && !(m.w%8), usefbo = movieaccel && hasFBO && hasTR && file->videow <= (uint)screen->w && file->videoh <= (uint)screen->h && (accelyuv || file->videow < (uint)screen->w || file->videoh < (uint)screen->h); uint w = screen->w, h = screen->h; if(usefbo) { w = file->videow; h = file->videoh; } if(w != m.w || h != m.h) m.init(w, h, 4); m.format = aviwriter::VID_RGB; m.frame = nextframe; glPixelStorei(GL_PACK_ALIGNMENT, texalign(m.video, m.w, 4)); if(usefbo) { uint tw = screen->w, th = screen->h; if(hasFBB && movieaccelblit) { tw = max(tw/2, m.w); th = max(th/2, m.h); } if(tw != scalew || th != scaleh) { if(!scalefb) glGenFramebuffers_(1, &scalefb); loopi(2) { if(!scaletex[i]) glGenTextures(1, &scaletex[i]); createtexture(scaletex[i], tw, th, NULL, 3, 1, GL_RGB, GL_TEXTURE_RECTANGLE_ARB); } scalew = tw; scaleh = th; } if(accelyuv && (!encodefb || !encoderb)) { if(!encodefb) glGenFramebuffers_(1, &encodefb); glBindFramebuffer_(GL_FRAMEBUFFER_EXT, encodefb); if(!encoderb) glGenRenderbuffers_(1, &encoderb); glBindRenderbuffer_(GL_RENDERBUFFER_EXT, encoderb); glRenderbufferStorage_(GL_RENDERBUFFER_EXT, GL_RGBA, (m.w*3)/8, m.h); glFramebufferRenderbuffer_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, encoderb); glBindRenderbuffer_(GL_RENDERBUFFER_EXT, 0); glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); } if(tw < (uint)screen->w || th < (uint)screen->h) { glBindFramebuffer_(GL_READ_FRAMEBUFFER_EXT, 0); glBindFramebuffer_(GL_DRAW_FRAMEBUFFER_EXT, scalefb); glFramebufferTexture2D_(GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_RECTANGLE_ARB, scaletex[0], 0); glBlitFramebuffer_(0, 0, screen->w, screen->h, 0, 0, tw, th, GL_COLOR_BUFFER_BIT, GL_LINEAR); glBindFramebuffer_(GL_DRAW_FRAMEBUFFER_EXT, 0); } else { glBindTexture(GL_TEXTURE_RECTANGLE_ARB, scaletex[0]); glCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, screen->w, screen->h); } if(tw > m.w || th > m.h || (!accelyuv && renderpath != R_FIXEDFUNCTION && tw >= m.w && th >= m.h)) { glBindFramebuffer_(GL_FRAMEBUFFER_EXT, scalefb); glViewport(0, 0, tw, th); glColor3f(1, 1, 1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, tw, 0, th, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_TEXTURE_RECTANGLE_ARB); do { glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_RECTANGLE_ARB, scaletex[1], 0); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, scaletex[0]); uint dw = max(tw/2, m.w), dh = max(th/2, m.h); if(dw == m.w && dh == m.h && !accelyuv && renderpath != R_FIXEDFUNCTION) { SETSHADER(movieyuv); m.format = aviwriter::VID_YUV; } else SETSHADER(moviergb); drawquad(tw, th, 0, 0, dw, dh); tw = dw; th = dh; swap(scaletex[0], scaletex[1]); } while(tw > m.w || th > m.h); glDisable(GL_TEXTURE_RECTANGLE_ARB); } if(accelyuv) { glBindFramebuffer_(GL_FRAMEBUFFER_EXT, encodefb); glViewport(0, 0, (m.w*3)/8, m.h); glColor3f(1, 1, 1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, (m.w*3)/8, m.h, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_TEXTURE_RECTANGLE_ARB); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, scaletex[0]); SETSHADER(moviey); drawquad(m.w, m.h, 0, 0, m.w/4, m.h); SETSHADER(moviev); drawquad(m.w, m.h, m.w/4, 0, m.w/8, m.h/2); SETSHADER(movieu); drawquad(m.w, m.h, m.w/4, m.h/2, m.w/8, m.h/2); glDisable(GL_TEXTURE_RECTANGLE_ARB); const uint planesize = m.w * m.h; glPixelStorei(GL_PACK_ALIGNMENT, texalign(m.video, m.w/4, 4)); glReadPixels(0, 0, m.w/4, m.h, GL_BGRA, GL_UNSIGNED_BYTE, m.video); glPixelStorei(GL_PACK_ALIGNMENT, texalign(&m.video[planesize], m.w/8, 4)); glReadPixels(m.w/4, 0, m.w/8, m.h/2, GL_BGRA, GL_UNSIGNED_BYTE, &m.video[planesize]); glPixelStorei(GL_PACK_ALIGNMENT, texalign(&m.video[planesize + planesize/4], m.w/8, 4)); glReadPixels(m.w/4, m.h/2, m.w/8, m.h/2, GL_BGRA, GL_UNSIGNED_BYTE, &m.video[planesize + planesize/4]); m.format = aviwriter::VID_YUV420; } else { glBindFramebuffer_(GL_FRAMEBUFFER_EXT, scalefb); glReadPixels(0, 0, m.w, m.h, GL_BGRA, GL_UNSIGNED_BYTE, m.video); } glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); glViewport(0, 0, screen->w, screen->h); } else glReadPixels(0, 0, m.w, m.h, GL_BGRA, GL_UNSIGNED_BYTE, m.video); } bool readbuffer() { if(!file) return false; if(state != REC_OK) { stop(); return false; } SDL_LockMutex(videolock); if(moviesync && videobuffers.full()) SDL_CondWait(shouldread, videolock); uint nextframe = (max(gettime() - starttime, 0)*file->videofps)/1000; if(!videobuffers.full() && (lastframe == ~0U || nextframe > lastframe)) { videobuffer &m = videobuffers.adding(); SDL_UnlockMutex(videolock); readbuffer(m, nextframe); SDL_LockMutex(videolock); lastframe = nextframe; videobuffers.add(); SDL_CondSignal(shouldencode); } SDL_UnlockMutex(videolock); return true; } void drawhud() { int w = screen->w, h = screen->h; if(forceaspect) w = int(ceil(h*forceaspect)); gettextres(w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); defaultshader->set(); glPushMatrix(); glScalef(1/3.0f, 1/3.0f, 1); double totalsize = file->filespaceguess(); const char *unit = "KB"; if(totalsize >= 1e9) { totalsize /= 1e9; unit = "GB"; } else if(totalsize >= 1e6) { totalsize /= 1e6; unit = "MB"; } else totalsize /= 1e3; draw_textf("recorded %.1f%s %d%%", w*3-10*FONTH, h*3-FONTH-FONTH*3/2, totalsize, unit, int(calcquality()*100)); glPopMatrix(); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } void capture() { if(readbuffer()) drawhud(); } } VARP(moview, 0, 320, 10000); VARP(movieh, 0, 240, 10000); VARP(moviefps, 1, 24, 1000); VARP(moviesound, 0, 1, 1); void movie(char *name) { if(name[0] == '\0') recorder::stop(); else if(!recorder::isrecording()) recorder::start(name, moviefps, moview ? moview : screen->w, movieh ? movieh : screen->h, moviesound!=0); } COMMAND(movie, "s"); ICOMMAND(movierecording, "", (), intret(recorder::isrecording() ? 1 : 0)); sauerbraten-0.0.20130203.dfsg/engine/normal.cpp0000644000175000017500000002717612010467000020641 0ustar vincentvincent#include "engine.h" struct normalgroup { vec pos; int flat, normals, tnormals; normalgroup() : flat(0), normals(-1), tnormals(-1) {} normalgroup(const vec &pos) : pos(pos), flat(0), normals(-1), tnormals(-1) {} }; static inline bool htcmp(const vec &v, const normalgroup &n) { return v == n.pos; } struct normal { int next; vec surface; }; struct tnormal { int next; float offset; int normals[2]; normalgroup *groups[2]; }; hashset normalgroups(1<<16); vector normals; vector tnormals; VARR(lerpangle, 0, 44, 180); static float lerpthreshold = 0; static bool usetnormals = true; static int addnormal(const vec &key, const vec &surface) { normalgroup &g = normalgroups.access(key, key); normal &n = normals.add(); n.next = g.normals; n.surface = surface; return g.normals = normals.length()-1; } static void addtnormal(const vec &key, float offset, int normal1, int normal2, normalgroup *group1, normalgroup *group2) { normalgroup &g = normalgroups.access(key, key); tnormal &n = tnormals.add(); n.next = g.tnormals; n.offset = offset; n.normals[0] = normal1; n.normals[1] = normal2; n.groups[0] = group1; n.groups[1] = group2; g.tnormals = tnormals.length()-1; } static int addnormal(const vec &key, int axis) { normalgroup &g = normalgroups.access(key, key); g.flat += 1<<(4*axis); return axis - 6; } static inline void findnormal(const normalgroup &g, const vec &surface, vec &v) { v = vec(0, 0, 0); int total = 0; if(surface.x >= lerpthreshold) { int n = (g.flat>>4)&0xF; v.x += n; total += n; } else if(surface.x <= -lerpthreshold) { int n = g.flat&0xF; v.x -= n; total += n; } if(surface.y >= lerpthreshold) { int n = (g.flat>>12)&0xF; v.y += n; total += n; } else if(surface.y <= -lerpthreshold) { int n = (g.flat>>8)&0xF; v.y -= n; total += n; } if(surface.z >= lerpthreshold) { int n = (g.flat>>20)&0xF; v.z += n; total += n; } else if(surface.z <= -lerpthreshold) { int n = (g.flat>>16)&0xF; v.z -= n; total += n; } for(int cur = g.normals; cur >= 0;) { normal &o = normals[cur]; if(o.surface.dot(surface) >= lerpthreshold) { v.add(o.surface); total++; } cur = o.next; } if(total > 1) v.normalize(); else if(!total) v = surface; } static inline bool findtnormal(const normalgroup &g, const vec &surface, vec &v) { float bestangle = lerpthreshold; tnormal *bestnorm = NULL; for(int cur = g.tnormals; cur >= 0;) { tnormal &o = tnormals[cur]; static const vec flats[6] = { vec(-1, 0, 0), vec(1, 0, 0), vec(0, -1, 0), vec(0, 1, 0), vec(0, 0, -1), vec(0, 0, 1) }; vec n1 = o.normals[0] < 0 ? flats[o.normals[0]+6] : normals[o.normals[0]].surface, n2 = o.normals[1] < 0 ? flats[o.normals[1]+6] : normals[o.normals[1]].surface, nt; nt.lerp(n1, n2, o.offset).normalize(); float tangle = nt.dot(surface); if(tangle >= bestangle) { bestangle = tangle; bestnorm = &o; } cur = o.next; } if(!bestnorm) return false; vec n1, n2; findnormal(*bestnorm->groups[0], surface, n1); findnormal(*bestnorm->groups[1], surface, n2); v.lerp(n1, n2, bestnorm->offset).normalize(); return true; } void findnormal(const vec &key, const vec &surface, vec &v) { const normalgroup *g = normalgroups.access(key); if(!g) v = surface; else if(g->tnormals < 0 || !findtnormal(*g, surface, v)) findnormal(*g, surface, v); } VARR(lerpsubdiv, 0, 2, 4); VARR(lerpsubdivsize, 4, 4, 128); static uint progress = 0; void show_addnormals_progress() { float bar1 = float(progress) / float(allocnodes); renderprogress(bar1, "computing normals..."); } void addnormals(cube &c, const ivec &o, int size) { CHECK_CALCLIGHT_PROGRESS(return, show_addnormals_progress); if(c.children) { progress++; size >>= 1; loopi(8) addnormals(c.children[i], ivec(i, o.x, o.y, o.z, size), size); return; } else if(isempty(c)) return; vec pos[MAXFACEVERTS]; int norms[MAXFACEVERTS]; int tj = usetnormals && c.ext ? c.ext->tjoints : -1, vis; loopi(6) if((vis = visibletris(c, i, o.x, o.y, o.z, size))) { CHECK_CALCLIGHT_PROGRESS(return, show_addnormals_progress); if(c.texture[i] == DEFAULT_SKY) continue; vec planes[2]; int numverts = c.ext ? c.ext->surfaces[i].numverts&MAXFACEVERTS : 0, convex = 0, numplanes = 0; if(numverts) { vertinfo *verts = c.ext->verts() + c.ext->surfaces[i].verts; vec vo = ivec(o).mask(~0xFFF).tovec(); loopj(numverts) { vertinfo &v = verts[j]; pos[j] = vec(v.x, v.y, v.z).mul(1.0f/8).add(vo); } if(!(c.merged&(1<= 0 && tjoints[tj].edge < i*(MAXFACEVERTS+1)) tj = tjoints[tj].next; while(tj >= 0 && tjoints[tj].edge < (i+1)*(MAXFACEVERTS+1)) { int edge = tjoints[tj].edge, e1 = edge%(MAXFACEVERTS+1), e2 = (e1+1)%numverts; const vec &v1 = pos[e1], &v2 = pos[e2]; ivec d = vec(v2).sub(v1).mul(8); int axis = abs(d.x) > abs(d.y) ? (abs(d.x) > abs(d.z) ? 0 : 2) : (abs(d.y) > abs(d.z) ? 1 : 2); if(d[axis] < 0) d.neg(); reduceslope(d); int origin = int(min(v1[axis], v2[axis])*8)&~0x7FFF, offset1 = (int(v1[axis]*8) - origin) / d[axis], offset2 = (int(v2[axis]*8) - origin) / d[axis]; vec o = vec(v1).sub(d.tovec().mul(offset1/8.0f)), n1, n2; float doffset = 1.0f / (offset2 - offset1); while(tj >= 0) { tjoint &t = tjoints[tj]; if(t.edge != edge) break; float offset = (t.offset - offset1) * doffset; vec tpos = d.tovec().mul(t.offset/8.0f).add(o); addtnormal(tpos, offset, norms[e1], norms[e2], normalgroups.access(v1), normalgroups.access(v2)); tj = t.next; } } } } void calcnormals(bool lerptjoints) { if(!lerpangle) return; usetnormals = lerptjoints; if(usetnormals) findtjoints(); lerpthreshold = cos(lerpangle*RAD) - 1e-5f; progress = 1; loopi(8) addnormals(worldroot[i], ivec(i, 0, 0, 0, worldsize/2), worldsize/2); } void clearnormals() { normalgroups.clear(); normals.setsize(0); tnormals.setsize(0); } void calclerpverts(const vec2 *c, const vec *n, lerpvert *lv, int &numv) { int i = 0; loopj(numv) { if(j) { if(c[j] == c[j-1] && n[j] == n[j-1]) continue; if(j == numv-1 && c[j] == c[0] && n[j] == n[0]) continue; } lv[i].normal = n[j]; lv[i].u = c[j].x; lv[i].v = c[j].y; i++; } numv = i; } void setlerpstep(float v, lerpbounds &bounds) { if(bounds.min->v + 1 > bounds.max->v) { bounds.nstep = vec(0, 0, 0); bounds.normal = bounds.min->normal; if(bounds.min->normal != bounds.max->normal) { bounds.normal.add(bounds.max->normal); bounds.normal.normalize(); } bounds.ustep = 0; bounds.u = bounds.min->u; return; } bounds.nstep = bounds.max->normal; bounds.nstep.sub(bounds.min->normal); bounds.nstep.div(bounds.max->v-bounds.min->v); bounds.normal = bounds.nstep; bounds.normal.mul(v - bounds.min->v); bounds.normal.add(bounds.min->normal); bounds.ustep = (bounds.max->u-bounds.min->u) / (bounds.max->v-bounds.min->v); bounds.u = bounds.ustep * (v-bounds.min->v) + bounds.min->u; } void initlerpbounds(float u, float v, const lerpvert *lv, int numv, lerpbounds &start, lerpbounds &end) { const lerpvert *first = &lv[0], *second = NULL; loopi(numv-1) { if(lv[i+1].v < first->v) { second = first; first = &lv[i+1]; } else if(!second || lv[i+1].v < second->v) second = &lv[i+1]; } if(int(first->v) < int(second->v)) { start.min = end.min = first; } else if(first->u > second->u) { start.min = second; end.min = first; } else { start.min = first; end.min = second; } if((lv[1].u - lv->u)*(lv[2].v - lv->v) > (lv[1].v - lv->v)*(lv[2].u - lv->u)) { start.winding = end.winding = 1; start.max = (start.min == lv ? &lv[numv-1] : start.min-1); end.max = (end.min == &lv[numv-1] ? lv : end.min+1); } else { start.winding = end.winding = -1; start.max = (start.min == &lv[numv-1] ? lv : start.min+1); end.max = (end.min == lv ? &lv[numv-1] : end.min-1); } setlerpstep(v, start); setlerpstep(v, end); } void updatelerpbounds(float v, const lerpvert *lv, int numv, lerpbounds &start, lerpbounds &end) { if(v >= start.max->v) { const lerpvert *next = start.winding > 0 ? (start.max == lv ? &lv[numv-1] : start.max-1) : (start.max == &lv[numv-1] ? lv : start.max+1); if(next->v > start.max->v) { start.min = start.max; start.max = next; setlerpstep(v, start); } } if(v >= end.max->v) { const lerpvert *next = end.winding > 0 ? (end.max == &lv[numv-1] ? lv : end.max+1) : (end.max == lv ? &lv[numv-1] : end.max-1); if(next->v > end.max->v) { end.min = end.max; end.max = next; setlerpstep(v, end); } } } void lerpnormal(float u, float v, const lerpvert *lv, int numv, lerpbounds &start, lerpbounds &end, vec &normal, vec &nstep) { updatelerpbounds(v, lv, numv, start, end); if(start.u + 1 > end.u) { nstep = vec(0, 0, 0); normal = start.normal; normal.add(end.normal); normal.normalize(); } else { vec nstart(start.normal), nend(end.normal); nstart.normalize(); nend.normalize(); nstep = nend; nstep.sub(nstart); nstep.div(end.u-start.u); normal = nstep; normal.mul(u-start.u); normal.add(nstart); normal.normalize(); } start.normal.add(start.nstep); start.u += start.ustep; end.normal.add(end.nstep); end.u += end.ustep; } sauerbraten-0.0.20130203.dfsg/engine/renderparticles.cpp0000644000175000017500000014170612067642403022551 0ustar vincentvincent// renderparticles.cpp #include "engine.h" #include "rendertarget.h" Shader *particleshader = NULL, *particlenotextureshader = NULL; VARP(particlesize, 20, 100, 500); // Check emit_particles() to limit the rate that paricles can be emitted for models/sparklies // Automatically stops particles being emitted when paused or in reflective drawing VARP(emitmillis, 1, 17, 1000); static int lastemitframe = 0, emitoffset = 0; static bool canemit = false, regenemitters = false, canstep = false; static bool emit_particles() { if(reflecting || refracting) return false; return canemit || emitoffset; } VARP(showparticles, 0, 1, 1); VAR(cullparticles, 0, 1, 1); VAR(replayparticles, 0, 1, 1); VARN(seedparticles, seedmillis, 0, 3000, 10000); VAR(dbgpcull, 0, 0, 1); VAR(dbgpseed, 0, 0, 1); struct particleemitter { extentity *ent; vec bbmin, bbmax; vec center; float radius; ivec bborigin, bbsize; int maxfade, lastemit, lastcull; particleemitter(extentity *ent) : ent(ent), bbmin(ent->o), bbmax(ent->o), maxfade(-1), lastemit(0), lastcull(0) {} void finalize() { center = vec(bbmin).add(bbmax).mul(0.5f); radius = bbmin.dist(bbmax)/2; bborigin = ivec(int(floor(bbmin.x)), int(floor(bbmin.y)), int(floor(bbmin.z))); bbsize = ivec(int(ceil(bbmax.x)), int(ceil(bbmax.y)), int(ceil(bbmax.z))).sub(bborigin); if(dbgpseed) conoutf(CON_DEBUG, "radius: %f, maxfade: %d", radius, maxfade); } void extendbb(const vec &o, float size = 0) { bbmin.x = min(bbmin.x, o.x - size); bbmin.y = min(bbmin.y, o.y - size); bbmin.z = min(bbmin.z, o.z - size); bbmax.x = max(bbmax.x, o.x + size); bbmax.y = max(bbmax.y, o.y + size); bbmax.z = max(bbmax.z, o.z + size); } void extendbb(float z, float size = 0) { bbmin.z = min(bbmin.z, z - size); bbmax.z = max(bbmax.z, z + size); } }; static vector emitters; static particleemitter *seedemitter = NULL; void clearparticleemitters() { emitters.shrink(0); regenemitters = true; } void addparticleemitters() { emitters.shrink(0); const vector &ents = entities::getents(); loopv(ents) { extentity &e = *ents[i]; if(e.type != ET_PARTICLES) continue; emitters.add(particleemitter(&e)); } regenemitters = false; } enum { PT_PART = 0, PT_TAPE, PT_TRAIL, PT_TEXT, PT_TEXTUP, PT_METER, PT_METERVS, PT_FIREBALL, PT_LIGHTNING, PT_FLARE, PT_MOD = 1<<8, PT_RND4 = 1<<9, PT_LERP = 1<<10, // use very sparingly - order of blending issues PT_TRACK = 1<<11, PT_GLARE = 1<<12, PT_SOFT = 1<<13, PT_HFLIP = 1<<14, PT_VFLIP = 1<<15, PT_ROT = 1<<16, PT_CULL = 1<<17, PT_FEW = 1<<18, PT_ICON = 1<<19, PT_FLIP = PT_HFLIP | PT_VFLIP | PT_ROT }; const char *partnames[] = { "part", "tape", "trail", "text", "textup", "meter", "metervs", "fireball", "lightning", "flare" }; struct particle { vec o, d; int gravity, fade, millis; bvec color; uchar flags; float size; union { const char *text; // will call delete[] on this only if it starts with an @ float val; physent *owner; struct { uchar color2[3]; uchar progress; }; }; }; struct partvert { vec pos; float u, v; bvec color; uchar alpha; }; #define COLLIDERADIUS 8.0f #define COLLIDEERROR 1.0f struct partrenderer { Texture *tex; const char *texname; int texclamp; uint type; int collide; partrenderer(const char *texname, int texclamp, int type, int collide = 0) : tex(NULL), texname(texname), texclamp(texclamp), type(type), collide(collide) { } partrenderer(int type, int collide = 0) : tex(NULL), texname(NULL), texclamp(0), type(type), collide(collide) { } virtual ~partrenderer() { } virtual void init(int n) { } virtual void reset() = 0; virtual void resettracked(physent *owner) { } virtual particle *addpart(const vec &o, const vec &d, int fade, int color, float size, int gravity = 0) = 0; virtual int adddepthfx(vec &bbmin, vec &bbmax) { return 0; } virtual void update() { } virtual void render() = 0; virtual bool haswork() = 0; virtual int count() = 0; //for debug virtual bool usesvertexarray() { return false; } virtual void cleanup() {} virtual void seedemitter(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int gravity) { } //blend = 0 => remove it void calc(particle *p, int &blend, int &ts, vec &o, vec &d, bool step = true) { o = p->o; d = p->d; if(type&PT_TRACK && p->owner) game::particletrack(p->owner, o, d); if(p->fade <= 5) { ts = 1; blend = 255; } else { ts = lastmillis-p->millis; blend = max(255 - (ts<<8)/p->fade, 0); if(p->gravity) { if(ts > p->fade) ts = p->fade; float t = ts; o.add(vec(d).mul(t/5000.0f)); o.z -= t*t/(2.0f * 5000.0f * p->gravity); } if(collide && o.z < p->val && step) { if(collide >= 0) { vec surface; float floorz = rayfloor(vec(o.x, o.y, p->val), surface, RAY_CLIPMAT, COLLIDERADIUS); float collidez = floorz<0 ? o.z-COLLIDERADIUS : p->val - floorz; if(o.z >= collidez+COLLIDEERROR) p->val = collidez+COLLIDEERROR; else { adddecal(collide, vec(o.x, o.y, collidez), vec(p->o).sub(o).normalize(), 2*p->size, p->color, type&PT_RND4 ? (p->flags>>5)&3 : 0); blend = 0; } } else blend = 0; } } } }; struct listparticle : particle { listparticle *next; }; VARP(outlinemeters, 0, 0, 1); struct listrenderer : partrenderer { static listparticle *parempty; listparticle *list; listrenderer(const char *texname, int texclamp, int type, int collide = 0) : partrenderer(texname, texclamp, type, collide), list(NULL) { } listrenderer(int type, int collide = 0) : partrenderer(type, collide), list(NULL) { } virtual ~listrenderer() { } virtual void killpart(listparticle *p) { } void reset() { if(!list) return; listparticle *p = list; for(;;) { killpart(p); if(p->next) p = p->next; else break; } p->next = parempty; parempty = list; list = NULL; } void resettracked(physent *owner) { if(!(type&PT_TRACK)) return; for(listparticle **prev = &list, *cur = list; cur; cur = *prev) { if(!owner || cur->owner==owner) { *prev = cur->next; cur->next = parempty; parempty = cur; } else prev = &cur->next; } } particle *addpart(const vec &o, const vec &d, int fade, int color, float size, int gravity) { if(!parempty) { listparticle *ps = new listparticle[256]; loopi(255) ps[i].next = &ps[i+1]; ps[255].next = parempty; parempty = ps; } listparticle *p = parempty; parempty = p->next; p->next = list; list = p; p->o = o; p->d = d; p->gravity = gravity; p->fade = fade; p->millis = lastmillis + emitoffset; p->color = bvec(color>>16, (color>>8)&0xFF, color&0xFF); p->size = size; p->owner = NULL; p->flags = 0; return p; } int count() { int num = 0; listparticle *lp; for(lp = list; lp; lp = lp->next) num++; return num; } bool haswork() { return (list != NULL); } virtual void startrender() = 0; virtual void endrender() = 0; virtual void renderpart(listparticle *p, const vec &o, const vec &d, int blend, int ts, uchar *color) = 0; void render() { startrender(); if(texname) { if(!tex) tex = textureload(texname, texclamp); glBindTexture(GL_TEXTURE_2D, tex->id); } for(listparticle **prev = &list, *p = list; p; p = *prev) { vec o, d; int blend, ts; calc(p, blend, ts, o, d, canstep); if(blend > 0) { renderpart(p, o, d, blend, ts, p->color.v); if(p->fade > 5 || !canstep) { prev = &p->next; continue; } } //remove *prev = p->next; p->next = parempty; killpart(p); parempty = p; } endrender(); } }; listparticle *listrenderer::parempty = NULL; struct meterrenderer : listrenderer { meterrenderer(int type) : listrenderer(type) {} void startrender() { glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); particlenotextureshader->set(); } void endrender() { glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); particleshader->set(); } void renderpart(listparticle *p, const vec &o, const vec &d, int blend, int ts, uchar *color) { int basetype = type&0xFF; glPushMatrix(); float scale = p->size/80.0f; GLfloat billboardmatrix[16] = { scale*camright.x, scale*camright.y, scale*camright.z, 0, -scale*camup.x, -scale*camup.y, -scale*camup.z, 0, -scale*camdir.x, -scale*camdir.y, -scale*camdir.z, 0, o.x, o.y, o.z, 1 }; glMultMatrixf(billboardmatrix); float right = 8*FONTH, left = p->progress/100.0f*right; glTranslatef(-right/2.0f, 0, 0); if(outlinemeters) { glColor3f(0, 0.8f, 0); glBegin(GL_TRIANGLE_STRIP); loopk(10) { const vec2 &sc = sincos360[k*(180/(10-1))]; float c = (0.5f + 0.1f)*sc.y, s = 0.5f - (0.5f + 0.1f)*sc.x; glVertex2f(-c*FONTH, s*FONTH); glVertex2f(right + c*FONTH, s*FONTH); } glEnd(); } if(basetype==PT_METERVS) glColor3ubv(p->color2); else glColor3f(0, 0, 0); glBegin(GL_TRIANGLE_STRIP); loopk(10) { const vec2 &sc = sincos360[k*(180/(10-1))]; float c = 0.5f*sc.y, s = 0.5f - 0.5f*sc.x; glVertex2f(left + c*FONTH, s*FONTH); glVertex2f(right + c*FONTH, s*FONTH); } glEnd(); if(outlinemeters) { glColor3f(0, 0.8f, 0); glBegin(GL_TRIANGLE_FAN); loopk(10) { const vec2 &sc = sincos360[k*(180/(10-1))]; float c = (0.5f + 0.1f)*sc.y, s = 0.5f - (0.5f + 0.1f)*sc.x; glVertex2f(left + c*FONTH, s*FONTH); } glEnd(); } glColor3ubv(color); glBegin(GL_TRIANGLE_STRIP); loopk(10) { const vec2 &sc = sincos360[k*(180/(10-1))]; float c = 0.5f*sc.y, s = 0.5f - 0.5f*sc.x; glVertex2f(-c*FONTH, s*FONTH); glVertex2f(left + c*FONTH, s*FONTH); } glEnd(); glPopMatrix(); } }; static meterrenderer meters(PT_METER|PT_LERP), metervs(PT_METERVS|PT_LERP); struct textrenderer : listrenderer { textrenderer(int type) : listrenderer(type) {} void startrender() { } void endrender() { } void killpart(listparticle *p) { if(p->text && p->flags&1) delete[] p->text; } void renderpart(listparticle *p, const vec &o, const vec &d, int blend, int ts, uchar *color) { glPushMatrix(); float scale = p->size/80.0f; GLfloat billboardmatrix[16] = { scale*camright.x, scale*camright.y, scale*camright.z, 0, -scale*camup.x, -scale*camup.y, -scale*camup.z, 0, -scale*camdir.x, -scale*camdir.y, -scale*camdir.z, 0, o.x, o.y, o.z, 1 }; glMultMatrixf(billboardmatrix); float xoff = -text_width(p->text)/2; float yoff = 0; if((type&0xFF)==PT_TEXTUP) { xoff += detrnd((size_t)p, 100)-50; yoff -= detrnd((size_t)p, 101); } //@TODO instead in worldspace beforehand? glTranslatef(xoff, yoff, 50); draw_text(p->text, 0, 0, color[0], color[1], color[2], blend); glPopMatrix(); } }; static textrenderer texts(PT_TEXT|PT_LERP); template static inline void modifyblend(const vec &o, int &blend) { blend = min(blend<<2, 255); } template<> inline void modifyblend(const vec &o, int &blend) { } template static inline void genpos(const vec &o, const vec &d, float size, int grav, int ts, partvert *vs) { vec udir = vec(camup).sub(camright).mul(size); vec vdir = vec(camup).add(camright).mul(size); vs[0].pos = vec(o.x + udir.x, o.y + udir.y, o.z + udir.z); vs[1].pos = vec(o.x + vdir.x, o.y + vdir.y, o.z + vdir.z); vs[2].pos = vec(o.x - udir.x, o.y - udir.y, o.z - udir.z); vs[3].pos = vec(o.x - vdir.x, o.y - vdir.y, o.z - vdir.z); } template<> inline void genpos(const vec &o, const vec &d, float size, int ts, int grav, partvert *vs) { vec dir1 = d, dir2 = d, c; dir1.sub(o); dir2.sub(camera1->o); c.cross(dir2, dir1).normalize().mul(size); vs[0].pos = vec(d.x-c.x, d.y-c.y, d.z-c.z); vs[1].pos = vec(o.x-c.x, o.y-c.y, o.z-c.z); vs[2].pos = vec(o.x+c.x, o.y+c.y, o.z+c.z); vs[3].pos = vec(d.x+c.x, d.y+c.y, d.z+c.z); } template<> inline void genpos(const vec &o, const vec &d, float size, int ts, int grav, partvert *vs) { vec e = d; if(grav) e.z -= float(ts)/grav; e.div(-75.0f).add(o); genpos(o, e, size, ts, grav, vs); } template static inline void genrotpos(const vec &o, const vec &d, float size, int grav, int ts, partvert *vs, int rot) { genpos(o, d, size, grav, ts, vs); } #define ROTCOEFFS(n) { \ vec(-1, 1, 0).rotate_around_z(n*2*M_PI/32.0f), \ vec( 1, 1, 0).rotate_around_z(n*2*M_PI/32.0f), \ vec( 1, -1, 0).rotate_around_z(n*2*M_PI/32.0f), \ vec(-1, -1, 0).rotate_around_z(n*2*M_PI/32.0f) \ } static const vec rotcoeffs[32][4] = { ROTCOEFFS(0), ROTCOEFFS(1), ROTCOEFFS(2), ROTCOEFFS(3), ROTCOEFFS(4), ROTCOEFFS(5), ROTCOEFFS(6), ROTCOEFFS(7), ROTCOEFFS(8), ROTCOEFFS(9), ROTCOEFFS(10), ROTCOEFFS(11), ROTCOEFFS(12), ROTCOEFFS(13), ROTCOEFFS(14), ROTCOEFFS(15), ROTCOEFFS(16), ROTCOEFFS(17), ROTCOEFFS(18), ROTCOEFFS(19), ROTCOEFFS(20), ROTCOEFFS(21), ROTCOEFFS(22), ROTCOEFFS(7), ROTCOEFFS(24), ROTCOEFFS(25), ROTCOEFFS(26), ROTCOEFFS(27), ROTCOEFFS(28), ROTCOEFFS(29), ROTCOEFFS(30), ROTCOEFFS(31), }; template<> inline void genrotpos(const vec &o, const vec &d, float size, int grav, int ts, partvert *vs, int rot) { const vec *coeffs = rotcoeffs[rot]; (vs[0].pos = o).add(vec(camright).mul(coeffs[0].x*size)).add(vec(camup).mul(coeffs[0].y*size)); (vs[1].pos = o).add(vec(camright).mul(coeffs[1].x*size)).add(vec(camup).mul(coeffs[1].y*size)); (vs[2].pos = o).add(vec(camright).mul(coeffs[2].x*size)).add(vec(camup).mul(coeffs[2].y*size)); (vs[3].pos = o).add(vec(camright).mul(coeffs[3].x*size)).add(vec(camup).mul(coeffs[3].y*size)); } template static inline void seedpos(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int grav) { if(grav) { vec end(o); float t = fade; end.add(vec(d).mul(t/5000.0f)); end.z -= t*t/(2.0f * 5000.0f * grav); pe.extendbb(end, size); float tpeak = d.z*grav; if(tpeak > 0 && tpeak < fade) pe.extendbb(o.z + 1.5f*d.z*tpeak/5000.0f, size); } } template<> inline void seedpos(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int grav) { pe.extendbb(d, size); } template<> inline void seedpos(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int grav) { vec e = d; if(grav) e.z -= float(fade)/grav; e.div(-75.0f).add(o); pe.extendbb(e, size); } template struct varenderer : partrenderer { partvert *verts; particle *parts; int maxparts, numparts, lastupdate, rndmask; varenderer(const char *texname, int type, int collide = 0) : partrenderer(texname, 3, type, collide), verts(NULL), parts(NULL), maxparts(0), numparts(0), lastupdate(-1), rndmask(0) { if(type & PT_HFLIP) rndmask |= 0x01; if(type & PT_VFLIP) rndmask |= 0x02; if(type & PT_ROT) rndmask |= 0x1F<<2; if(type & PT_RND4) rndmask |= 0x03<<5; } void init(int n) { DELETEA(parts); DELETEA(verts); parts = new particle[n]; verts = new partvert[n*4]; maxparts = n; numparts = 0; lastupdate = -1; } void reset() { numparts = 0; lastupdate = -1; } void resettracked(physent *owner) { if(!(type&PT_TRACK)) return; loopi(numparts) { particle *p = parts+i; if(!owner || (p->owner == owner)) p->fade = -1; } lastupdate = -1; } int count() { return numparts; } bool haswork() { return (numparts > 0); } bool usesvertexarray() { return true; } particle *addpart(const vec &o, const vec &d, int fade, int color, float size, int gravity) { particle *p = parts + (numparts < maxparts ? numparts++ : rnd(maxparts)); //next free slot, or kill a random kitten p->o = o; p->d = d; p->gravity = gravity; p->fade = fade; p->millis = lastmillis + emitoffset; p->color = bvec(color>>16, (color>>8)&0xFF, color&0xFF); p->size = size; p->owner = NULL; p->flags = 0x80 | (rndmask ? rnd(0x80) & rndmask : 0); lastupdate = -1; return p; } void seedemitter(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int gravity) { pe.maxfade = max(pe.maxfade, fade); size *= SQRT2; pe.extendbb(o, size); seedpos(pe, o, d, fade, size, gravity); if(!gravity) return; vec end(o); float t = fade; end.add(vec(d).mul(t/5000.0f)); end.z -= t*t/(2.0f * 5000.0f * gravity); pe.extendbb(end, size); float tpeak = d.z*gravity; if(tpeak > 0 && tpeak < fade) pe.extendbb(o.z + 1.5f*d.z*tpeak/5000.0f, size); } void genverts(particle *p, partvert *vs, bool regen) { vec o, d; int blend, ts; calc(p, blend, ts, o, d); if(blend <= 1 || p->fade <= 5) p->fade = -1; //mark to remove on next pass (i.e. after render) modifyblend(o, blend); if(regen) { p->flags &= ~0x80; #define SETTEXCOORDS(u1c, u2c, v1c, v2c, body) \ { \ float u1 = u1c, u2 = u2c, v1 = v1c, v2 = v2c; \ body; \ vs[0].u = u1; \ vs[0].v = v1; \ vs[1].u = u2; \ vs[1].v = v1; \ vs[2].u = u2; \ vs[2].v = v2; \ vs[3].u = u1; \ vs[3].v = v2; \ } if(type&PT_RND4) { float tx = 0.5f*((p->flags>>5)&1), ty = 0.5f*((p->flags>>6)&1); SETTEXCOORDS(tx, tx + 0.5f, ty, ty + 0.5f, { if(p->flags&0x01) swap(u1, u2); if(p->flags&0x02) swap(v1, v2); }); } else if(type&PT_ICON) { float tx = 0.25f*(p->flags&3), ty = 0.25f*((p->flags>>2)&3); SETTEXCOORDS(tx, tx + 0.25f, ty, ty + 0.25f, {}); } else SETTEXCOORDS(0, 1, 0, 1, {}); #define SETCOLOR(r, g, b, a) \ do { \ uchar col[4] = { uchar(r), uchar(g), uchar(b), uchar(a) }; \ loopi(4) memcpy(vs[i].color.v, col, sizeof(col)); \ } while(0) #define SETMODCOLOR SETCOLOR((p->color[0]*blend)>>8, (p->color[1]*blend)>>8, (p->color[2]*blend)>>8, 255) if(type&PT_MOD) SETMODCOLOR; else SETCOLOR(p->color[0], p->color[1], p->color[2], blend); } else if(type&PT_MOD) SETMODCOLOR; else loopi(4) vs[i].alpha = blend; if(type&PT_ROT) genrotpos(o, d, p->size, ts, p->gravity, vs, (p->flags>>2)&0x1F); else genpos(o, d, p->size, ts, p->gravity, vs); } void update() { if(lastmillis == lastupdate) return; lastupdate = lastmillis; loopi(numparts) { particle *p = &parts[i]; partvert *vs = &verts[i*4]; if(p->fade < 0) { do { --numparts; if(numparts <= i) return; } while(parts[numparts].fade < 0); *p = parts[numparts]; genverts(p, vs, true); } else genverts(p, vs, (p->flags&0x80)!=0); } } void render() { if(!tex) tex = textureload(texname, texclamp); glBindTexture(GL_TEXTURE_2D, tex->id); glVertexPointer(3, GL_FLOAT, sizeof(partvert), &verts->pos); glTexCoordPointer(2, GL_FLOAT, sizeof(partvert), &verts->u); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(partvert), &verts->color); glDrawArrays(GL_QUADS, 0, numparts*4); } }; typedef varenderer quadrenderer; typedef varenderer taperenderer; typedef varenderer trailrenderer; #include "depthfx.h" #include "explosion.h" #include "lensflare.h" #include "lightning.h" struct softquadrenderer : quadrenderer { softquadrenderer(const char *texname, int type, int collide = 0) : quadrenderer(texname, type|PT_SOFT, collide) { } int adddepthfx(vec &bbmin, vec &bbmax) { if(!depthfxtex.highprecision() && !depthfxtex.emulatehighprecision()) return 0; int numsoft = 0; loopi(numparts) { particle &p = parts[i]; float radius = p.size*SQRT2; vec o, d; int blend, ts; calc(&p, blend, ts, o, d, false); if(!isfoggedsphere(radius, p.o) && (depthfxscissor!=2 || depthfxtex.addscissorbox(p.o, radius))) { numsoft++; loopk(3) { bbmin[k] = min(bbmin[k], o[k] - radius); bbmax[k] = max(bbmax[k], o[k] + radius); } } } return numsoft; } }; static partrenderer *parts[] = { new quadrenderer("packages/particles/blood.png", PT_PART|PT_FLIP|PT_MOD|PT_RND4, DECAL_BLOOD), // blood spats (note: rgb is inverted) new trailrenderer("packages/particles/base.png", PT_TRAIL|PT_LERP), // water, entity new quadrenderer("packages/particles/smoke.png", PT_PART|PT_FLIP|PT_LERP), // smoke new quadrenderer("packages/particles/steam.png", PT_PART|PT_FLIP), // steam new quadrenderer("packages/particles/flames.png", PT_PART|PT_HFLIP|PT_RND4|PT_GLARE), // flame on - no flipping please, they have orientation new quadrenderer("packages/particles/ball1.png", PT_PART|PT_FEW|PT_GLARE), // fireball1 new quadrenderer("packages/particles/ball2.png", PT_PART|PT_FEW|PT_GLARE), // fireball2 new quadrenderer("packages/particles/ball3.png", PT_PART|PT_FEW|PT_GLARE), // fireball3 new taperenderer("packages/particles/flare.jpg", PT_TAPE|PT_GLARE), // streak &lightnings, // lightning &fireballs, // explosion fireball &bluefireballs, // bluish explosion fireball new quadrenderer("packages/particles/spark.png", PT_PART|PT_FLIP|PT_GLARE), // sparks new quadrenderer("packages/particles/base.png", PT_PART|PT_FLIP|PT_GLARE), // edit mode entities new quadrenderer("packages/particles/snow.png", PT_PART|PT_FLIP|PT_RND4, -1), // colliding snow new quadrenderer("packages/particles/muzzleflash1.jpg", PT_PART|PT_FEW|PT_FLIP|PT_GLARE|PT_TRACK), // muzzle flash new quadrenderer("packages/particles/muzzleflash2.jpg", PT_PART|PT_FEW|PT_FLIP|PT_GLARE|PT_TRACK), // muzzle flash new quadrenderer("packages/particles/muzzleflash3.jpg", PT_PART|PT_FEW|PT_FLIP|PT_GLARE|PT_TRACK), // muzzle flash new quadrenderer("packages/hud/items.png", PT_PART|PT_FEW|PT_ICON), // hud icon new quadrenderer("packages/hud/items.png", PT_PART|PT_FEW|PT_ICON), // grey hud icon &texts, // text &meters, // meter &metervs, // meter vs. &flares // lens flares - must be done last }; void finddepthfxranges() { depthfxmin = vec(1e16f, 1e16f, 1e16f); depthfxmax = vec(0, 0, 0); numdepthfxranges = fireballs.finddepthfxranges(depthfxowners, depthfxranges, 0, MAXDFXRANGES, depthfxmin, depthfxmax); numdepthfxranges = bluefireballs.finddepthfxranges(depthfxowners, depthfxranges, numdepthfxranges, MAXDFXRANGES, depthfxmin, depthfxmax); loopk(3) { depthfxmin[k] -= depthfxmargin; depthfxmax[k] += depthfxmargin; } if(depthfxparts) { loopi(sizeof(parts)/sizeof(parts[0])) { partrenderer *p = parts[i]; if(p->type&PT_SOFT && p->adddepthfx(depthfxmin, depthfxmax)) { if(!numdepthfxranges) { numdepthfxranges = 1; depthfxowners[0] = NULL; depthfxranges[0] = 0; } } } } if(depthfxscissor<2 && numdepthfxranges>0) depthfxtex.addscissorbox(depthfxmin, depthfxmax); } VARFP(maxparticles, 10, 4000, 40000, particleinit()); VARFP(fewparticles, 10, 100, 40000, particleinit()); void particleinit() { if(!particleshader) particleshader = lookupshaderbyname("particle"); if(!particlenotextureshader) particlenotextureshader = lookupshaderbyname("particlenotexture"); loopi(sizeof(parts)/sizeof(parts[0])) parts[i]->init(parts[i]->type&PT_FEW ? min(fewparticles, maxparticles) : maxparticles); } void clearparticles() { loopi(sizeof(parts)/sizeof(parts[0])) parts[i]->reset(); clearparticleemitters(); } void cleanupparticles() { loopi(sizeof(parts)/sizeof(parts[0])) parts[i]->cleanup(); } void removetrackedparticles(physent *owner) { loopi(sizeof(parts)/sizeof(parts[0])) parts[i]->resettracked(owner); } VARP(particleglare, 0, 2, 100); VAR(debugparticles, 0, 0, 1); void renderparticles(bool mainpass) { canstep = mainpass; //want to debug BEFORE the lastpass render (that would delete particles) if(debugparticles && !glaring && !reflecting && !refracting) { int n = sizeof(parts)/sizeof(parts[0]); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, FONTH*n*2*screen->w/float(screen->h), FONTH*n*2, 0, -1, 1); //squeeze into top-left corner glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); defaultshader->set(); loopi(n) { int type = parts[i]->type; const char *title = parts[i]->texname ? strrchr(parts[i]->texname, '/')+1 : NULL; string info = ""; if(type&PT_GLARE) concatstring(info, "g,"); if(type&PT_LERP) concatstring(info, "l,"); if(type&PT_MOD) concatstring(info, "m,"); if(type&PT_RND4) concatstring(info, "r,"); if(type&PT_TRACK) concatstring(info, "t,"); if(type&PT_FLIP) concatstring(info, "f,"); if(parts[i]->collide) concatstring(info, "c,"); if(info[0]) info[strlen(info)-1] = '\0'; defformatstring(ds)("%d\t%s(%s) %s", parts[i]->count(), partnames[type&0xFF], info, title ? title : ""); draw_text(ds, FONTH, (i+n/2)*FONTH); } glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } if(glaring && !particleglare) return; loopi(sizeof(parts)/sizeof(parts[0])) { if(glaring && !(parts[i]->type&PT_GLARE)) continue; parts[i]->update(); } static float zerofog[4] = { 0, 0, 0, 1 }; float oldfogc[4]; bool rendered = false; uint lastflags = PT_LERP, flagmask = PT_LERP|PT_MOD; if(binddepthfxtex()) flagmask |= PT_SOFT; loopi(sizeof(parts)/sizeof(parts[0])) { partrenderer *p = parts[i]; if(glaring && !(p->type&PT_GLARE)) continue; if(!p->haswork()) continue; if(!rendered) { rendered = true; glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if(glaring) setenvparamf("colorscale", SHPARAM_VERTEX, 4, particleglare, particleglare, particleglare, 1); else setenvparamf("colorscale", SHPARAM_VERTEX, 4, 1, 1, 1, 1); particleshader->set(); glGetFloatv(GL_FOG_COLOR, oldfogc); } uint flags = p->type & flagmask; if(p->usesvertexarray()) flags |= 0x01; //0x01 = VA marker uint changedbits = (flags ^ lastflags); if(changedbits != 0x0000) { if(changedbits&0x01) { if(flags&0x01) { glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); } else { glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); } } if(changedbits&PT_LERP) glFogfv(GL_FOG_COLOR, (flags&PT_LERP) ? oldfogc : zerofog); if(changedbits&(PT_LERP|PT_MOD)) { if(flags&PT_LERP) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); else if(flags&PT_MOD) glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR); else glBlendFunc(GL_SRC_ALPHA, GL_ONE); } if(changedbits&PT_SOFT) { if(flags&PT_SOFT) { if(depthfxtex.target==GL_TEXTURE_RECTANGLE_ARB) { if(!depthfxtex.highprecision()) SETSHADER(particlesoft8rect); else SETSHADER(particlesoftrect); } else { if(!depthfxtex.highprecision()) SETSHADER(particlesoft8); else SETSHADER(particlesoft); } binddepthfxparams(depthfxpartblend); } else particleshader->set(); } lastflags = flags; } p->render(); } if(rendered) { if(lastflags&(PT_LERP|PT_MOD)) glBlendFunc(GL_SRC_ALPHA, GL_ONE); if(!(lastflags&PT_LERP)) glFogfv(GL_FOG_COLOR, oldfogc); if(lastflags&0x01) { glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); } glDisable(GL_BLEND); glDepthMask(GL_TRUE); } } static int addedparticles = 0; static inline particle *newparticle(const vec &o, const vec &d, int fade, int type, int color, float size, int gravity = 0) { static particle dummy; if(seedemitter) { parts[type]->seedemitter(*seedemitter, o, d, fade, size, gravity); return &dummy; } if(fade + emitoffset < 0) return &dummy; addedparticles++; return parts[type]->addpart(o, d, fade, color, size, gravity); } VARP(maxparticledistance, 256, 1024, 4096); static void splash(int type, int color, int radius, int num, int fade, const vec &p, float size, int gravity) { if(camera1->o.dist(p) > maxparticledistance && !seedemitter) return; float collidez = parts[type]->collide ? p.z - raycube(p, vec(0, 0, -1), COLLIDERADIUS, RAY_CLIPMAT) + (parts[type]->collide >= 0 ? COLLIDEERROR : 0) : -1; int fmin = 1; int fmax = fade*3; loopi(num) { int x, y, z; do { x = rnd(radius*2)-radius; y = rnd(radius*2)-radius; z = rnd(radius*2)-radius; } while(x*x+y*y+z*z>radius*radius); vec tmp = vec((float)x, (float)y, (float)z); int f = (num < 10) ? (fmin + rnd(fmax)) : (fmax - (i*(fmax-fmin))/(num-1)); //help deallocater by using fade distribution rather than random newparticle(p, tmp, f, type, color, size, gravity)->val = collidez; } } static void regularsplash(int type, int color, int radius, int num, int fade, const vec &p, float size, int gravity, int delay = 0) { if(!emit_particles() || (delay > 0 && rnd(delay) != 0)) return; splash(type, color, radius, num, fade, p, size, gravity); } bool canaddparticles() { return !renderedgame && !shadowmapping; } void regular_particle_splash(int type, int num, int fade, const vec &p, int color, float size, int radius, int gravity, int delay) { if(!canaddparticles()) return; regularsplash(type, color, radius, num, fade, p, size, gravity, delay); } void particle_splash(int type, int num, int fade, const vec &p, int color, float size, int radius, int gravity) { if(!canaddparticles()) return; splash(type, color, radius, num, fade, p, size, gravity); } VARP(maxtrail, 1, 500, 10000); void particle_trail(int type, int fade, const vec &s, const vec &e, int color, float size, int gravity) { if(!canaddparticles()) return; vec v; float d = e.dist(s, v); int steps = clamp(int(d*2), 1, maxtrail); v.div(steps); vec p = s; loopi(steps) { p.add(v); vec tmp = vec(float(rnd(11)-5), float(rnd(11)-5), float(rnd(11)-5)); newparticle(p, tmp, rnd(fade)+fade, type, color, size, gravity); } } VARP(particletext, 0, 1, 1); VARP(maxparticletextdistance, 0, 128, 10000); void particle_text(const vec &s, const char *t, int type, int fade, int color, float size, int gravity) { if(!canaddparticles()) return; if(!particletext || camera1->o.dist(s) > maxparticletextdistance) return; particle *p = newparticle(s, vec(0, 0, 1), fade, type, color, size, gravity); p->text = t; } void particle_textcopy(const vec &s, const char *t, int type, int fade, int color, float size, int gravity) { if(!canaddparticles()) return; if(!particletext || camera1->o.dist(s) > maxparticletextdistance) return; particle *p = newparticle(s, vec(0, 0, 1), fade, type, color, size, gravity); p->text = newstring(t); p->flags = 1; } void particle_icon(const vec &s, int ix, int iy, int type, int fade, int color, float size, int gravity) { if(!canaddparticles()) return; particle *p = newparticle(s, vec(0, 0, 1), fade, type, color, size, gravity); p->flags |= ix | (iy<<2); } void particle_meter(const vec &s, float val, int type, int fade, int color, int color2, float size) { if(!canaddparticles()) return; particle *p = newparticle(s, vec(0, 0, 1), fade, type, color, size); p->color2[0] = color2>>16; p->color2[1] = (color2>>8)&0xFF; p->color2[2] = color2&0xFF; p->progress = clamp(int(val*100), 0, 100); } void particle_flare(const vec &p, const vec &dest, int fade, int type, int color, float size, physent *owner) { if(!canaddparticles()) return; newparticle(p, dest, fade, type, color, size)->owner = owner; } void particle_fireball(const vec &dest, float maxsize, int type, int fade, int color, float size) { if(!canaddparticles()) return; float growth = maxsize - size; if(fade < 0) fade = int(growth*20); newparticle(dest, vec(0, 0, 1), fade, type, color, size)->val = growth; } //dir = 0..6 where 0=up static inline vec offsetvec(vec o, int dir, int dist) { vec v = vec(o); v[(2+dir)%3] += (dir>2)?(-dist):dist; return v; } //converts a 16bit color to 24bit static inline int colorfromattr(int attr) { return (((attr&0xF)<<4) | ((attr&0xF0)<<8) | ((attr&0xF00)<<12)) + 0x0F0F0F; } /* Experiments in shapes... * dir: (where dir%3 is similar to offsetvec with 0=up) * 0..2 circle * 3.. 5 cylinder shell * 6..11 cone shell * 12..14 plane volume * 15..20 line volume, i.e. wall * 21 sphere * 24..26 flat plane * +32 to inverse direction */ void regularshape(int type, int radius, int color, int dir, int num, int fade, const vec &p, float size, int gravity, int vel = 200) { if(!emit_particles()) return; int basetype = parts[type]->type&0xFF; bool flare = (basetype == PT_TAPE) || (basetype == PT_LIGHTNING), inv = (dir&0x20)!=0, taper = (dir&0x40)!=0 && !seedemitter; dir &= 0x1F; loopi(num) { vec to, from; if(dir < 12) { const vec2 &sc = sincos360[rnd(360)]; to[dir%3] = sc.y*radius; to[(dir+1)%3] = sc.x*radius; to[(dir+2)%3] = 0.0; to.add(p); if(dir < 3) //circle from = p; else if(dir < 6) //cylinder { from = to; to[(dir+2)%3] += radius; from[(dir+2)%3] -= radius; } else //cone { from = p; to[(dir+2)%3] += (dir < 9)?radius:(-radius); } } else if(dir < 15) //plane { to[dir%3] = float(rnd(radius<<4)-(radius<<3))/8.0; to[(dir+1)%3] = float(rnd(radius<<4)-(radius<<3))/8.0; to[(dir+2)%3] = radius; to.add(p); from = to; from[(dir+2)%3] -= 2*radius; } else if(dir < 21) //line { if(dir < 18) { to[dir%3] = float(rnd(radius<<4)-(radius<<3))/8.0; to[(dir+1)%3] = 0.0; } else { to[dir%3] = 0.0; to[(dir+1)%3] = float(rnd(radius<<4)-(radius<<3))/8.0; } to[(dir+2)%3] = 0.0; to.add(p); from = to; to[(dir+2)%3] += radius; } else if(dir < 24) //sphere { to = vec(PI2*float(rnd(1000))/1000.0, PI*float(rnd(1000)-500)/1000.0).mul(radius); to.add(p); from = p; } else if(dir < 27) // flat plane { to[dir%3] = float(rndscale(2*radius)-radius); to[(dir+1)%3] = float(rndscale(2*radius)-radius); to[(dir+2)%3] = 0.0; to.add(p); from = to; } else from = to = p; if(inv) swap(from, to); if(taper) { float dist = clamp(from.dist2(camera1->o)/maxparticledistance, 0.0f, 1.0f); if(dist > 0.2f) { dist = 1 - (dist - 0.2f)/0.8f; if(rnd(0x10000) > dist*dist*0xFFFF) continue; } } if(flare) newparticle(from, to, rnd(fade*3)+1, type, color, size, gravity); else { vec d = vec(to).sub(from).rescale(vel); //velocity particle *n = newparticle(from, d, rnd(fade*3)+1, type, color, size, gravity); if(parts[type]->collide) n->val = from.z - raycube(from, vec(0, 0, -1), parts[type]->collide >= 0 ? COLLIDERADIUS : max(from.z, 0.0f), RAY_CLIPMAT) + (parts[type]->collide >= 0 ? COLLIDEERROR : 0); } } } static void regularflame(int type, const vec &p, float radius, float height, int color, int density = 3, float scale = 2.0f, float speed = 200.0f, float fade = 600.0f, int gravity = -15) { if(!emit_particles()) return; float size = scale * min(radius, height); vec v(0, 0, min(1.0f, height)*speed); loopi(density) { vec s = p; s.x += rndscale(radius*2.0f)-radius; s.y += rndscale(radius*2.0f)-radius; newparticle(s, v, rnd(max(int(fade*height), 1))+1, type, color, size, gravity); } } void regular_particle_flame(int type, const vec &p, float radius, float height, int color, int density, float scale, float speed, float fade, int gravity) { if(!canaddparticles()) return; regularflame(type, p, radius, height, color, density, scale, speed, fade, gravity); } static void makeparticles(entity &e) { switch(e.attr1) { case 0: //fire and smoke - - 0 values default to compat for old maps { //regularsplash(PART_FIREBALL1, 0xFFC8C8, 150, 1, 40, e.o, 4.8f); //regularsplash(PART_SMOKE, 0x897661, 50, 1, 200, vec(e.o.x, e.o.y, e.o.z+3.0f), 2.4f, -20, 3); float radius = e.attr2 ? float(e.attr2)/100.0f : 1.5f, height = e.attr3 ? float(e.attr3)/100.0f : radius/3; regularflame(PART_FLAME, e.o, radius, height, e.attr4 ? colorfromattr(e.attr4) : 0x903020, 3, 2.0f); regularflame(PART_SMOKE, vec(e.o.x, e.o.y, e.o.z + 4.0f*min(radius, height)), radius, height, 0x303020, 1, 4.0f, 100.0f, 2000.0f, -20); break; } case 1: //steam vent - regularsplash(PART_STEAM, 0x897661, 50, 1, 200, offsetvec(e.o, e.attr2, rnd(10)), 2.4f, -20); break; case 2: //water fountain - { int color; if(e.attr3 > 0) color = colorfromattr(e.attr3); else { int mat = MAT_WATER + clamp(-e.attr3, 0, 3); const bvec &wfcol = getwaterfallcolor(mat); color = (int(wfcol[0])<<16) | (int(wfcol[1])<<8) | int(wfcol[2]); if(!color) { const bvec &wcol = getwatercolor(mat); color = (int(wcol[0])<<16) | (int(wcol[1])<<8) | int(wcol[2]); } } regularsplash(PART_WATER, color, 150, 4, 200, offsetvec(e.o, e.attr2, rnd(10)), 0.6f, 2); break; } case 3: //fire ball - newparticle(e.o, vec(0, 0, 1), 1, PART_EXPLOSION, colorfromattr(e.attr3), 4.0f)->val = 1+e.attr2; break; case 4: //tape - case 7: //lightning case 9: //steam case 10: //water case 13: //snow { static const int typemap[] = { PART_STREAK, -1, -1, PART_LIGHTNING, -1, PART_STEAM, PART_WATER, -1, -1, PART_SNOW }; static const float sizemap[] = { 0.28f, 0.0f, 0.0f, 1.0f, 0.0f, 2.4f, 0.60f, 0.0f, 0.0f, 0.5f }; static const int gravmap[] = { 0, 0, 0, 0, 0, -20, 2, 0, 0, 20 }; int type = typemap[e.attr1-4]; float size = sizemap[e.attr1-4]; int gravity = gravmap[e.attr1-4]; if(e.attr2 >= 256) regularshape(type, max(1+e.attr3, 1), colorfromattr(e.attr4), e.attr2-256, 5, e.attr5 > 0 ? min(int(e.attr5), 10000) : 200, e.o, size, gravity); else newparticle(e.o, offsetvec(e.o, e.attr2, max(1+e.attr3, 0)), 1, type, colorfromattr(e.attr4), size, gravity); break; } case 5: //meter, metervs - case 6: { particle *p = newparticle(e.o, vec(0, 0, 1), 1, e.attr1==5 ? PART_METER : PART_METER_VS, colorfromattr(e.attr3), 2.0f); int color2 = colorfromattr(e.attr4); p->color2[0] = color2>>16; p->color2[1] = (color2>>8)&0xFF; p->color2[2] = color2&0xFF; p->progress = clamp(int(e.attr2), 0, 100); break; } case 11: // flame - radius=100, height=100 is the classic size regularflame(PART_FLAME, e.o, float(e.attr2)/100.0f, float(e.attr3)/100.0f, colorfromattr(e.attr4), 3, 2.0f); break; case 12: // smoke plume regularflame(PART_SMOKE, e.o, float(e.attr2)/100.0f, float(e.attr3)/100.0f, colorfromattr(e.attr4), 1, 4.0f, 100.0f, 2000.0f, -20); break; case 32: //lens flares - plain/sparkle/sun/sparklesun case 33: case 34: case 35: flares.addflare(e.o, e.attr2, e.attr3, e.attr4, (e.attr1&0x02)!=0, (e.attr1&0x01)!=0); break; default: if(!editmode) { defformatstring(ds)("particles %d?", e.attr1); particle_textcopy(e.o, ds, PART_TEXT, 1, 0x6496FF, 2.0f); } break; } } bool printparticles(extentity &e, char *buf) { switch(e.attr1) { case 0: case 4: case 7: case 8: case 9: case 10: case 11: case 12: case 13: formatstring(buf)("%s %d %d %d 0x%.3hX %d", entities::entname(e.type), e.attr1, e.attr2, e.attr3, e.attr4, e.attr5); return true; case 3: formatstring(buf)("%s %d %d 0x%.3hX %d %d", entities::entname(e.type), e.attr1, e.attr2, e.attr3, e.attr4, e.attr5); return true; case 5: case 6: formatstring(buf)("%s %d %d 0x%.3hX 0x%.3hX %d", entities::entname(e.type), e.attr1, e.attr2, e.attr3, e.attr4, e.attr5); return true; } return false; } void seedparticles() { renderprogress(0, "seeding particles"); addparticleemitters(); canemit = true; loopv(emitters) { particleemitter &pe = emitters[i]; extentity &e = *pe.ent; seedemitter = &pe; for(int millis = 0; millis < seedmillis; millis += min(emitmillis, seedmillis/10)) makeparticles(e); seedemitter = NULL; pe.lastemit = -seedmillis; pe.finalize(); } } void updateparticles() { if(regenemitters) addparticleemitters(); if(lastmillis - lastemitframe >= emitmillis) { canemit = true; lastemitframe = lastmillis - (lastmillis%emitmillis); } else canemit = false; flares.makelightflares(); if(!editmode || showparticles) { int emitted = 0, replayed = 0; addedparticles = 0; loopv(emitters) { particleemitter &pe = emitters[i]; extentity &e = *pe.ent; if(e.o.dist(camera1->o) > maxparticledistance) { pe.lastemit = lastmillis; continue; } if(cullparticles && pe.maxfade >= 0) { if(isfoggedsphere(pe.radius, pe.center)) { pe.lastcull = lastmillis; continue; } if(pvsoccluded(pe.bborigin, pe.bbsize)) { pe.lastcull = lastmillis; continue; } } makeparticles(e); emitted++; if(replayparticles && pe.maxfade > 5 && pe.lastcull > pe.lastemit) { for(emitoffset = max(pe.lastemit + emitmillis - lastmillis, -pe.maxfade); emitoffset < 0; emitoffset += emitmillis) { makeparticles(e); replayed++; } emitoffset = 0; } pe.lastemit = lastmillis; } if(dbgpcull && (canemit || replayed) && addedparticles) conoutf(CON_DEBUG, "%d emitters, %d particles", emitted, addedparticles); } if(editmode) // show sparkly thingies for map entities in edit mode { const vector &ents = entities::getents(); // note: order matters in this case as particles of the same type are drawn in the reverse order that they are added loopv(entgroup) { entity &e = *ents[entgroup[i]]; particle_textcopy(e.o, entname(e), PART_TEXT, 1, 0xFF4B19, 2.0f); } loopv(ents) { entity &e = *ents[i]; if(e.type==ET_EMPTY) continue; particle_textcopy(e.o, entname(e), PART_TEXT, 1, 0x1EC850, 2.0f); regular_particle_splash(PART_EDIT, 2, 40, e.o, 0x3232FF, 0.32f*particlesize/100.0f); } } } sauerbraten-0.0.20130203.dfsg/engine/lightmap.h0000644000175000017500000000712512071421015020616 0ustar vincentvincent#define LM_MINW 2 #define LM_MINH 2 #define LM_MAXW 128 #define LM_MAXH 128 #define LM_PACKW 512 #define LM_PACKH 512 struct PackNode { PackNode *child1, *child2; ushort x, y, w, h; int available; PackNode() : child1(0), child2(0), x(0), y(0), w(LM_PACKW), h(LM_PACKH), available(min(LM_PACKW, LM_PACKH)) {} PackNode(ushort x, ushort y, ushort w, ushort h) : child1(0), child2(0), x(x), y(y), w(w), h(h), available(min(w, h)) {} void clear() { DELETEP(child1); DELETEP(child2); } ~PackNode() { clear(); } bool insert(ushort &tx, ushort &ty, ushort tw, ushort th); }; enum { LM_DIFFUSE = 0, LM_BUMPMAP0, LM_BUMPMAP1, LM_TYPE = 0x0F, LM_ALPHA = 1<<4, LM_FLAGS = 0xF0 }; struct LightMap { int type, bpp, tex, offsetx, offsety; PackNode packroot; uint lightmaps, lumels; int unlitx, unlity; uchar *data; LightMap() : type(LM_DIFFUSE), bpp(3), tex(-1), offsetx(-1), offsety(-1), lightmaps(0), lumels(0), unlitx(-1), unlity(-1), data(NULL) { } ~LightMap() { if(data) delete[] data; } void finalize() { packroot.clear(); packroot.available = 0; } void copy(ushort tx, ushort ty, uchar *src, ushort tw, ushort th); bool insert(ushort &tx, ushort &ty, uchar *src, ushort tw, ushort th); }; extern vector lightmaps; struct LightMapTexture { int w, h, type; GLuint id; int unlitx, unlity; LightMapTexture() : w(0), h(0), type(LM_DIFFUSE), id(0), unlitx(-1), unlity(-1) {} }; extern vector lightmaptexs; extern bvec ambientcolor, skylightcolor; extern void clearlights(); extern void initlights(); extern void lightents(bool force = false); extern void clearlightcache(int id = -1); extern void resetlightmaps(bool fullclean = true); extern void brightencube(cube &c); extern void setsurfaces(cube &c, const surfaceinfo *surfs, const vertinfo *verts, int numverts); extern void setsurface(cube &c, int orient, const surfaceinfo &surf, const vertinfo *verts, int numverts); extern void previewblends(const ivec &bo, const ivec &bs); struct lerpvert { vec normal; float u, v; bool operator==(const lerpvert &l) const { return u == l.u && v == l.v; } bool operator!=(const lerpvert &l) const { return u != l.u || v != l.v; } }; struct lerpbounds { const lerpvert *min; const lerpvert *max; float u, ustep; vec normal, nstep; int winding; }; extern void calcnormals(bool lerptjoints = false); extern void clearnormals(); extern void findnormal(const vec &key, const vec &surface, vec &v); extern void calclerpverts(const vec2 *c, const vec *n, lerpvert *lv, int &numv); extern void initlerpbounds(float u, float v, const lerpvert *lv, int numv, lerpbounds &start, lerpbounds &end); extern void lerpnormal(float u, float v, const lerpvert *lv, int numv, lerpbounds &start, lerpbounds &end, vec &normal, vec &nstep); #define CHECK_CALCLIGHT_PROGRESS_LOCKED(exit, show_calclight_progress, before, after) \ if(check_calclight_progress) \ { \ if(!calclight_canceled) \ { \ before; \ show_calclight_progress(); \ check_calclight_canceled(); \ after; \ } \ if(calclight_canceled) { exit; } \ } #define CHECK_CALCLIGHT_PROGRESS(exit, show_calclight_progress) CHECK_CALCLIGHT_PROGRESS_LOCKED(exit, show_calclight_progress, , ) extern bool calclight_canceled; extern volatile bool check_calclight_progress; extern void check_calclight_canceled(); extern int lightmapping; sauerbraten-0.0.20130203.dfsg/engine/engine.h0000644000175000017500000005654212077450335020302 0ustar vincentvincent#ifndef __ENGINE_H__ #define __ENGINE_H__ #include "cube.h" #include "world.h" #ifndef STANDALONE #include "octa.h" #include "lightmap.h" #include "bih.h" #include "texture.h" #include "model.h" // GL_ARB_multitexture extern PFNGLACTIVETEXTUREARBPROC glActiveTexture_; extern PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTexture_; extern PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2f_; extern PFNGLMULTITEXCOORD3FARBPROC glMultiTexCoord3f_; extern PFNGLMULTITEXCOORD4FARBPROC glMultiTexCoord4f_; // GL_ARB_vertex_buffer_object extern PFNGLGENBUFFERSARBPROC glGenBuffers_; extern PFNGLBINDBUFFERARBPROC glBindBuffer_; extern PFNGLMAPBUFFERARBPROC glMapBuffer_; extern PFNGLUNMAPBUFFERARBPROC glUnmapBuffer_; extern PFNGLBUFFERDATAARBPROC glBufferData_; extern PFNGLBUFFERSUBDATAARBPROC glBufferSubData_; extern PFNGLDELETEBUFFERSARBPROC glDeleteBuffers_; extern PFNGLGETBUFFERSUBDATAARBPROC glGetBufferSubData_; // GL_ARB_occlusion_query extern PFNGLGENQUERIESARBPROC glGenQueries_; extern PFNGLDELETEQUERIESARBPROC glDeleteQueries_; extern PFNGLBEGINQUERYARBPROC glBeginQuery_; extern PFNGLENDQUERYARBPROC glEndQuery_; extern PFNGLGETQUERYIVARBPROC glGetQueryiv_; extern PFNGLGETQUERYOBJECTIVARBPROC glGetQueryObjectiv_; extern PFNGLGETQUERYOBJECTUIVARBPROC glGetQueryObjectuiv_; // GL_EXT_framebuffer_object extern PFNGLBINDRENDERBUFFEREXTPROC glBindRenderbuffer_; extern PFNGLDELETERENDERBUFFERSEXTPROC glDeleteRenderbuffers_; extern PFNGLGENFRAMEBUFFERSEXTPROC glGenRenderbuffers_; extern PFNGLRENDERBUFFERSTORAGEEXTPROC glRenderbufferStorage_; extern PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatus_; extern PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebuffer_; extern PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffers_; extern PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffers_; extern PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2D_; extern PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbuffer_; extern PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmap_; // GL_EXT_framebuffer_blit #ifndef GL_EXT_framebuffer_blit #define GL_READ_FRAMEBUFFER_EXT 0x8CA8 #define GL_DRAW_FRAMEBUFFER_EXT 0x8CA9 #define GL_DRAW_FRAMEBUFFER_BINDING_EXT 0x8CA6 #define GL_READ_FRAMEBUFFER_BINDING_EXT 0x8CAA typedef void (APIENTRYP PFNGLBLITFRAMEBUFFEREXTPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); #endif extern PFNGLBLITFRAMEBUFFEREXTPROC glBlitFramebuffer_; // GL_EXT_draw_range_elements extern PFNGLDRAWRANGEELEMENTSEXTPROC glDrawRangeElements_; // GL_EXT_blend_minmax extern PFNGLBLENDEQUATIONEXTPROC glBlendEquation_; // GL_EXT_blend_color extern PFNGLBLENDCOLOREXTPROC glBlendColor_; // GL_EXT_multi_draw_arrays extern PFNGLMULTIDRAWARRAYSEXTPROC glMultiDrawArrays_; extern PFNGLMULTIDRAWELEMENTSEXTPROC glMultiDrawElements_; // GL_EXT_packed_depth_stencil #ifndef GL_DEPTH_STENCIL_EXT #define GL_DEPTH_STENCIL_EXT 0x84F9 #endif #ifndef GL_DEPTH24_STENCIL8_EXT #define GL_DEPTH24_STENCIL8_EXT 0x88F0 #endif // GL_ARB_texture_compression extern PFNGLCOMPRESSEDTEXIMAGE3DARBPROC glCompressedTexImage3D_; extern PFNGLCOMPRESSEDTEXIMAGE2DARBPROC glCompressedTexImage2D_; extern PFNGLCOMPRESSEDTEXIMAGE1DARBPROC glCompressedTexImage1D_; extern PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC glCompressedTexSubImage3D_; extern PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC glCompressedTexSubImage2D_; extern PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC glCompressedTexSubImage1D_; extern PFNGLGETCOMPRESSEDTEXIMAGEARBPROC glGetCompressedTexImage_; // GL_EXT_fog_coord extern PFNGLFOGCOORDPOINTEREXTPROC glFogCoordPointer_; // GL_ARB_map_buffer_range #ifndef GL_ARB_map_buffer_range #define GL_MAP_READ_BIT 0x0001 #define GL_MAP_WRITE_BIT 0x0002 #define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 #define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 #define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 #define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length); #endif extern PFNGLMAPBUFFERRANGEPROC glMapBufferRange_; extern PFNGLFLUSHMAPPEDBUFFERRANGEPROC glFlushMappedBufferRange_; #include "varray.h" extern dynent *player; extern physent *camera1; // special ent that acts as camera, same object as player1 in FPS mode extern int worldscale, worldsize; extern int mapversion; extern char *maptitle; extern vector texmru; extern int xtraverts, xtravertsva; extern const ivec cubecoords[8]; extern const ivec facecoords[6][4]; extern const uchar fv[6][4]; extern const uchar fvmasks[64]; extern const uchar faceedgesidx[6][4]; extern bool inbetweenframes, renderedframe; extern SDL_Surface *screen; extern int zpass, glowpass; extern vector entgroup; // rendertext struct font { struct charinfo { short x, y, w, h, offsetx, offsety, advance, tex; }; char *name; vector texs; vector chars; int charoffset, defaultw, defaulth, scale; font() : name(NULL) {} ~font() { DELETEA(name); } }; #define FONTH (curfont->scale) #define FONTW (FONTH/2) #define MINRESW 640 #define MINRESH 480 extern font *curfont; // texture extern int hwtexsize, hwcubetexsize, hwmaxaniso, maxtexsize; extern Texture *textureload(const char *name, int clamp = 0, bool mipit = true, bool msg = true); extern int texalign(void *data, int w, int bpp); extern void cleanuptexture(Texture *t); extern void loadalphamask(Texture *t); extern void loadlayermasks(); extern Texture *cubemapload(const char *name, bool mipit = true, bool msg = true, bool transient = false); extern void drawcubemap(int size, const vec &o, float yaw, float pitch, const cubemapside &side); extern void loadshaders(); extern void setuptexparameters(int tnum, void *pixels, int clamp, int filter, GLenum format = GL_RGB, GLenum target = GL_TEXTURE_2D); extern void createtexture(int tnum, int w, int h, void *pixels, int clamp, int filter, GLenum component = GL_RGB, GLenum target = GL_TEXTURE_2D, int pw = 0, int ph = 0, int pitch = 0, bool resize = true, GLenum format = GL_FALSE); extern void blurtexture(int n, int bpp, int w, int h, uchar *dst, const uchar *src, int margin = 0); extern void blurnormals(int n, int w, int h, bvec *dst, const bvec *src, int margin = 0); extern void renderpostfx(); extern void initenvmaps(); extern void genenvmaps(); extern ushort closestenvmap(const vec &o); extern ushort closestenvmap(int orient, int x, int y, int z, int size); extern GLuint lookupenvmap(ushort emid); extern GLuint lookupenvmap(Slot &slot); extern bool reloadtexture(Texture &tex); extern bool reloadtexture(const char *name); extern void setuptexcompress(); extern void clearslots(); extern void compacteditvslots(); extern void compactmruvslots(); extern void compactvslots(cube *c, int n = 8); extern void compactvslot(int &index); extern int compactvslots(); // shadowmap extern int shadowmap, shadowmapcasters; extern bool shadowmapping; extern bool isshadowmapcaster(const vec &o, float rad); extern bool addshadowmapcaster(const vec &o, float xyrad, float zrad); extern bool isshadowmapreceiver(vtxarray *va); extern void rendershadowmap(); extern void pushshadowmap(); extern void popshadowmap(); extern void rendershadowmapreceivers(); extern void guessshadowdir(); // pvs extern void clearpvs(); extern bool pvsoccluded(const ivec &bborigin, const ivec &bbsize); extern bool waterpvsoccluded(int height); extern void setviewcell(const vec &p); extern void savepvs(stream *f); extern void loadpvs(stream *f, int numpvs); extern int getnumviewcells(); static inline bool pvsoccluded(const ivec &bborigin, int size) { return pvsoccluded(bborigin, ivec(size, size, size)); } // rendergl extern bool hasVBO, hasDRE, hasOQ, hasTR, hasFBO, hasDS, hasTF, hasBE, hasBC, hasCM, hasNP2, hasTC, hasS3TC, hasFXT1, hasTE, hasMT, hasD3, hasAF, hasVP2, hasVP3, hasPP, hasMDA, hasTE3, hasTE4, hasVP, hasFP, hasGLSL, hasGM, hasNVFB, hasSGIDT, hasSGISH, hasDT, hasSH, hasNVPCF, hasRN, hasPBO, hasFBB, hasUBO, hasBUE, hasMBR, hasFC, hasTEX; extern int hasstencil; extern int glversion, glslversion; extern float curfov, fovy, aspect, forceaspect; extern bool envmapping, minimapping, renderedgame, modelpreviewing; extern const glmatrixf viewmatrix; extern glmatrixf mvmatrix, projmatrix, mvpmatrix, invmvmatrix, invmvpmatrix, fogmatrix, invfogmatrix, envmatrix; extern bvec fogcolor; extern void gl_checkextensions(); extern void gl_init(int w, int h, int bpp, int depth, int fsaa); extern void cleangl(); extern void rendergame(bool mainpass = false); extern void invalidatepostfx(); extern void gl_drawframe(int w, int h); extern void gl_drawmainmenu(int w, int h); extern void drawminimap(); extern void drawtextures(); extern void enablepolygonoffset(GLenum type); extern void disablepolygonoffset(GLenum type); extern void calcspherescissor(const vec ¢er, float size, float &sx1, float &sy1, float &sx2, float &sy2); extern int pushscissor(float sx1, float sy1, float sx2, float sy2); extern void popscissor(); extern void recomputecamera(); extern void findorientation(); extern void writecrosshairs(stream *f); namespace modelpreview { extern void start(bool background = true); extern void end(); } // renderextras extern void render3dbox(vec &o, float tofloor, float toceil, float xradius, float yradius = 0); // octa extern cube *newcubes(uint face = F_EMPTY, int mat = MAT_AIR); extern cubeext *growcubeext(cubeext *ext, int maxverts); extern void setcubeext(cube &c, cubeext *ext); extern cubeext *newcubeext(cube &c, int maxverts = 0, bool init = true); extern void getcubevector(cube &c, int d, int x, int y, int z, ivec &p); extern void setcubevector(cube &c, int d, int x, int y, int z, const ivec &p); extern int familysize(const cube &c); extern void freeocta(cube *c); extern void discardchildren(cube &c, bool fixtex = false, int depth = 0); extern void optiface(uchar *p, cube &c); extern void validatec(cube *c, int size = 0); extern bool isvalidcube(const cube &c); extern ivec lu; extern int lusize; extern cube &lookupcube(int tx, int ty, int tz, int tsize = 0, ivec &ro = lu, int &rsize = lusize); extern const cube *neighbourstack[32]; extern int neighbourdepth; extern const cube &neighbourcube(const cube &c, int orient, int x, int y, int z, int size, ivec &ro = lu, int &rsize = lusize); extern void resetclipplanes(); extern int getmippedtexture(const cube &p, int orient); extern void forcemip(cube &c, bool fixtex = true); extern bool subdividecube(cube &c, bool fullcheck=true, bool brighten=true); extern void edgespan2vectorcube(cube &c); extern int faceconvexity(const ivec v[4]); extern int faceconvexity(const ivec v[4], int &vis); extern int faceconvexity(const vertinfo *verts, int numverts, int size); extern int faceconvexity(const cube &c, int orient); extern void calcvert(const cube &c, int x, int y, int z, int size, ivec &vert, int i, bool solid = false); extern void calcvert(const cube &c, int x, int y, int z, int size, vec &vert, int i, bool solid = false); extern uint faceedges(const cube &c, int orient); extern bool collapsedface(const cube &c, int orient); extern bool touchingface(const cube &c, int orient); extern bool flataxisface(const cube &c, int orient); extern bool collideface(const cube &c, int orient); extern int genclipplane(const cube &c, int i, vec *v, plane *clip); extern void genclipplanes(const cube &c, int x, int y, int z, int size, clipplanes &p, bool collide = true); extern bool visibleface(const cube &c, int orient, int x, int y, int z, int size, ushort mat = MAT_AIR, ushort nmat = MAT_AIR, ushort matmask = MATF_VOLUME); extern int classifyface(const cube &c, int orient, int x, int y, int z, int size); extern int visibletris(const cube &c, int orient, int x, int y, int z, int size, ushort nmat = MAT_ALPHA, ushort matmask = MAT_ALPHA); extern int visibleorient(const cube &c, int orient); extern void genfaceverts(const cube &c, int orient, ivec v[4]); extern int calcmergedsize(int orient, const ivec &co, int size, const vertinfo *verts, int numverts); extern void invalidatemerges(cube &c, const ivec &co, int size, bool msg); extern void calcmerges(); extern int mergefaces(int orient, facebounds *m, int sz); extern void mincubeface(const cube &cu, int orient, const ivec &o, int size, const facebounds &orig, facebounds &cf, ushort nmat = MAT_AIR, ushort matmask = MATF_VOLUME); static inline uchar octantrectangleoverlap(const ivec &c, int size, const ivec &o, const ivec &s) { uchar p = 0xFF; // bitmask of possible collisions with octants. 0 bit = 0 octant, etc ivec v(c); v.add(size); if(v.z <= o.z) p &= 0xF0; // not in a -ve Z octant else if(v.z >= o.z+s.z) p &= 0x0F; // not in a +ve Z octant if(v.y <= o.y) p &= 0xCC; // not in a -ve Y octant else if(v.y >= o.y+s.y) p &= 0x33; // etc.. if(v.x <= o.x) p &= 0xAA; else if(v.x >= o.x+s.x) p &= 0x55; return p; } static inline cubeext &ext(cube &c) { return *(c.ext ? c.ext : newcubeext(c)); } // ents extern char *entname(entity &e); extern bool haveselent(); extern undoblock *copyundoents(undoblock *u); extern void pasteundoents(undoblock *u); // octaedit extern void cancelsel(); extern void rendertexturepanel(int w, int h); extern void addundo(undoblock *u); extern void commitchanges(bool force = false); extern void rendereditcursor(); extern void tryedit(); // octarender extern vector tjoints; extern ushort encodenormal(const vec &n); extern vec decodenormal(ushort norm); extern void reduceslope(ivec &n); extern void findtjoints(); extern void octarender(); extern void allchanged(bool load = false); extern void clearvas(cube *c); extern vtxarray *newva(int x, int y, int z, int size); extern void destroyva(vtxarray *va, bool reparent = true); extern bool readva(vtxarray *va, ushort *&edata, uchar *&vdata); extern void updatevabb(vtxarray *va, bool force = false); extern void updatevabbs(bool force = false); // renderva extern void visiblecubes(bool cull = true); extern void setvfcP(float z = -1, const vec &bbmin = vec(-1, -1, -1), const vec &bbmax = vec(1, 1, 1)); extern void savevfcP(); extern void restorevfcP(); extern void rendergeom(float causticspass = 0, bool fogpass = false); extern void renderalphageom(bool fogpass = false); extern void rendermapmodels(); extern void renderreflectedgeom(bool causticspass = false, bool fogpass = false); extern void renderreflectedmapmodels(); extern void renderoutline(); extern bool rendersky(bool explicitonly = false); extern bool isfoggedsphere(float rad, const vec &cv); extern int isvisiblesphere(float rad, const vec &cv); extern bool bboccluded(const ivec &bo, const ivec &br); extern occludequery *newquery(void *owner); extern bool checkquery(occludequery *query, bool nowait = false); extern void resetqueries(); extern int getnumqueries(); extern void drawbb(const ivec &bo, const ivec &br, const vec &camera = camera1->o); #define startquery(query) { glBeginQuery_(GL_SAMPLES_PASSED_ARB, ((occludequery *)(query))->id); } #define endquery(query) \ { \ glEndQuery_(GL_SAMPLES_PASSED_ARB); \ extern int ati_oq_bug; \ if(ati_oq_bug) glFlush(); \ } // dynlight extern void updatedynlights(); extern int finddynlights(); extern void calcdynlightmask(vtxarray *va); extern int setdynlights(vtxarray *va); extern bool getdynlight(int n, vec &o, float &radius, vec &color); // material extern int showmat; extern int findmaterial(const char *name); extern const char *findmaterialname(int mat); extern const char *getmaterialdesc(int mat, const char *prefix = ""); extern void genmatsurfs(const cube &c, int cx, int cy, int cz, int size, vector &matsurfs); extern void rendermatsurfs(materialsurface *matbuf, int matsurfs); extern void rendermatgrid(materialsurface *matbuf, int matsurfs); extern int optimizematsurfs(materialsurface *matbuf, int matsurfs); extern void setupmaterials(int start = 0, int len = 0); extern void rendermaterials(); extern int visiblematerial(const cube &c, int orient, int x, int y, int z, int size, ushort matmask = MATF_VOLUME); // water extern int refracting, refractfog; extern bvec refractcolor; extern bool reflecting, fading, fogging; extern float reflectz; extern int reflectdist, vertwater, waterrefract, waterreflect, waterfade, caustics, waterfallrefract; #define GETMATIDXVAR(name, var, type) \ type get##name##var(int mat) \ { \ switch(mat&MATF_INDEX) \ { \ default: case 0: return name##var; \ case 1: return name##2##var; \ case 2: return name##3##var; \ case 3: return name##4##var; \ } \ } extern const bvec &getwatercolor(int mat); extern const bvec &getwaterfallcolor(int mat); extern int getwaterfog(int mat); extern const bvec &getlavacolor(int mat); extern int getlavafog(int mat); extern const bvec &getglasscolor(int mat); extern void cleanreflections(); extern void queryreflections(); extern void drawreflections(); extern void renderwater(); extern void renderlava(const materialsurface &m, Texture *tex, float scale); extern void loadcaustics(bool force = false); extern void preloadwatershaders(bool force = false); // glare extern bool glaring; extern void drawglaretex(); extern void addglare(); // depthfx extern bool depthfxing; extern void drawdepthfxtex(); // server extern vector gameargs; extern void initserver(bool listen, bool dedicated); extern void cleanupserver(); extern void serverslice(bool dedicated, uint timeout); extern void updatetime(); extern ENetSocket connectmaster(); extern void localclienttoserver(int chan, ENetPacket *); extern void localconnect(); extern bool serveroption(char *opt); // serverbrowser extern bool resolverwait(const char *name, ENetAddress *address); extern int connectwithtimeout(ENetSocket sock, const char *hostname, const ENetAddress &address); extern void addserver(const char *name, int port = 0, const char *password = NULL, bool keep = false); extern void writeservercfg(); // client extern void localdisconnect(bool cleanup = true); extern void localservertoclient(int chan, ENetPacket *packet); extern void connectserv(const char *servername, int port, const char *serverpassword); extern void abortconnect(); extern void clientkeepalive(); // command extern hashset idents; extern int identflags; extern void clearoverrides(); extern void writecfg(const char *name = NULL); extern void checksleep(int millis); extern void clearsleep(bool clearoverrides = true); // console extern void keypress(int code, bool isdown, int cooked); extern int rendercommand(int x, int y, int w); extern int renderconsole(int w, int h, int abovehud); extern void conoutf(const char *s, ...) PRINTFARGS(1, 2); extern void conoutf(int type, const char *s, ...) PRINTFARGS(2, 3); extern void resetcomplete(); extern void complete(char *s, const char *cmdprefix); const char *getkeyname(int code); extern const char *addreleaseaction(char *s); extern void writebinds(stream *f); extern void writecompletions(stream *f); // main enum { NOT_INITING = 0, INIT_LOAD, INIT_RESET }; extern int initing, numcpus; enum { CHANGE_GFX = 1<<0, CHANGE_SOUND = 1<<1 }; extern bool initwarning(const char *desc, int level = INIT_RESET, int type = CHANGE_GFX); extern bool grabinput, minimized; extern void pushevent(const SDL_Event &e); extern bool interceptkey(int sym); extern float loadprogress; extern void renderbackground(const char *caption = NULL, Texture *mapshot = NULL, const char *mapname = NULL, const char *mapinfo = NULL, bool restore = false, bool force = false); extern void renderprogress(float bar, const char *text, GLuint tex = 0, bool background = false); extern void getfps(int &fps, int &bestdiff, int &worstdiff); extern void swapbuffers(); extern int getclockmillis(); // menu extern void menuprocess(); extern void addchange(const char *desc, int type); extern void clearchanges(int type); // physics extern void mousemove(int dx, int dy); extern bool pointincube(const clipplanes &p, const vec &v); extern bool overlapsdynent(const vec &o, float radius); extern void rotatebb(vec ¢er, vec &radius, int yaw); extern float shadowray(const vec &o, const vec &ray, float radius, int mode, extentity *t = NULL); struct ShadowRayCache; extern ShadowRayCache *newshadowraycache(); extern void freeshadowraycache(ShadowRayCache *&cache); extern void resetshadowraycache(ShadowRayCache *cache); extern float shadowray(ShadowRayCache *cache, const vec &o, const vec &ray, float radius, int mode, extentity *t = NULL); // world extern vector outsideents; extern void entcancel(); extern void entitiesinoctanodes(); extern void attachentities(); extern void freeoctaentities(cube &c); extern bool pointinsel(selinfo &sel, vec &o); extern void resetmap(); extern void startmap(const char *name); // rendermodel struct mapmodelinfo { string name; model *m; }; extern void findanims(const char *pattern, vector &anims); extern void loadskin(const char *dir, const char *altdir, Texture *&skin, Texture *&masks); extern mapmodelinfo *getmminfo(int i); extern void startmodelquery(occludequery *query); extern void endmodelquery(); extern void preloadmodelshaders(); extern void preloadusedmapmodels(bool msg = false, bool bih = false); // renderparticles extern void particleinit(); extern void clearparticles(); extern void clearparticleemitters(); extern void seedparticles(); extern void updateparticles(); extern void renderparticles(bool mainpass = false); extern bool printparticles(extentity &e, char *buf); // decal extern void initdecals(); extern void cleardecals(); extern void renderdecals(bool mainpass = false); // blob enum { BLOB_STATIC = 0, BLOB_DYNAMIC }; extern int showblobs; extern void initblobs(int type = -1); extern void resetblobs(); extern void renderblob(int type, const vec &o, float radius, float fade = 1); extern void flushblobs(); // rendersky extern int explicitsky; extern double skyarea; extern void drawskybox(int farplane, bool limited); extern bool limitsky(); // 3dgui extern void g3d_render(); extern bool g3d_windowhit(bool on, bool act); // menus extern int mainmenu; extern void clearmainmenu(); extern void g3d_mainmenu(); // sound extern void clearmapsounds(); extern void checkmapsounds(); extern void updatesounds(); extern void preloadmapsounds(); extern void initmumble(); extern void closemumble(); extern void updatemumble(); // grass extern void generategrass(); extern void rendergrass(); // blendmap extern int blendpaintmode; struct BlendMapCache; extern BlendMapCache *newblendmapcache(); extern void freeblendmapcache(BlendMapCache *&cache); extern bool setblendmaporigin(BlendMapCache *cache, const ivec &o, int size); extern bool hasblendmap(BlendMapCache *cache); extern uchar lookupblendmap(BlendMapCache *cache, const vec &pos); extern void resetblendmap(); extern void enlargeblendmap(); extern void shrinkblendmap(int octant); extern void optimizeblendmap(); extern void stoppaintblendmap(); extern void trypaintblendmap(); extern void renderblendbrush(GLuint tex, float x, float y, float w, float h); extern void renderblendbrush(); extern bool loadblendmap(stream *f, int info); extern void saveblendmap(stream *f); extern uchar shouldsaveblendmap(); // recorder namespace recorder { extern void stop(); extern void capture(); extern void cleanup(); } #endif #endif sauerbraten-0.0.20130203.dfsg/engine/md2.h0000644000175000017500000003666212072642735017522 0ustar vincentvincentstruct md2; static const float md2normaltable[256][3] = { { -0.525731f, 0.000000f, 0.850651f }, { -0.442863f, 0.238856f, 0.864188f }, { -0.295242f, 0.000000f, 0.955423f }, { -0.309017f, 0.500000f, 0.809017f }, { -0.162460f, 0.262866f, 0.951056f }, { 0.000000f, 0.000000f, 1.000000f }, { 0.000000f, 0.850651f, 0.525731f }, { -0.147621f, 0.716567f, 0.681718f }, { 0.147621f, 0.716567f, 0.681718f }, { 0.000000f, 0.525731f, 0.850651f }, { 0.309017f, 0.500000f, 0.809017f }, { 0.525731f, 0.000000f, 0.850651f }, { 0.295242f, 0.000000f, 0.955423f }, { 0.442863f, 0.238856f, 0.864188f }, { 0.162460f, 0.262866f, 0.951056f }, { -0.681718f, 0.147621f, 0.716567f }, { -0.809017f, 0.309017f, 0.500000f }, { -0.587785f, 0.425325f, 0.688191f }, { -0.850651f, 0.525731f, 0.000000f }, { -0.864188f, 0.442863f, 0.238856f }, { -0.716567f, 0.681718f, 0.147621f }, { -0.688191f, 0.587785f, 0.425325f }, { -0.500000f, 0.809017f, 0.309017f }, { -0.238856f, 0.864188f, 0.442863f }, { -0.425325f, 0.688191f, 0.587785f }, { -0.716567f, 0.681718f, -0.147621f }, { -0.500000f, 0.809017f, -0.309017f }, { -0.525731f, 0.850651f, 0.000000f }, { 0.000000f, 0.850651f, -0.525731f }, { -0.238856f, 0.864188f, -0.442863f }, { 0.000000f, 0.955423f, -0.295242f }, { -0.262866f, 0.951056f, -0.162460f }, { 0.000000f, 1.000000f, 0.000000f }, { 0.000000f, 0.955423f, 0.295242f }, { -0.262866f, 0.951056f, 0.162460f }, { 0.238856f, 0.864188f, 0.442863f }, { 0.262866f, 0.951056f, 0.162460f }, { 0.500000f, 0.809017f, 0.309017f }, { 0.238856f, 0.864188f, -0.442863f }, { 0.262866f, 0.951056f, -0.162460f }, { 0.500000f, 0.809017f, -0.309017f }, { 0.850651f, 0.525731f, 0.000000f }, { 0.716567f, 0.681718f, 0.147621f }, { 0.716567f, 0.681718f, -0.147621f }, { 0.525731f, 0.850651f, 0.000000f }, { 0.425325f, 0.688191f, 0.587785f }, { 0.864188f, 0.442863f, 0.238856f }, { 0.688191f, 0.587785f, 0.425325f }, { 0.809017f, 0.309017f, 0.500000f }, { 0.681718f, 0.147621f, 0.716567f }, { 0.587785f, 0.425325f, 0.688191f }, { 0.955423f, 0.295242f, 0.000000f }, { 1.000000f, 0.000000f, 0.000000f }, { 0.951056f, 0.162460f, 0.262866f }, { 0.850651f, -0.525731f, 0.000000f }, { 0.955423f, -0.295242f, 0.000000f }, { 0.864188f, -0.442863f, 0.238856f }, { 0.951056f, -0.162460f, 0.262866f }, { 0.809017f, -0.309017f, 0.500000f }, { 0.681718f, -0.147621f, 0.716567f }, { 0.850651f, 0.000000f, 0.525731f }, { 0.864188f, 0.442863f, -0.238856f }, { 0.809017f, 0.309017f, -0.500000f }, { 0.951056f, 0.162460f, -0.262866f }, { 0.525731f, 0.000000f, -0.850651f }, { 0.681718f, 0.147621f, -0.716567f }, { 0.681718f, -0.147621f, -0.716567f }, { 0.850651f, 0.000000f, -0.525731f }, { 0.809017f, -0.309017f, -0.500000f }, { 0.864188f, -0.442863f, -0.238856f }, { 0.951056f, -0.162460f, -0.262866f }, { 0.147621f, 0.716567f, -0.681718f }, { 0.309017f, 0.500000f, -0.809017f }, { 0.425325f, 0.688191f, -0.587785f }, { 0.442863f, 0.238856f, -0.864188f }, { 0.587785f, 0.425325f, -0.688191f }, { 0.688191f, 0.587785f, -0.425325f }, { -0.147621f, 0.716567f, -0.681718f }, { -0.309017f, 0.500000f, -0.809017f }, { 0.000000f, 0.525731f, -0.850651f }, { -0.525731f, 0.000000f, -0.850651f }, { -0.442863f, 0.238856f, -0.864188f }, { -0.295242f, 0.000000f, -0.955423f }, { -0.162460f, 0.262866f, -0.951056f }, { 0.000000f, 0.000000f, -1.000000f }, { 0.295242f, 0.000000f, -0.955423f }, { 0.162460f, 0.262866f, -0.951056f }, { -0.442863f, -0.238856f, -0.864188f }, { -0.309017f, -0.500000f, -0.809017f }, { -0.162460f, -0.262866f, -0.951056f }, { 0.000000f, -0.850651f, -0.525731f }, { -0.147621f, -0.716567f, -0.681718f }, { 0.147621f, -0.716567f, -0.681718f }, { 0.000000f, -0.525731f, -0.850651f }, { 0.309017f, -0.500000f, -0.809017f }, { 0.442863f, -0.238856f, -0.864188f }, { 0.162460f, -0.262866f, -0.951056f }, { 0.238856f, -0.864188f, -0.442863f }, { 0.500000f, -0.809017f, -0.309017f }, { 0.425325f, -0.688191f, -0.587785f }, { 0.716567f, -0.681718f, -0.147621f }, { 0.688191f, -0.587785f, -0.425325f }, { 0.587785f, -0.425325f, -0.688191f }, { 0.000000f, -0.955423f, -0.295242f }, { 0.000000f, -1.000000f, 0.000000f }, { 0.262866f, -0.951056f, -0.162460f }, { 0.000000f, -0.850651f, 0.525731f }, { 0.000000f, -0.955423f, 0.295242f }, { 0.238856f, -0.864188f, 0.442863f }, { 0.262866f, -0.951056f, 0.162460f }, { 0.500000f, -0.809017f, 0.309017f }, { 0.716567f, -0.681718f, 0.147621f }, { 0.525731f, -0.850651f, 0.000000f }, { -0.238856f, -0.864188f, -0.442863f }, { -0.500000f, -0.809017f, -0.309017f }, { -0.262866f, -0.951056f, -0.162460f }, { -0.850651f, -0.525731f, 0.000000f }, { -0.716567f, -0.681718f, -0.147621f }, { -0.716567f, -0.681718f, 0.147621f }, { -0.525731f, -0.850651f, 0.000000f }, { -0.500000f, -0.809017f, 0.309017f }, { -0.238856f, -0.864188f, 0.442863f }, { -0.262866f, -0.951056f, 0.162460f }, { -0.864188f, -0.442863f, 0.238856f }, { -0.809017f, -0.309017f, 0.500000f }, { -0.688191f, -0.587785f, 0.425325f }, { -0.681718f, -0.147621f, 0.716567f }, { -0.442863f, -0.238856f, 0.864188f }, { -0.587785f, -0.425325f, 0.688191f }, { -0.309017f, -0.500000f, 0.809017f }, { -0.147621f, -0.716567f, 0.681718f }, { -0.425325f, -0.688191f, 0.587785f }, { -0.162460f, -0.262866f, 0.951056f }, { 0.442863f, -0.238856f, 0.864188f }, { 0.162460f, -0.262866f, 0.951056f }, { 0.309017f, -0.500000f, 0.809017f }, { 0.147621f, -0.716567f, 0.681718f }, { 0.000000f, -0.525731f, 0.850651f }, { 0.425325f, -0.688191f, 0.587785f }, { 0.587785f, -0.425325f, 0.688191f }, { 0.688191f, -0.587785f, 0.425325f }, { -0.955423f, 0.295242f, 0.000000f }, { -0.951056f, 0.162460f, 0.262866f }, { -1.000000f, 0.000000f, 0.000000f }, { -0.850651f, 0.000000f, 0.525731f }, { -0.955423f, -0.295242f, 0.000000f }, { -0.951056f, -0.162460f, 0.262866f }, { -0.864188f, 0.442863f, -0.238856f }, { -0.951056f, 0.162460f, -0.262866f }, { -0.809017f, 0.309017f, -0.500000f }, { -0.864188f, -0.442863f, -0.238856f }, { -0.951056f, -0.162460f, -0.262866f }, { -0.809017f, -0.309017f, -0.500000f }, { -0.681718f, 0.147621f, -0.716567f }, { -0.681718f, -0.147621f, -0.716567f }, { -0.850651f, 0.000000f, -0.525731f }, { -0.688191f, 0.587785f, -0.425325f }, { -0.587785f, 0.425325f, -0.688191f }, { -0.425325f, 0.688191f, -0.587785f }, { -0.425325f, -0.688191f, -0.587785f }, { -0.587785f, -0.425325f, -0.688191f }, { -0.688191f, -0.587785f, -0.425325f } }; struct md2 : vertmodel, vertloader { struct md2_header { int magic; int version; int skinwidth, skinheight; int framesize; int numskins, numvertices, numtexcoords; int numtriangles, numglcommands, numframes; int offsetskins, offsettexcoords, offsettriangles; int offsetframes, offsetglcommands, offsetend; }; struct md2_vertex { uchar vertex[3], normalindex; }; struct md2_frame { float scale[3]; float translate[3]; char name[16]; }; md2(const char *name) : vertmodel(name) {} static const char *formatname() { return "md2"; } static bool multiparted() { return false; } static bool multimeshed() { return false; } int type() const { return MDL_MD2; } int linktype(animmodel *m) const { return LINK_COOP; } struct md2meshgroup : vertmeshgroup { void genverts(int *glcommands, vector &tcverts, vector &vindexes, vector &tris) { hashtable tchash; vector idxs; for(int *command = glcommands; (*command)!=0;) { int numvertex = *command++; bool isfan = numvertex<0; if(isfan) numvertex = -numvertex; idxs.setsize(0); loopi(numvertex) { union { int i; float f; } u, v; u.i = *command++; v.i = *command++; int vindex = *command++; ivec tckey(u.i, v.i, vindex); int *idx = tchash.access(tckey); if(!idx) { idx = &tchash[tckey]; *idx = tcverts.length(); tcvert &tc = tcverts.add(); tc.u = u.f; tc.v = v.f; vindexes.add((ushort)vindex); } idxs.add(*idx); } loopi(numvertex-2) { tri &t = tris.add(); if(isfan) { t.vert[0] = idxs[0]; t.vert[1] = idxs[i+1]; t.vert[2] = idxs[i+2]; } else loopk(3) t.vert[k] = idxs[i&1 && k ? i+(1-(k-1))+1 : i+k]; } } } bool load(const char *filename) { stream *file = openfile(filename, "rb"); if(!file) return false; md2_header header; file->read(&header, sizeof(md2_header)); lilswap(&header.magic, sizeof(md2_header)/sizeof(int)); if(header.magic!=844121161 || header.version!=8) { delete file; return false; } name = newstring(filename); numframes = header.numframes; vertmesh &m = *new vertmesh; m.group = this; meshes.add(&m); int *glcommands = new int[header.numglcommands]; file->seek(header.offsetglcommands, SEEK_SET); int numglcommands = file->read(glcommands, header.numglcommands*sizeof(int))/sizeof(int); lilswap(glcommands, numglcommands); if(numglcommands < header.numglcommands) memset(&glcommands[numglcommands], 0, (header.numglcommands-numglcommands)*sizeof(int)); vector tcgen; vector vgen; vector trigen; genverts(glcommands, tcgen, vgen,trigen); delete[] glcommands; m.numverts = tcgen.length(); m.tcverts = new tcvert[m.numverts]; memcpy(m.tcverts, tcgen.getbuf(), m.numverts*sizeof(tcvert)); m.numtris = trigen.length(); m.tris = new tri[m.numtris]; memcpy(m.tris, trigen.getbuf(), m.numtris*sizeof(tri)); m.verts = new vert[m.numverts*numframes]; md2_vertex *tmpverts = new md2_vertex[header.numvertices]; int frame_offset = header.offsetframes; vert *curvert = m.verts; loopi(header.numframes) { md2_frame frame; file->seek(frame_offset, SEEK_SET); file->read(&frame, sizeof(md2_frame)); lilswap(frame.scale, 6); file->read(tmpverts, header.numvertices*sizeof(md2_vertex)); loopj(m.numverts) { const md2_vertex &v = tmpverts[vgen[j]]; curvert->pos = vec(v.vertex[0]*frame.scale[0]+frame.translate[0], -(v.vertex[1]*frame.scale[1]+frame.translate[1]), v.vertex[2]*frame.scale[2]+frame.translate[2]); const float *norm = md2normaltable[v.normalindex]; curvert->norm = vec(norm[0], -norm[1], norm[2]); curvert++; } frame_offset += header.framesize; } delete[] tmpverts; delete file; return true; } }; struct md2part : part { void getdefaultanim(animinfo &info, int anim, uint varseed, dynent *d) { // 0 3 6 7 8 9 10 11 12 13 14 15 16 17 // D D D D D D A P I R, E J T W FO SA GS GI static const int _frame[] = { 178, 184, 190, 183, 189, 197, 46, 54, 0, 40, 162, 67, 95, 112, 72, 84, 7, 6 }; static const int _range[] = { 6, 6, 8, 1, 1, 1, 8, 4, 40, 6, 1, 1, 17, 11, 12, 11, 18, 1 }; // DE DY I F B L R H1 H2 H3 H4 H5 H6 H7 A1 A2 A3 A4 A5 A6 A7 PA J SI SW ED LA T WI LO GI GS static const int animfr[] = { 5, 2, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 8, 8, 6, 6, 6, 6, 6, 6, 6, 7, 11, 8, 9, 10, 14, 12, 13, 15, 17, 16 }; anim &= ANIM_INDEX; if((size_t)anim >= sizeof(animfr)/sizeof(animfr[0])) { info.frame = 0; info.range = 1; return; } int n = animfr[anim]; switch(anim) { case ANIM_DYING: case ANIM_DEAD: n -= varseed%3; break; case ANIM_FORWARD: case ANIM_BACKWARD: case ANIM_LEFT: case ANIM_RIGHT: case ANIM_SWIM: info.speed = 5500.0f/d->maxspeed; break; } info.frame = _frame[n]; info.range = _range[n]; } }; meshgroup *loadmeshes(const char *name, va_list args) { md2meshgroup *group = new md2meshgroup; if(!group->load(name)) { delete group; return NULL; } return group; } bool load() { if(loaded) return true; part &mdl = *new md2part; parts.add(&mdl); mdl.model = this; mdl.index = 0; const char *pname = parentdir(loadname); defformatstring(name1)("packages/models/%s/tris.md2", loadname); mdl.meshes = sharemeshes(path(name1)); if(!mdl.meshes) { defformatstring(name2)("packages/models/%s/tris.md2", pname); // try md2 in parent folder (vert sharing) mdl.meshes = sharemeshes(path(name2)); if(!mdl.meshes) return false; } Texture *tex, *masks; loadskin(loadname, pname, tex, masks); mdl.initskins(tex, masks); if(tex==notexture) conoutf("could not load model skin for %s", name1); loading = this; identflags &= ~IDF_PERSIST; defformatstring(name3)("packages/models/%s/md2.cfg", loadname); if(!execfile(name3, false)) { formatstring(name3)("packages/models/%s/md2.cfg", pname); execfile(name3, false); } identflags |= IDF_PERSIST; loading = 0; scale /= 4; translate.y = -translate.y; parts[0]->translate = translate; loopv(parts) parts[i]->meshes->shared++; return loaded = true; } }; vertcommands md2commands; sauerbraten-0.0.20130203.dfsg/engine/octa.cpp0000644000175000017500000015775312075052370020317 0ustar vincentvincent// core world management routines #include "engine.h" cube *worldroot = newcubes(F_SOLID); int allocnodes = 0; cubeext *growcubeext(cubeext *old, int maxverts) { cubeext *ext = (cubeext *)new uchar[sizeof(cubeext) + maxverts*sizeof(vertinfo)]; if(old) { ext->va = old->va; ext->ents = old->ents; ext->tjoints = old->tjoints; } else { ext->va = NULL; ext->ents = NULL; ext->tjoints = -1; } ext->maxverts = maxverts; return ext; } void setcubeext(cube &c, cubeext *ext) { cubeext *old = c.ext; if(old == ext) return; c.ext = ext; if(old) delete[] (uchar *)old; } cubeext *newcubeext(cube &c, int maxverts, bool init) { if(c.ext && c.ext->maxverts >= maxverts) return c.ext; cubeext *ext = growcubeext(c.ext, maxverts); if(init) { if(c.ext) { memcpy(ext->surfaces, c.ext->surfaces, sizeof(ext->surfaces)); memcpy(ext->verts(), c.ext->verts(), c.ext->maxverts*sizeof(vertinfo)); } else memset(ext->surfaces, 0, sizeof(ext->surfaces)); } setcubeext(c, ext); return ext; } cube *newcubes(uint face, int mat) { cube *c = new cube[8]; loopi(8) { c->children = NULL; c->ext = NULL; c->visible = 0; c->merged = 0; setfaces(*c, face); loopl(6) c->texture[l] = DEFAULT_GEOM; c->material = mat; c++; } allocnodes++; return c-8; } int familysize(const cube &c) { int size = 1; if(c.children) loopi(8) size += familysize(c.children[i]); return size; } void freeocta(cube *c) { if(!c) return; loopi(8) discardchildren(c[i]); delete[] c; allocnodes--; } void freecubeext(cube &c) { if(c.ext) { delete[] (uchar *)c.ext; c.ext = NULL; } } void discardchildren(cube &c, bool fixtex, int depth) { c.material = MAT_AIR; c.visible = 0; c.merged = 0; if(c.ext) { if(c.ext->va) destroyva(c.ext->va); c.ext->va = NULL; c.ext->tjoints = -1; freeoctaentities(c); freecubeext(c); } if(c.children) { uint filled = F_EMPTY; loopi(8) { discardchildren(c.children[i], fixtex, depth+1); filled |= c.children[i].faces[0]; } if(fixtex) { loopi(6) c.texture[i] = getmippedtexture(c, i); if(depth > 0 && filled != F_EMPTY) c.faces[0] = F_SOLID; } DELETEA(c.children); allocnodes--; } } void getcubevector(cube &c, int d, int x, int y, int z, ivec &p) { ivec v(d, x, y, z); loopi(3) p[i] = edgeget(cubeedge(c, i, v[R[i]], v[C[i]]), v[D[i]]); } void setcubevector(cube &c, int d, int x, int y, int z, const ivec &p) { ivec v(d, x, y, z); loopi(3) edgeset(cubeedge(c, i, v[R[i]], v[C[i]]), v[D[i]], p[i]); } static inline void getcubevector(cube &c, int i, ivec &p) { p.x = edgeget(cubeedge(c, 0, (i>>R[0])&1, (i>>C[0])&1), (i>>D[0])&1); p.y = edgeget(cubeedge(c, 1, (i>>R[1])&1, (i>>C[1])&1), (i>>D[1])&1); p.z = edgeget(cubeedge(c, 2, (i>>R[2])&1, (i>>C[2])&1), (i>>D[2])&1); } static inline void setcubevector(cube &c, int i, const ivec &p) { edgeset(cubeedge(c, 0, (i>>R[0])&1, (i>>C[0])&1), (i>>D[0])&1, p.x); edgeset(cubeedge(c, 1, (i>>R[1])&1, (i>>C[1])&1), (i>>D[1])&1, p.y); edgeset(cubeedge(c, 2, (i>>R[2])&1, (i>>C[2])&1), (i>>D[2])&1, p.z); } void optiface(uchar *p, cube &c) { uint f = *(uint *)p; if(((f>>4)&0x0F0F0F0FU) == (f&0x0F0F0F0FU)) emptyfaces(c); } void printcube() { cube &c = lookupcube(lu.x, lu.y, lu.z); // assume this is cube being pointed at conoutf(CON_DEBUG, "= %p = (%d, %d, %d) @ %d", (void *)&c, lu.x, lu.y, lu.z, lusize); conoutf(CON_DEBUG, " x %.8x", c.faces[0]); conoutf(CON_DEBUG, " y %.8x", c.faces[1]); conoutf(CON_DEBUG, " z %.8x", c.faces[2]); } COMMAND(printcube, ""); bool isvalidcube(const cube &c) { clipplanes p; genclipplanes(c, 0, 0, 0, 256, p); loopi(8) // test that cube is convex { vec v; calcvert(c, 0, 0, 0, 256, v, i); if(!pointincube(p, v)) return false; } return true; } void validatec(cube *c, int size) { loopi(8) { if(c[i].children) { if(size<=1) { solidfaces(c[i]); discardchildren(c[i], true); } else validatec(c[i].children, size>>1); } else if(size > 0x1000) { subdividecube(c[i], true, false); validatec(c[i].children, size>>1); } else { loopj(3) { uint f = c[i].faces[j], e0 = f&0x0F0F0F0FU, e1 = (f>>4)&0x0F0F0F0FU; if(e0 == e1 || ((e1+0x07070707U)|(e1-e0))&0xF0F0F0F0U) { emptyfaces(c[i]); break; } } } } } ivec lu; int lusize; cube &lookupcube(int tx, int ty, int tz, int tsize, ivec &ro, int &rsize) { tx = clamp(tx, 0, worldsize-1); ty = clamp(ty, 0, worldsize-1); tz = clamp(tz, 0, worldsize-1); int scale = worldscale-1, csize = abs(tsize); cube *c = &worldroot[octastep(tx, ty, tz, scale)]; if(!(csize>>scale)) do { if(!c->children) { if(tsize > 0) do { subdividecube(*c); scale--; c = &c->children[octastep(tx, ty, tz, scale)]; } while(!(csize>>scale)); break; } scale--; c = &c->children[octastep(tx, ty, tz, scale)]; } while(!(csize>>scale)); ro = ivec(tx, ty, tz).mask(~0<children) { scale--; c = &c->children[octastep(o.x, o.y, o.z, scale)]; } return c->material; } const cube *neighbourstack[32]; int neighbourdepth = -1; const cube &neighbourcube(const cube &c, int orient, int x, int y, int z, int size, ivec &ro, int &rsize) { ivec n(x, y, z); int dim = dimension(orient); uint diff = n[dim]; if(dimcoord(orient)) n[dim] += size; else n[dim] -= size; diff ^= n[dim]; if(diff >= uint(worldsize)) { ro = n; rsize = size; return c; } int scale = worldscale; const cube *nc = worldroot; if(neighbourdepth >= 0) { scale -= neighbourdepth + 1; diff >>= scale; do { scale++; diff >>= 1; } while(diff); nc = neighbourstack[worldscale - scale]; } scale--; nc = &nc[octastep(n.x, n.y, n.z, scale)]; if(!(size>>scale) && nc->children) do { scale--; nc = &nc->children[octastep(n.x, n.y, n.z, scale)]; } while(!(size>>scale) && nc->children); ro = n.mask(~0< DEFAULT_SKY) loopi(numtexs) if(texs[i] == tex) return tex; texs[numtexs++] = tex; } loopirev(numtexs) if(!i || texs[i] > DEFAULT_SKY) return texs[i]; return DEFAULT_GEOM; } void forcemip(cube &c, bool fixtex) { cube *ch = c.children; emptyfaces(c); loopi(8) loopj(8) { int n = i^(j==3 ? 4 : (j==4 ? 3 : j)); if(!isempty(ch[n])) // breadth first search for cube near vert { ivec v; getcubevector(ch[n], i, v); // adjust vert to parent size setcubevector(c, i, ivec(n, v.x, v.y, v.z, 8).shr(1)); break; } } if(fixtex) loopj(6) c.texture[j] = getmippedtexture(c, j); } static int midedge(const ivec &a, const ivec &b, int xd, int yd, bool &perfect) { int ax = a[xd], ay = a[yd], bx = b[xd], by = b[yd]; if(ay==by) return ay; if(ax==bx) { perfect = false; return ay; } bool crossx = (ax<8 && bx>8) || (ax>8 && bx<8); bool crossy = (ay<8 && by>8) || (ay>8 && by<8); if(crossy && !crossx) { midedge(a,b,yd,xd,perfect); return 8; } // to test perfection if(ax<=8 && bx<=8) return ax>bx ? ay : by; if(ax>=8 && bx>=8) return ax16)) perfect = false; return crossy ? 8 : min(max(y, 0), 16); } static inline bool crosscenter(const ivec &a, const ivec &b, int xd, int yd) { int ax = a[xd], ay = a[yd], bx = b[xd], by = b[yd]; return (((ax <= 8 && bx <= 8) || (ax >= 8 && bx >= 8)) && ((ay <= 8 && by <= 8) || (ay >= 8 && by >= 8))) || (ax + bx == 16 && ay + by == 16); } bool subdividecube(cube &c, bool fullcheck, bool brighten) { if(c.children) return true; if(c.ext) memset(c.ext->surfaces, 0, sizeof(c.ext->surfaces)); if(isempty(c) || isentirelysolid(c)) { c.children = newcubes(isempty(c) ? F_EMPTY : F_SOLID, c.material); loopi(8) { loopl(6) c.children[i].texture[l] = c.texture[l]; if(brighten && !isempty(c)) brightencube(c.children[i]); } return true; } cube *ch = c.children = newcubes(F_SOLID, c.material); bool perfect = true; ivec v[8]; loopi(8) { getcubevector(c, i, v[i]); v[i].mul(2); } loopj(6) { int d = dimension(j), z = dimcoord(j); const ivec &v00 = v[octaindex(d, 0, 0, z)], &v10 = v[octaindex(d, 1, 0, z)], &v01 = v[octaindex(d, 0, 1, z)], &v11 = v[octaindex(d, 1, 1, z)]; int e[3][3]; // corners e[0][0] = v00[d]; e[0][2] = v01[d]; e[2][0] = v10[d]; e[2][2] = v11[d]; // edges e[0][1] = midedge(v00, v01, C[d], d, perfect); e[1][0] = midedge(v00, v10, R[d], d, perfect); e[1][2] = midedge(v11, v01, R[d], d, perfect); e[2][1] = midedge(v11, v10, C[d], d, perfect); // center bool p1 = perfect, p2 = perfect; int c1 = midedge(v00, v11, R[d], d, p1); int c2 = midedge(v01, v10, R[d], d, p2); if(z ? c1 > c2 : c1 < c2) { e[1][1] = c1; perfect = p1 && (c1 == c2 || crosscenter(v00, v11, C[d], R[d])); } else { e[1][1] = c2; perfect = p2 && (c1 == c2 || crosscenter(v01, v10, C[d], R[d])); } loopi(8) { ch[i].texture[j] = c.texture[j]; int rd = (i>>R[d])&1, cd = (i>>C[d])&1, dd = (i>>D[d])&1; edgeset(cubeedge(ch[i], d, 0, 0), z, clamp(e[rd][cd] - dd*8, 0, 8)); edgeset(cubeedge(ch[i], d, 1, 0), z, clamp(e[1+rd][cd] - dd*8, 0, 8)); edgeset(cubeedge(ch[i], d, 0, 1), z, clamp(e[rd][1+cd] - dd*8, 0, 8)); edgeset(cubeedge(ch[i], d, 1, 1), z, clamp(e[1+rd][1+cd] - dd*8, 0, 8)); } } validatec(ch); if(fullcheck) loopi(8) if(!isvalidcube(ch[i])) // not so good... { emptyfaces(ch[i]); perfect=false; } if(brighten) loopi(8) if(!isempty(ch[i])) brightencube(ch[i]); return perfect; } bool crushededge(uchar e, int dc) { return dc ? e==0 : e==0x88; } int visibleorient(const cube &c, int orient) { loopi(2) { int a = faceedgesidx[orient][i*2 + 0]; int b = faceedgesidx[orient][i*2 + 1]; loopj(2) { if(crushededge(c.edges[a],j) && crushededge(c.edges[b],j) && touchingface(c, orient)) return ((a>>2)<<1) + j; } } return orient; } VAR(mipvis, 0, 0, 1); static int remipprogress = 0, remiptotal = 0; bool remip(cube &c, int x, int y, int z, int size) { cube *ch = c.children; if(!ch) { if(size<<1 <= 0x1000) return true; subdividecube(c); ch = c.children; } else if((remipprogress++&0xFFF)==1) renderprogress(float(remipprogress)/remiptotal, "remipping..."); bool perfect = true; loopi(8) { ivec o(i, x, y, z, size); if(!remip(ch[i], o.x, o.y, o.z, size>>1)) perfect = false; } solidfaces(c); // so texmip is more consistent loopj(6) c.texture[j] = getmippedtexture(c, j); // parents get child texs regardless if(!perfect) return false; if(size<<1 > 0x1000) return false; ushort mat = MAT_AIR; loopi(8) { mat = ch[i].material; if((mat&MATF_CLIP) == MAT_NOCLIP || mat&MAT_ALPHA) { if(i > 0) return false; while(++i < 8) if(ch[i].material != mat) return false; break; } else if(!isentirelysolid(ch[i])) { while(++i < 8) { int omat = ch[i].material; if(isentirelysolid(ch[i]) ? (omat&MATF_CLIP) == MAT_NOCLIP || omat&MAT_ALPHA : mat != omat) return false; } break; } } cube n = c; n.ext = NULL; forcemip(n); n.children = NULL; if(!subdividecube(n, false, false)) { freeocta(n.children); return false; } cube *nh = n.children; uchar vis[6] = {0, 0, 0, 0, 0, 0}; loopi(8) { if(ch[i].faces[0] != nh[i].faces[0] || ch[i].faces[1] != nh[i].faces[1] || ch[i].faces[2] != nh[i].faces[2]) { freeocta(nh); return false; } if(isempty(ch[i]) && isempty(nh[i])) continue; ivec o(i, x, y, z, size); loop(orient, 6) if(visibleface(ch[i], orient, o.x, o.y, o.z, size, MAT_AIR, (mat&MAT_ALPHA)^MAT_ALPHA, MAT_ALPHA)) { if(ch[i].texture[orient] != n.texture[orient]) { freeocta(nh); return false; } vis[orient] |= 1<>1); remip(worldroot[i], o.x, o.y, o.z, worldsize>>2); } calcmerges(); if(!local) allchanged(); } void remip_() { mpremip(true); allchanged(); } COMMANDN(remip, remip_, ""); static inline int edgeval(cube &c, const ivec &p, int dim, int coord) { return edgeget(cubeedge(c, dim, p[R[dim]]>>3, p[C[dim]]>>3), coord); } void genvertp(cube &c, ivec &p1, ivec &p2, ivec &p3, plane &pl, bool solid = false) { int dim = 0; if(p1.y==p2.y && p2.y==p3.y) dim = 1; else if(p1.z==p2.z && p2.z==p3.z) dim = 2; int coord = p1[dim]; ivec v1(p1), v2(p2), v3(p3); v1[dim] = solid ? coord*8 : edgeval(c, p1, dim, coord); v2[dim] = solid ? coord*8 : edgeval(c, p2, dim, coord); v3[dim] = solid ? coord*8 : edgeval(c, p3, dim, coord); pl.toplane(v1.tovec(), v2.tovec(), v3.tovec()); } static bool threeplaneintersect(plane &pl1, plane &pl2, plane &pl3, vec &dest) { vec &t1 = dest, t2, t3, t4; t1.cross(pl1, pl2); t4 = t1; t1.mul(pl3.offset); t2.cross(pl3, pl1); t2.mul(pl2.offset); t3.cross(pl2, pl3); t3.mul(pl1.offset); t1.add(t2); t1.add(t3); t1.mul(-1); float d = t4.dot(pl3); if(d==0) return false; t1.div(d); return true; } static void genedgespanvert(ivec &p, cube &c, vec &v) { ivec p1(8-p.x, p.y, p.z); ivec p2(p.x, 8-p.y, p.z); ivec p3(p.x, p.y, 8-p.z); plane plane1, plane2, plane3; genvertp(c, p, p1, p2, plane1); genvertp(c, p, p2, p3, plane2); genvertp(c, p, p3, p1, plane3); if(plane1==plane2) genvertp(c, p, p1, p2, plane1, true); if(plane1==plane3) genvertp(c, p, p1, p2, plane1, true); if(plane2==plane3) genvertp(c, p, p2, p3, plane2, true); ASSERT(threeplaneintersect(plane1, plane2, plane3, v)); //ASSERT(v.x>=0 && v.x<=8); //ASSERT(v.y>=0 && v.y<=8); //ASSERT(v.z>=0 && v.z<=8); v.x = max(0.0f, min(8.0f, v.x)); v.y = max(0.0f, min(8.0f, v.y)); v.z = max(0.0f, min(8.0f, v.z)); } void edgespan2vectorcube(cube &c) { if(isentirelysolid(c) || isempty(c)) return; cube o = c; loop(x, 2) loop(y, 2) loop(z, 2) { ivec p(8*x, 8*y, 8*z); vec v; genedgespanvert(p, o, v); edgeset(cubeedge(c, 0, y, z), x, int(v.x+0.49f)); edgeset(cubeedge(c, 1, z, x), y, int(v.y+0.49f)); edgeset(cubeedge(c, 2, x, y), z, int(v.z+0.49f)); } } const ivec cubecoords[8] = // verts of bounding cube { #define GENCUBEVERT(n, x, y, z) ivec(x, y, z), GENCUBEVERTS(0, 8, 0, 8, 0, 8) #undef GENCUBEVERT }; template static inline void gencubevert(const cube &c, int i, T &v) { switch(i) { #define GENCUBEVERT(n, x, y, z) \ case n: \ v = T(edgeget(cubeedge(c, 0, y, z), x), \ edgeget(cubeedge(c, 1, z, x), y), \ edgeget(cubeedge(c, 2, x, y), z)); \ break; GENCUBEVERTS(0, 1, 0, 1, 0, 1) #undef GENCUBEVERT } } void genfaceverts(const cube &c, int orient, ivec v[4]) { switch(orient) { #define GENFACEORIENT(o, v0, v1, v2, v3) \ case o: v0 v1 v2 v3 break; #define GENFACEVERT(o, n, x,y,z, xv,yv,zv) \ v[n] = ivec(edgeget(cubeedge(c, 0, y, z), x), \ edgeget(cubeedge(c, 1, z, x), y), \ edgeget(cubeedge(c, 2, x, y), z)); GENFACEVERTS(0, 1, 0, 1, 0, 1, , , , , , ) #undef GENFACEORIENT #undef GENFACEVERT } } const ivec facecoords[6][4] = { #define GENFACEORIENT(o, v0, v1, v2, v3) \ { v0, v1, v2, v3 }, #define GENFACEVERT(o, n, x,y,z, xv,yv,zv) \ ivec(x,y,z) GENFACEVERTS(0, 8, 0, 8, 0, 8, , , , , , ) #undef GENFACEORIENT #undef GENFACEVERT }; const uchar fv[6][4] = // indexes for cubecoords, per each vert of a face orientation { { 2, 1, 6, 5 }, { 3, 4, 7, 0 }, { 4, 5, 6, 7 }, { 1, 2, 3, 0 }, { 6, 1, 0, 7 }, { 5, 4, 3, 2 }, }; const uchar fvmasks[64] = // mask of verts used given a mask of visible face orientations { 0x00, 0x66, 0x99, 0xFF, 0xF0, 0xF6, 0xF9, 0xFF, 0x0F, 0x6F, 0x9F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC3, 0xE7, 0xDB, 0xFF, 0xF3, 0xF7, 0xFB, 0xFF, 0xCF, 0xEF, 0xDF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3C, 0x7E, 0xBD, 0xFF, 0xFC, 0xFE, 0xFD, 0xFF, 0x3F, 0x7F, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; const uchar faceedgesidx[6][4] = // ordered edges surrounding each orient {//0..1 = row edges, 2..3 = column edges { 4, 5, 8, 10 }, { 6, 7, 9, 11 }, { 8, 9, 0, 2 }, { 10, 11, 1, 3 }, { 0, 1, 4, 6 }, { 2, 3, 5, 7 }, }; bool flataxisface(const cube &c, int orient) { uint face = c.faces[dimension(orient)]; if(dimcoord(orient)) face >>= 4; return (face&0x0F0F0F0F) == 0x01010101*(face&0x0F); } bool collideface(const cube &c, int orient) { if(flataxisface(c, orient)) { uchar r1 = c.edges[faceedgesidx[orient][0]], r2 = c.edges[faceedgesidx[orient][1]]; if(uchar((r1>>4)|(r2&0xF0)) == uchar((r1&0x0F)|(r2<<4))) return false; uchar c1 = c.edges[faceedgesidx[orient][2]], c2 = c.edges[faceedgesidx[orient][3]]; if(uchar((c1>>4)|(c2&0xF0)) == uchar((c1&0x0F)|(c2<<4))) return false; } return true; } bool touchingface(const cube &c, int orient) { uint face = c.faces[dimension(orient)]; return dimcoord(orient) ? (face&0xF0F0F0F0)==0x80808080 : (face&0x0F0F0F0F)==0; } bool notouchingface(const cube &c, int orient) { uint face = c.faces[dimension(orient)]; return dimcoord(orient) ? (face&0x80808080)==0 : ((0x88888888-face)&0x08080808) == 0; } int faceconvexity(const ivec v[4]) { ivec n; n.cross(ivec(v[1]).sub(v[0]), ivec(v[2]).sub(v[0])); return ivec(v[0]).sub(v[3]).dot(n); // 1 if convex, -1 if concave, 0 if flat } int faceconvexity(const vertinfo *verts, int numverts, int size) { if(numverts < 4) return 0; ivec v0 = verts[0].getxyz(), e1 = verts[1].getxyz().sub(v0), e2 = verts[2].getxyz().sub(v0), n; if(size >= (8<<5)) { if(size >= (8<<10)) n.cross(e1.shr(10), e2.shr(10)); else n.cross(e1, e2).shr(10); } else n.cross(e1, e2); return verts[3].getxyz().sub(v0).dot(n); } int faceconvexity(const ivec v[4], int &vis) { ivec e1, e2, e3, n; n.cross((e1 = v[1]).sub(v[0]), (e2 = v[2]).sub(v[0])); int convex = (e3 = v[0]).sub(v[3]).dot(n); if(!convex) { if(ivec().cross(e3, e2).iszero()) { if(!n.iszero()) vis = 1; } else if(n.iszero()) { vis = 2; } return 0; } return convex; } int faceconvexity(const cube &c, int orient) { if(flataxisface(c, orient)) return 0; ivec v[4]; genfaceverts(c, orient, v); return faceconvexity(v); } int faceorder(const cube &c, int orient) // gets above 'fv' so that each face is convex { return faceconvexity(c, orient)<0 ? 1 : 0; } static inline void faceedges(const cube &c, int orient, uchar edges[4]) { loopk(4) edges[k] = c.edges[faceedgesidx[orient][k]]; } uint faceedges(const cube &c, int orient) { union { uchar edges[4]; uint face; } u; faceedges(c, orient, u.edges); return u.face; } struct facevec { int x, y; facevec() {} facevec(int x, int y) : x(x), y(y) {} bool operator==(const facevec &f) const { return x == f.x && y == f.y; } bool operator!=(const facevec &f) const { return x != f.x || y != f.y; } }; static inline int genfacevecs(const cube &cu, int orient, const ivec &pos, int size, bool solid, facevec *fvecs, const ivec *v = NULL) { int i = 0; if(solid) { switch(orient) { #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: \ { \ if(dimcoord(orient)) { v0 v1 v2 v3 } else { v3 v2 v1 v0 } \ break; \ } #define GENFACEVERT(orient, vert, xv,yv,zv, x,y,z) \ { facevec &f = fvecs[i]; x ((xv)<<3); y ((yv)<<3); z ((zv)<<3); i++; } GENFACEVERTS(pos.x, pos.x+size, pos.y, pos.y+size, pos.z, pos.z+size, f.x = , f.x = , f.y = , f.y = , (void), (void)) #undef GENFACEVERT } return 4; } ivec buf[4]; if(!v) { genfaceverts(cu, orient, buf); v = buf; } facevec prev(INT_MAX, INT_MAX); switch(orient) { #define GENFACEVERT(orient, vert, sx,sy,sz, dx,dy,dz) \ { \ const ivec &e = v[vert]; \ ivec ef; \ ef.dx = e.sx; ef.dy = e.sy; ef.dz = e.sz; \ if(ef.z == dimcoord(orient)*8) \ { \ facevec &f = fvecs[i]; \ ivec pf; \ pf.dx = pos.sx; pf.dy = pos.sy; pf.dz = pos.sz; \ f = facevec(ef.x*size + (pf.x<<3), ef.y*size + (pf.y<<3)); \ if(f != prev) { prev = f; i++; } \ } \ } GENFACEVERTS(x, x, y, y, z, z, x, x, y, y, z, z) #undef GENFACEORIENT #undef GENFACEVERT } if(fvecs[0] == prev) i--; return i; } static inline int clipfacevecy(const facevec &o, const facevec &dir, int cx, int cy, int size, facevec &r) { if(dir.x >= 0) { if(cx <= o.x || cx >= o.x+dir.x) return 0; } else if(cx <= o.x+dir.x || cx >= o.x) return 0; int t = (o.y-cy) + (cx-o.x)*dir.y/dir.x; if(t <= 0 || t >= size) return 0; r.x = cx; r.y = cy + t; return 1; } static inline int clipfacevecx(const facevec &o, const facevec &dir, int cx, int cy, int size, facevec &r) { if(dir.y >= 0) { if(cy <= o.y || cy >= o.y+dir.y) return 0; } else if(cy <= o.y+dir.y || cy >= o.y) return 0; int t = (o.x-cx) + (cy-o.y)*dir.x/dir.y; if(t <= 0 || t >= size) return 0; r.x = cx + t; r.y = cy; return 1; } static inline int clipfacevec(const facevec &o, const facevec &dir, int cx, int cy, int size, facevec *rvecs) { int r = 0; if(o.x >= cx && o.x <= cx+size && o.y >= cy && o.y <= cy+size && ((o.x != cx && o.x != cx+size) || (o.y != cy && o.y != cy+size))) { rvecs[0].x = o.x; rvecs[0].y = o.y; r++; } r += clipfacevecx(o, dir, cx, cy, size, rvecs[r]); r += clipfacevecx(o, dir, cx, cy+size, size, rvecs[r]); r += clipfacevecy(o, dir, cx, cy, size, rvecs[r]); r += clipfacevecy(o, dir, cx+size, cy, size, rvecs[r]); ASSERT(r <= 2); return r; } static inline bool insideface(const facevec *p, int nump, const facevec *o, int numo) { int bounds = 0; facevec prev = o[numo-1]; loopi(numo) { const facevec &cur = o[i]; facevec dir(cur.x-prev.x, cur.y-prev.y); int offset = dir.x*prev.y - dir.y*prev.x; loopj(nump) if(dir.x*p[j].y - dir.y*p[j].x > offset) return false; bounds++; prev = cur; } return bounds>=3; } static inline int clipfacevecs(const facevec *o, int numo, int cx, int cy, int size, facevec *rvecs) { cx <<= 3; cy <<= 3; size <<= 3; int r = 0; facevec prev = o[numo-1]; loopi(numo) { const facevec &cur = o[i]; r += clipfacevec(prev, facevec(cur.x-prev.x, cur.y-prev.y), cx, cy, size, &rvecs[r]); prev = cur; } facevec corner[4] = {facevec(cx, cy), facevec(cx+size, cy), facevec(cx+size, cy+size), facevec(cx, cy+size)}; loopi(4) if(insideface(&corner[i], 1, o, numo)) rvecs[r++] = corner[i]; ASSERT(r <= 8); return r; } bool collapsedface(const cube &c, int orient) { int e0 = c.edges[faceedgesidx[orient][0]], e1 = c.edges[faceedgesidx[orient][1]], e2 = c.edges[faceedgesidx[orient][2]], e3 = c.edges[faceedgesidx[orient][3]], face = dimension(orient)*4, f0 = c.edges[face+0], f1 = c.edges[face+1], f2 = c.edges[face+2], f3 = c.edges[face+3]; if(dimcoord(orient)) { f0 >>= 4; f1 >>= 4; f2 >>= 4; f3 >>= 4; } else { f0 &= 0xF; f1 &= 0xF; f2 &= 0xF; f3 &= 0xF; } ivec v0(e0&0xF, e2&0xF, f0), v1(e0>>4, e3&0xF, f1), v2(e1>>4, e3>>4, f3), v3(e1&0xF, e2>>4, f2); return ivec().cross(v1.sub(v0), v2.sub(v0)).iszero() && ivec().cross(v2, v3.sub(v0)).iszero(); } static inline bool occludesface(const cube &c, int orient, const ivec &o, int size, const ivec &vo, int vsize, ushort vmat, ushort nmat, ushort matmask, const facevec *vf, int numv) { int dim = dimension(orient); if(!c.children) { if(nmat != MAT_AIR && (c.material&matmask) == nmat) { facevec nf[8]; return clipfacevecs(vf, numv, o[C[dim]], o[R[dim]], size, nf) < 3; } if(isentirelysolid(c)) return true; if(vmat != MAT_AIR && ((c.material&matmask) == vmat || (isliquid(vmat) && isclipped(c.material&MATF_VOLUME)))) return true; if(touchingface(c, orient) && faceedges(c, orient) == F_SOLID) return true; facevec cf[8]; int numc = clipfacevecs(vf, numv, o[C[dim]], o[R[dim]], size, cf); if(numc < 3) return true; if(isempty(c) || notouchingface(c, orient)) return false; facevec of[4]; int numo = genfacevecs(c, orient, o, size, false, of); return numo >= 3 && insideface(cf, numc, of, numo); } size >>= 1; int coord = dimcoord(orient); loopi(8) if(octacoord(dim, i) == coord) { if(!occludesface(c.children[i], orient, ivec(i, o.x, o.y, o.z, size), size, vo, vsize, vmat, nmat, matmask, vf, numv)) return false; } return true; } bool visibleface(const cube &c, int orient, int x, int y, int z, int size, ushort mat, ushort nmat, ushort matmask) { if(mat != MAT_AIR) { if(faceedges(c, orient)==F_SOLID && touchingface(c, orient)) return false; } else { if(collapsedface(c, orient)) return false; if(!touchingface(c, orient)) return true; } ivec no; int nsize; const cube &o = neighbourcube(c, orient, x, y, z, size, no, nsize); if(&o==&c) return false; int opp = opposite(orient); if(nsize > size || (nsize == size && !o.children)) { if(nmat != MAT_AIR && (o.material&matmask) == nmat) return true; if(isentirelysolid(o)) return false; if(mat != MAT_AIR && ((o.material&matmask) == mat || (isliquid(mat) && (o.material&MATF_VOLUME) == MAT_GLASS))) return false; if(isempty(o) || notouchingface(o, opp)) return true; if(touchingface(o, opp) && faceedges(o, opp) == F_SOLID) return false; ivec vo(x, y, z); vo.mask(0xFFF); no.mask(0xFFF); facevec cf[4], of[4]; int numc = genfacevecs(c, orient, vo, size, mat != MAT_AIR, cf), numo = genfacevecs(o, opp, no, nsize, false, of); return numo < 3 || !insideface(cf, numc, of, numo); } ivec vo(x, y, z); vo.mask(0xFFF); no.mask(0xFFF); facevec cf[4]; int numc = genfacevecs(c, orient, vo, size, mat != MAT_AIR, cf); return !occludesface(o, opp, no, nsize, vo, size, mat, nmat, matmask, cf, numc); } int classifyface(const cube &c, int orient, int x, int y, int z, int size) { if(collapsedface(c, orient)) return 0; int vismask = (c.material&MATF_CLIP) == MAT_NOCLIP ? 1 : 3; if(!touchingface(c, orient)) return vismask; ivec no; int nsize; const cube &o = neighbourcube(c, orient, x, y, z, size, no, nsize); if(&o==&c) return 0; int vis = 0, opp = opposite(orient); if(nsize > size || (nsize == size && !o.children)) { if((~c.material & o.material) & MAT_ALPHA) vis |= 1; if((o.material&MATF_CLIP) == MAT_NOCLIP) vis |= vismask&2; if(vis == vismask || isentirelysolid(o)) return vis; if(isempty(o) || notouchingface(o, opp)) return vismask; if(touchingface(o, opp) && faceedges(o, opp) == F_SOLID) return vis; ivec vo(x, y, z); vo.mask(0xFFF); no.mask(0xFFF); facevec cf[4], of[4]; int numc = genfacevecs(c, orient, vo, size, false, cf), numo = genfacevecs(o, opp, no, nsize, false, of); if(numo < 3 || !insideface(cf, numc, of, numo)) return vismask; return vis; } ivec vo(x, y, z); vo.mask(0xFFF); no.mask(0xFFF); facevec cf[4]; int numc = genfacevecs(c, orient, vo, size, false, cf); if(!occludesface(o, opp, no, nsize, vo, size, MAT_AIR, (c.material&MAT_ALPHA)^MAT_ALPHA, MAT_ALPHA, cf, numc)) vis |= 1; if(vismask&2 && !occludesface(o, opp, no, nsize, vo, size, MAT_AIR, MAT_NOCLIP, MATF_CLIP, cf, numc)) vis |= 2; return vis; } // more expensive version that checks both triangles of a face independently int visibletris(const cube &c, int orient, int x, int y, int z, int size, ushort nmat, ushort matmask) { int vis = 3, touching = 0xF; ivec v[4], e1, e2, e3, n; genfaceverts(c, orient, v); n.cross((e1 = v[1]).sub(v[0]), (e2 = v[2]).sub(v[0])); int convex = (e3 = v[0]).sub(v[3]).dot(n); if(!convex) { if(ivec().cross(e3, e2).iszero()) { if(n.iszero()) return 0; vis = 1; touching = 0xF&~(1<<3); } else if(n.iszero()) { vis = 2; touching = 0xF&~(1<<1); } } int dim = dimension(orient), coord = dimcoord(orient); if(v[0][dim] != coord*8) touching &= ~(1<<0); if(v[1][dim] != coord*8) touching &= ~(1<<1); if(v[2][dim] != coord*8) touching &= ~(1<<2); if(v[3][dim] != coord*8) touching &= ~(1<<3); static const int notouchmasks[2][16] = // mask of triangles not touching { // order 0: flat or convex // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 { 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 1, 3, 0 }, // order 1: concave { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 2, 0 }, }; int order = convex < 0 ? 1 : 0, notouch = notouchmasks[order][touching]; if((vis¬ouch)==vis) return vis; ivec no; int nsize; const cube &o = neighbourcube(c, orient, x, y, z, size, no, nsize); if(&o==&c) return 0; if((c.material&matmask) == nmat) nmat = MAT_AIR; ivec vo(x, y, z); vo.mask(0xFFF); no.mask(0xFFF); facevec cf[4], of[4]; int opp = opposite(orient), numo = 0, numc; if(nsize > size || (nsize == size && !o.children)) { if(isempty(o) || notouchingface(o, opp)) return vis; if(nmat != MAT_AIR && (o.material&matmask) == nmat) return vis; if(isentirelysolid(o) || (touchingface(o, opp) && faceedges(o, opp) == F_SOLID)) return vis¬ouch; numc = genfacevecs(c, orient, vo, size, false, cf, v); numo = genfacevecs(o, opp, no, nsize, false, of); if(numo < 3) return vis; if(insideface(cf, numc, of, numo)) return vis¬ouch; } else { numc = genfacevecs(c, orient, vo, size, false, cf, v); if(occludesface(o, opp, no, nsize, vo, size, MAT_AIR, nmat, matmask, cf, numc)) return vis¬ouch; } if(vis != 3 || notouch) return vis; static const int triverts[2][2][2][3] = { // order { // coord { { 1, 2, 3 }, { 0, 1, 3 } }, // verts { { 0, 1, 2 }, { 0, 2, 3 } } }, { // coord { { 0, 1, 2 }, { 3, 0, 2 } }, // verts { { 1, 2, 3 }, { 1, 3, 0 } } } }; do { loopi(2) { const int *verts = triverts[order][coord][i]; facevec tf[3] = { cf[verts[0]], cf[verts[1]], cf[verts[2]] }; if(numo > 0) { if(!insideface(tf, 3, of, numo)) continue; } else if(!occludesface(o, opp, no, nsize, vo, size, MAT_AIR, nmat, matmask, tf, 3)) continue; return vis & ~(1<=8) v.mul(size/8); else v.div(8/size); v.add(ivec(x, y, z).shl(3)); } void calcvert(const cube &c, int x, int y, int z, int size, vec &v, int i, bool solid) { if(solid) v = cubecoords[i].tovec(); else gencubevert(c, i, v); v.mul(size/8.0f).add(vec(x, y, z)); } int genclipplane(const cube &c, int orient, vec *v, plane *clip) { int planes = 0, convex = faceconvexity(c, orient), order = convex < 0 ? 1 : 0; const vec &v0 = v[fv[orient][order]], &v1 = v[fv[orient][order+1]], &v2 = v[fv[orient][order+2]], &v3 = v[fv[orient][(order+3)&3]]; if(v0==v2) return 0; if(v0!=v1 && v1!=v2) clip[planes++].toplane(v0, v1, v2); if(v0!=v3 && v2!=v3 && (!planes || convex)) clip[planes++].toplane(v0, v2, v3); return planes; } void genclipplanes(const cube &c, int x, int y, int z, int size, clipplanes &p, bool collide) { // generate tight bounding box calcvert(c, x, y, z, size, p.v[0], 0); vec mx = p.v[0], mn = p.v[0]; for(int i = 1; i < 8; i++) { calcvert(c, x, y, z, size, p.v[i], i); mx.max(p.v[i]); mn.min(p.v[i]); } p.r = mx.sub(mn).mul(0.5f); p.o = mn.add(p.r); p.size = 0; p.visible = 0; if(collide || (c.visible&0xC0) == 0x40) { loopi(6) if(c.visible&(1< y.v2) return false; if(x.u1 < y.u1) return true; if(x.u1 > y.u1) return false; return false; } static int mergefacev(int orient, facebounds *m, int sz, facebounds &n) { for(int i = sz-1; i >= 0; --i) { if(m[i].v2 < n.v1) break; if(m[i].v2 == n.v1 && m[i].u1 == n.u1 && m[i].u2 == n.u2) { n.v1 = m[i].v1; memmove(&m[i], &m[i+1], (sz - (i+1)) * sizeof(facebounds)); return 1; } } return 0; } static int mergefaceu(int orient, facebounds &m, facebounds &n) { if(m.v1 == n.v1 && m.v2 == n.v2 && m.u2 == n.u1) { n.u1 = m.u1; return 1; } return 0; } static int mergeface(int orient, facebounds *m, int sz, facebounds &n) { for(bool merged = false; sz; merged = true) { int vmerged = mergefacev(orient, m, sz, n); sz -= vmerged; if(!vmerged && merged) break; if(!sz) break; int umerged = mergefaceu(orient, m[sz-1], n); sz -= umerged; if(!umerged) break; } m[sz++] = n; return sz; } int mergefaces(int orient, facebounds *m, int sz) { quicksort(m, sz, mergefacecmp); int nsz = 0; loopi(sz) nsz = mergeface(orient, m, nsz, m[i]); return nsz; } struct cfkey { uchar orient; ushort material, tex; ivec n; int offset; }; static inline bool htcmp(const cfkey &x, const cfkey &y) { return x.orient == y.orient && x.tex == y.tex && x.n == y.n && x.offset == y.offset && x.material==y.material; } static inline uint hthash(const cfkey &k) { return hthash(k.n)^k.offset^k.tex^k.orient^k.material; } void mincubeface(const cube &cu, int orient, const ivec &o, int size, const facebounds &orig, facebounds &cf, ushort nmat, ushort matmask) { int dim = dimension(orient); if(cu.children) { size >>= 1; int coord = dimcoord(orient); loopi(8) if(octacoord(dim, i) == coord) mincubeface(cu.children[i], orient, ivec(i, o.x, o.y, o.z, size), size, orig, cf, nmat, matmask); return; } int c = C[dim], r = R[dim]; ushort uco = (o[c]&0xFFF)<<3, vco = (o[r]&0xFFF)<<3; ushort uc1 = uco, vc1 = vco, uc2 = ushort(size<<3)+uco, vc2 = ushort(size<<3)+vco; uc1 = max(uc1, orig.u1); uc2 = min(uc2, orig.u2); vc1 = max(vc1, orig.v1); vc2 = min(vc2, orig.v2); if(!isempty(cu) && touchingface(cu, orient) && !(nmat!=MAT_AIR && (cu.material&matmask)==nmat)) { uchar r1 = cu.edges[faceedgesidx[orient][0]], r2 = cu.edges[faceedgesidx[orient][1]], c1 = cu.edges[faceedgesidx[orient][2]], c2 = cu.edges[faceedgesidx[orient][3]]; ushort u1 = max(c1&0xF, c2&0xF)*size+uco, u2 = min(c1>>4, c2>>4)*size+uco, v1 = max(r1&0xF, r2&0xF)*size+vco, v2 = min(r1>>4, r2>>4)*size+vco; u1 = max(u1, orig.u1); u2 = min(u2, orig.u2); v1 = max(v1, orig.v1); v2 = min(v2, orig.v2); if(v2-v1==vc2-vc1) { if(u2-u1==uc2-uc1) return; if(u1==uc1) uc1 = u2; if(u2==uc2) uc2 = u1; } else if(u2-u1==uc2-uc1) { if(v1==vc1) vc1 = v2; if(v2==vc2) vc2 = v1; } } if(uc1==uc2 || vc1==vc2) return; cf.u1 = min(cf.u1, uc1); cf.u2 = max(cf.u2, uc2); cf.v1 = min(cf.v1, vc1); cf.v2 = max(cf.v2, vc2); } bool mincubeface(const cube &cu, int orient, const ivec &co, int size, facebounds &orig) { ivec no; int nsize; const cube &nc = neighbourcube(cu, orient, co.x, co.y, co.z, size, no, nsize); facebounds mincf; mincf.u1 = orig.u2; mincf.u2 = orig.u1; mincf.v1 = orig.v2; mincf.v2 = orig.v1; mincubeface(nc, opposite(orient), no, nsize, orig, mincf, cu.material&MAT_ALPHA ? MAT_AIR : MAT_ALPHA, MAT_ALPHA); bool smaller = false; if(mincf.u1 > orig.u1) { orig.u1 = mincf.u1; smaller = true; } if(mincf.u2 < orig.u2) { orig.u2 = mincf.u2; smaller = true; } if(mincf.v1 > orig.v1) { orig.v1 = mincf.v1; smaller = true; } if(mincf.v2 < orig.v2) { orig.v2 = mincf.v2; smaller = true; } return smaller; } VAR(maxmerge, 0, 6, 12); VAR(minface, 0, 4, 12); struct pvert { ushort x, y; pvert() {} pvert(ushort x, ushort y) : x(x), y(y) {} bool operator==(const pvert &o) const { return x == o.x && y == o.y; } bool operator!=(const pvert &o) const { return x != o.x || y != o.y; } }; struct pedge { pvert from, to; pedge() {} pedge(const pvert &from, const pvert &to) : from(from), to(to) {} bool operator==(const pedge &o) const { return from == o.from && to == o.to; } bool operator!=(const pedge &o) const { return from != o.from || to != o.to; } }; static inline uint hthash(const pedge &x) { return uint(x.from.x)^(uint(x.from.y)<<8); } static inline bool htcmp(const pedge &x, const pedge &y) { return x == y; } struct poly { cube *c; int numverts; bool merged; pvert verts[MAXFACEVERTS]; }; bool clippoly(poly &p, const facebounds &b) { pvert verts1[MAXFACEVERTS+4], verts2[MAXFACEVERTS+4]; int numverts1 = 0, numverts2 = 0, px = p.verts[p.numverts-1].x, py = p.verts[p.numverts-1].y; loopi(p.numverts) { int x = p.verts[i].x, y = p.verts[i].y; if(x < b.u1) { if(px > b.u2) verts1[numverts1++] = pvert(b.u2, y + ((y - py)*(b.u2 - x))/(x - px)); if(px > b.u1) verts1[numverts1++] = pvert(b.u1, y + ((y - py)*(b.u1 - x))/(x - px)); } else if(x > b.u2) { if(px < b.u1) verts1[numverts1++] = pvert(b.u1, y + ((y - py)*(b.u1 - x))/(x - px)); if(px < b.u2) verts1[numverts1++] = pvert(b.u2, y + ((y - py)*(b.u2 - x))/(x - px)); } else { if(px < b.u1) { if(x > b.u1) verts1[numverts1++] = pvert(b.u1, y + ((y - py)*(b.u1 - x))/(x - px)); } else if(px > b.u2 && x < b.u2) verts1[numverts1++] = pvert(b.u2, y + ((y - py)*(b.u2 - x))/(x - px)); verts1[numverts1++] = pvert(x, y); } px = x; py = y; } if(numverts1 < 3) return false; px = verts1[numverts1-1].x; py = verts1[numverts1-1].y; loopi(numverts1) { int x = verts1[i].x, y = verts1[i].y; if(y < b.v1) { if(py > b.v2) verts2[numverts2++] = pvert(x + ((x - px)*(b.v2 - y))/(y - py), b.v2); if(py > b.v1) verts2[numverts2++] = pvert(x + ((x - px)*(b.v1 - y))/(y - py), b.v1); } else if(y > b.v2) { if(py < b.v1) verts2[numverts2++] = pvert(x + ((x - px)*(b.v1 - y))/(y - py), b.v1); if(py < b.v2) verts2[numverts2++] = pvert(x + ((x - px)*(b.v2 - y))/(y - py), b.v2); } else { if(py < b.v1) { if(y > b.v1) verts2[numverts2++] = pvert(x + ((x - px)*(b.v1 - y))/(y - py), b.v1); } else if(py > b.v2 && y < b.v2) verts2[numverts2++] = pvert(x + ((x - px)*(b.v2 - y))/(y - py), b.v2); verts2[numverts2++] = pvert(x, y); } px = x; py = y; } if(numverts2 < 3) return false; if(numverts2 > MAXFACEVERTS) return false; memcpy(p.verts, verts2, numverts2*sizeof(pvert)); p.numverts = numverts2; return true; } bool genpoly(cube &cu, int orient, const ivec &o, int size, int vis, ivec &n, int &offset, poly &p) { int dim = dimension(orient), coord = dimcoord(orient); ivec v[4]; genfaceverts(cu, orient, v); if(flataxisface(cu, orient)) { n = ivec(0, 0, 0); n[dim] = coord ? 1 : -1; } else { if(faceconvexity(v)) return false; n.cross(ivec(v[1]).sub(v[0]), ivec(v[2]).sub(v[0])); if(n.iszero()) n.cross(ivec(v[2]).sub(v[0]), ivec(v[3]).sub(v[0])); reduceslope(n); } ivec po = ivec(o).mask(0xFFF).shl(3); loopk(4) v[k].mul(size).add(po); offset = -n.dot(v[3]); int r = R[dim], c = C[dim], order = vis&4 ? 1 : 0; p.numverts = 0; if(coord) { const ivec &v0 = v[order]; p.verts[p.numverts++] = pvert(v0[c], v0[r]); if(vis&1) { const ivec &v1 = v[order+1]; p.verts[p.numverts++] = pvert(v1[c], v1[r]); } const ivec &v2 = v[order+2]; p.verts[p.numverts++] = pvert(v2[c], v2[r]); if(vis&2) { const ivec &v3 = v[(order+3)&3]; p.verts[p.numverts++] = pvert(v3[c], v3[r]); } } else { if(vis&2) { const ivec &v3 = v[(order+3)&3]; p.verts[p.numverts++] = pvert(v3[c], v3[r]); } const ivec &v2 = v[order+2]; p.verts[p.numverts++] = pvert(v2[c], v2[r]); if(vis&1) { const ivec &v1 = v[order+1]; p.verts[p.numverts++] = pvert(v1[c], v1[r]); } const ivec &v0 = v[order]; p.verts[p.numverts++] = pvert(v0[c], v0[r]); } if(faceedges(cu, orient)!=F_SOLID) { int px = int(p.verts[p.numverts-2].x) - int(p.verts[p.numverts-3].x), py = int(p.verts[p.numverts-2].y) - int(p.verts[p.numverts-3].y), cx = int(p.verts[p.numverts-1].x) - int(p.verts[p.numverts-2].x), cy = int(p.verts[p.numverts-1].y) - int(p.verts[p.numverts-2].y), dir = px*cy - py*cx; if(dir > 0) return false; if(!dir) { if(p.numverts < 4) return false; p.verts[p.numverts-2] = p.verts[p.numverts-1]; p.numverts--; } px = cx; py = cy; cx = int(p.verts[0].x) - int(p.verts[p.numverts-1].x); cy = int(p.verts[0].y) - int(p.verts[p.numverts-1].y); dir = px*cy - py*cx; if(dir > 0) return false; if(!dir) { if(p.numverts < 4) return false; p.numverts--; } px = cx; py = cy; cx = int(p.verts[1].x) - int(p.verts[0].x); cy = int(p.verts[1].y) - int(p.verts[0].y); dir = px*cy - py*cx; if(dir > 0) return false; if(!dir) { if(p.numverts < 4) return false; p.verts[0] = p.verts[p.numverts-1]; p.numverts--; } px = cx; py = cy; cx = int(p.verts[2].x) - int(p.verts[1].x); cy = int(p.verts[2].y) - int(p.verts[1].y); dir = px*cy - py*cx; if(dir > 0) return false; if(!dir) { if(p.numverts < 4) return false; p.verts[1] = p.verts[2]; p.verts[2] = p.verts[3]; p.numverts--; } } p.c = &cu; p.merged = false; if(minface && size >= 1< &links, vector &queue, int owner, poly &p, poly &q, const pedge &e) { int pe = -1, qe = -1; loopi(p.numverts) if(p.verts[i] == e.from) { pe = i; break; } loopi(q.numverts) if(q.verts[i] == e.to) { qe = i; break; } if(pe < 0 || qe < 0) return false; if(p.verts[(pe+1)%p.numverts] != e.to || q.verts[(qe+1)%q.numverts] != e.from) return false; /* * c----d * | | * F----T * | P | * b----a */ pvert verts[2*MAXFACEVERTS]; int numverts = 0, index = pe+2; // starts at A = T+1, ends at F = T+p.numverts loopi(p.numverts-1) { if(index >= p.numverts) index -= p.numverts; verts[numverts++] = p.verts[index++]; } index = qe+2; // starts at C = T+2 = F+1, ends at T = T+q.numverts int px = int(verts[numverts-1].x) - int(verts[numverts-2].x), py = int(verts[numverts-1].y) - int(verts[numverts-2].y); loopi(q.numverts-1) { if(index >= q.numverts) index -= q.numverts; pvert &src = q.verts[index++]; int cx = int(src.x) - int(verts[numverts-1].x), cy = int(src.y) - int(verts[numverts-1].y), dir = px*cy - py*cx; if(dir > 0) return false; if(!dir) numverts--; verts[numverts++] = src; px = cx; py = cy; } int cx = int(verts[0].x) - int(verts[numverts-1].x), cy = int(verts[0].y) - int(verts[numverts-1].y), dir = px*cy - py*cx; if(dir > 0) return false; if(!dir) numverts--; if(numverts > MAXFACEVERTS) return false; q.merged = true; q.numverts = 0; p.merged = true; p.numverts = numverts; memcpy(p.verts, verts, numverts*sizeof(pvert)); int prev = p.numverts-1; loopj(p.numverts) { pedge e(p.verts[prev], p.verts[j]); int order = e.from.x > e.to.x || (e.from.x == e.to.x && e.from.y > e.to.y) ? 1 : 0; if(order) swap(e.from, e.to); plink &l = links.access(e, e); bool shouldqueue = l.polys[order] < 0 && l.polys[order^1] >= 0; l.polys[order] = owner; if(shouldqueue) queue.add(&l); prev = j; } return true; } void addmerge(cube &cu, int orient, const ivec &co, const ivec &n, int offset, poly &p) { cu.merged |= 1<surfaces[orient] = ambientsurface; return; } surfaceinfo surf = brightsurface; vertinfo verts[MAXFACEVERTS]; surf.numverts |= p.numverts; int dim = dimension(orient), coord = dimcoord(orient), c = C[dim], r = R[dim]; loopk(p.numverts) { pvert &src = p.verts[coord ? k : p.numverts-1-k]; vertinfo &dst = verts[k]; ivec v; v[c] = src.x; v[r] = src.y; v[dim] = -(offset + n[c]*src.x + n[r]*src.y)/n[dim]; dst.set(v); } if(cu.ext) { const surfaceinfo &oldsurf = cu.ext->surfaces[orient]; int numverts = oldsurf.numverts&MAXFACEVERTS; if(numverts == p.numverts) { ivec v0 = verts[0].getxyz(); const vertinfo *oldverts = cu.ext->verts() + oldsurf.verts; loopj(numverts) if(v0 == oldverts[j].getxyz()) { for(int k = 1; k < numverts; k++) { if(++j >= numverts) j = 0; if(verts[k].getxyz() != oldverts[j].getxyz()) goto nomatch; } return; } nomatch:; } } setsurface(cu, orient, surf, verts, p.numverts); } static inline void clearmerge(cube &c, int orient) { if(c.merged&(1<surfaces[orient] = brightsurface; } } void addmerges(int orient, const ivec &co, const ivec &n, int offset, vector &polys) { loopv(polys) { poly &p = polys[i]; if(p.merged) addmerge(*p.c, orient, co, n, offset, p); else clearmerge(*p.c, orient); } } void mergepolys(int orient, const ivec &co, const ivec &n, int offset, vector &polys) { if(polys.length() <= 1) { addmerges(orient, co, n, offset, polys); return; } hashset links(polys.length() <= 32 ? 128 : 1024); vector queue; loopv(polys) { poly &p = polys[i]; int prev = p.numverts-1; loopj(p.numverts) { pedge e(p.verts[prev], p.verts[j]); int order = e.from.x > e.to.x || (e.from.x == e.to.x && e.from.y > e.to.y) ? 1 : 0; if(order) swap(e.from, e.to); plink &l = links.access(e, e); l.polys[order] = i; if(l.polys[0] >= 0 && l.polys[1] >= 0) queue.add(&l); prev = j; } } vector nextqueue; while(queue.length()) { loopv(queue) { plink &l = *queue[i]; if(l.polys[0] >= 0 && l.polys[1] >= 0) mergepolys(orient, links, nextqueue, l.polys[0], polys[l.polys[0]], polys[l.polys[1]], l); } queue.setsize(0); queue.move(nextqueue); } addmerges(orient, co, n, offset, polys); } static int genmergeprogress = 0; struct cfpolys { vector polys; }; static hashtable cpolys; void genmerges(cube *c = worldroot, const ivec &o = ivec(0, 0, 0), int size = worldsize>>1) { if((genmergeprogress++&0xFFF)==0) renderprogress(float(genmergeprogress)/allocnodes, "merging faces..."); neighbourstack[++neighbourdepth] = c; loopi(8) { ivec co(i, o.x, o.y, o.z, size); int vis; if(c[i].children) genmerges(c[i].children, co, size>>1); else if(!isempty(c[i])) loopj(6) if((vis = visibletris(c[i], j, co.x, co.y, co.z, size))) { cfkey k; poly p; if(size < 1<= 1<= x2 && mo.y <= y1 && mo.y + (1<= y2 && mo.z <= z1 && mo.z + (1<= z2) break; bits++; } return bits-3; } static void invalidatemerges(cube &c) { if(c.merged) { brightencube(c); c.merged = 0; } if(c.ext) { if(c.ext->va) { if(!(c.ext->va->hasmerges&(MERGE_PART | MERGE_ORIGIN))) return; destroyva(c.ext->va); c.ext->va = NULL; } if(c.ext->tjoints >= 0) c.ext->tjoints = -1; } if(c.children) loopi(8) invalidatemerges(c.children[i]); } static int invalidatedmerges = 0; void invalidatemerges(cube &c, const ivec &co, int size, bool msg) { if(msg && invalidatedmerges!=totalmillis) { renderprogress(0, "invalidating merged surfaces..."); invalidatedmerges = totalmillis; } invalidatemerges(c); } void calcmerges() { genmergeprogress = 0; genmerges(); } sauerbraten-0.0.20130203.dfsg/engine/octaedit.cpp0000644000175000017500000020112512077327333021152 0ustar vincentvincent#include "engine.h" extern int outline; void boxs(int orient, vec o, const vec &s) { int d = dimension(orient), dc= dimcoord(orient); float f = !outline ? 0 : (dc>0 ? 0.2f : -0.2f); o[D[d]] += float(dc) * s[D[d]] + f, glBegin(GL_LINE_LOOP); glVertex3fv(o.v); o[R[d]] += s[R[d]]; glVertex3fv(o.v); o[C[d]] += s[C[d]]; glVertex3fv(o.v); o[R[d]] -= s[R[d]]; glVertex3fv(o.v); glEnd(); xtraverts += 4; } void boxs3D(const vec &o, vec s, int g) { s.mul(g); loopi(6) boxs(i, o, s); } void boxsgrid(int orient, vec o, vec s, int g) { int d = dimension(orient), dc= dimcoord(orient); float ox = o[R[d]], oy = o[C[d]], xs = s[R[d]], ys = s[C[d]], f = !outline ? 0 : (dc>0 ? 0.2f : -0.2f); o[D[d]] += dc * s[D[d]]*g + f; glBegin(GL_LINES); loop(x, xs) { o[R[d]] += g; glVertex3fv(o.v); o[C[d]] += ys*g; glVertex3fv(o.v); o[C[d]] = oy; } loop(y, ys) { o[C[d]] += g; o[R[d]] = ox; glVertex3fv(o.v); o[R[d]] += xs*g; glVertex3fv(o.v); } glEnd(); xtraverts += 2*int(xs+ys); } selinfo sel, lastsel; int orient = 0; int gridsize = 8; ivec cor, lastcor; ivec cur, lastcur; extern int entediting; bool editmode = false; bool havesel = false; bool hmapsel = false; int horient = 0; extern int entmoving; VARF(dragging, 0, 0, 1, if(!dragging || cor[0]<0) return; lastcur = cur; lastcor = cor; sel.grid = gridsize; sel.orient = orient; ); VARF(moving, 0, 0, 1, if(!moving) return; vec v(cur.v); v.add(1); moving = pointinsel(sel, v); if(moving) havesel = false; // tell cursorupdate to create handle ); VARF(gridpower, 0, 3, 12, { if(dragging) return; gridsize = 1<=worldsize) gridsize = worldsize/2; cancelsel(); }); VAR(passthroughsel, 0, 0, 1); VAR(editing, 1, 0, 0); VAR(selectcorners, 0, 0, 1); VARF(hmapedit, 0, 0, 1, horient = sel.orient); void forcenextundo() { lastsel.orient = -1; } void cubecancel() { havesel = false; moving = dragging = hmapedit = passthroughsel = 0; forcenextundo(); } void cancelsel() { cubecancel(); entcancel(); } void toggleedit(bool force) { if(!force) { if(!isconnected()) return; if(player->state!=CS_ALIVE && player->state!=CS_DEAD && player->state!=CS_EDITING) return; // do not allow dead players to edit to avoid state confusion if(!game::allowedittoggle()) return; // not in most multiplayer modes } if(!(editmode = !editmode)) { player->state = player->editstate; player->o.z -= player->eyeheight; // entinmap wants feet pos entinmap(player); // find spawn closest to current floating pos } else { game::resetgamestate(); player->editstate = player->state; player->state = CS_EDITING; } cancelsel(); stoppaintblendmap(); keyrepeat(editmode); editing = entediting = editmode; extern int fullbright; if(fullbright) { initlights(); lightents(); } if(!force) game::edittoggled(editmode); } bool noedit(bool view, bool msg) { if(!editmode) { if(msg) conoutf(CON_ERROR, "operation only allowed in edit mode"); return true; } if(view || haveselent()) return false; float r = 1.0f; vec o = sel.o.tovec(), s = sel.s.tovec(); s.mul(float(sel.grid) / 2.0f); o.add(s); r = float(max(s.x, max(s.y, s.z))); bool viewable = (isvisiblesphere(r, o) != VFC_NOT_VISIBLE); if(!viewable && msg) conoutf(CON_ERROR, "selection not in view"); return !viewable; } void reorient() { sel.cx = 0; sel.cy = 0; sel.cxs = sel.s[R[dimension(orient)]]*2; sel.cys = sel.s[C[dimension(orient)]]*2; sel.orient = orient; } void selextend() { if(noedit(true)) return; loopi(3) { if(cur[i]=sel.o[i]+sel.s[i]*sel.grid) { sel.s[i] = (cur[i]-sel.o[i])/sel.grid+1; } } } ICOMMAND(edittoggle, "", (), toggleedit(false)); COMMAND(entcancel, ""); COMMAND(cubecancel, ""); COMMAND(cancelsel, ""); COMMAND(reorient, ""); COMMAND(selextend, ""); ///////// selection support ///////////// cube &blockcube(int x, int y, int z, const block3 &b, int rgrid) // looks up a world cube, based on coordinates mapped by the block { int dim = dimension(b.orient), dc = dimcoord(b.orient); ivec s(dim, x*b.grid, y*b.grid, dc*(b.s[dim]-1)*b.grid); s.add(b.o); if(dc) s[dim] -= z*b.grid; else s[dim] += z*b.grid; return lookupcube(s.x, s.y, s.z, rgrid); } #define loopxy(b) loop(y,(b).s[C[dimension((b).orient)]]) loop(x,(b).s[R[dimension((b).orient)]]) #define loopxyz(b, r, f) { loop(z,(b).s[D[dimension((b).orient)]]) loopxy((b)) { cube &c = blockcube(x,y,z,b,r); f; } } #define loopselxyz(f) { if(local) makeundo(); loopxyz(sel, sel.grid, f); changed(sel); } #define selcube(x, y, z) blockcube(x, y, z, sel, sel.grid) ////////////// cursor /////////////// int selchildcount = 0, selchildmat = -1; ICOMMAND(havesel, "", (), intret(havesel ? selchildcount : 0)); void countselchild(cube *c, const ivec &cor, int size) { ivec ss(sel.s); ss.mul(sel.grid); loopoctabox(cor, size, sel.o, ss) { ivec o(i, cor.x, cor.y, cor.z, size); if(c[i].children) countselchild(c[i].children, o, size/2); else { selchildcount++; if(c[i].material != MAT_AIR && selchildmat != MAT_AIR) { if(selchildmat < 0) selchildmat = c[i].material; else if(selchildmat != c[i].material) selchildmat = MAT_AIR; } } } } void normalizelookupcube(int x, int y, int z) { if(lusize>gridsize) { lu.x += (x-lu.x)/gridsize*gridsize; lu.y += (y-lu.y)/gridsize*gridsize; lu.z += (z-lu.z)/gridsize*gridsize; } else if(gridsize>lusize) { lu.x &= ~(gridsize-1); lu.y &= ~(gridsize-1); lu.z &= ~(gridsize-1); } lusize = gridsize; } void updateselection() { sel.o.x = min(lastcur.x, cur.x); sel.o.y = min(lastcur.y, cur.y); sel.o.z = min(lastcur.z, cur.z); sel.s.x = abs(lastcur.x-cur.x)/sel.grid+1; sel.s.y = abs(lastcur.y-cur.y)/sel.grid+1; sel.s.z = abs(lastcur.z-cur.z)/sel.grid+1; } void editmoveplane(const vec &o, const vec &ray, int d, float off, vec &handle, vec &dest, bool first) { plane pl(d, off); float dist = 0.0f; if(pl.rayintersect(player->o, ray, dist)) { dest = ray; dest.mul(dist); dest.add(player->o); if(first) { handle = dest; handle.sub(o); } dest.sub(handle); } } inline bool isheightmap(int orient, int d, bool empty, cube *c); extern void entdrag(const vec &ray); extern bool hoveringonent(int ent, int orient); extern void renderentselection(const vec &o, const vec &ray, bool entmoving); extern float rayent(const vec &o, const vec &ray, float radius, int mode, int size, int &orient, int &ent); VAR(gridlookup, 0, 0, 1); VAR(passthroughcube, 0, 1, 1); void rendereditcursor() { int d = dimension(sel.orient), od = dimension(orient), odc = dimcoord(orient); bool hidecursor = g3d_windowhit(true, false) || blendpaintmode, hovering = false; hmapsel = false; if(moving) { ivec e; static vec v, handle; editmoveplane(sel.o.tovec(), camdir, od, sel.o[D[od]]+odc*sel.grid*sel.s[D[od]], handle, v, !havesel); if(!havesel) { v.add(handle); (e = handle).mask(~(sel.grid-1)); v.sub(handle = e.tovec()); havesel = true; } (e = v).mask(~(sel.grid-1)); sel.o[R[od]] = e[R[od]]; sel.o[C[od]] = e[C[od]]; } else if(entmoving) { entdrag(camdir); } else { ivec w; float sdist = 0, wdist = 0, t; int entorient = 0, ent = -1; wdist = rayent(player->o, camdir, 1e16f, (editmode && showmat ? RAY_EDITMAT : 0) // select cubes first | (!dragging && entediting ? RAY_ENTS : 0) | RAY_SKIPFIRST | (passthroughcube==1 ? RAY_PASS : 0), gridsize, entorient, ent); if((havesel || dragging) && !passthroughsel && !hmapedit) // now try selecting the selection if(rayrectintersect(sel.o.tovec(), vec(sel.s.tovec()).mul(sel.grid), player->o, camdir, sdist, orient)) { // and choose the nearest of the two if(sdist < wdist) { wdist = sdist; ent = -1; } } if((hovering = hoveringonent(hidecursor ? -1 : ent, entorient))) { if(!havesel) { selchildcount = 0; selchildmat = -1; sel.s = ivec(0, 0, 0); } } else { vec w = vec(camdir).mul(wdist+0.05f).add(player->o); if(!insideworld(w)) { loopi(3) wdist = min(wdist, ((camdir[i] > 0 ? worldsize : 0) - player->o[i]) / camdir[i]); w = vec(camdir).mul(wdist-0.05f).add(player->o); if(!insideworld(w)) { wdist = 0; loopi(3) w[i] = clamp(player->o[i], 0.0f, float(worldsize)); } } cube *c = &lookupcube(int(w.x), int(w.y), int(w.z)); if(gridlookup && !dragging && !moving && !havesel && hmapedit!=1) gridsize = lusize; int mag = lusize / gridsize; normalizelookupcube(int(w.x), int(w.y), int(w.z)); if(sdist == 0 || sdist > wdist) rayrectintersect(lu.tovec(), vec(gridsize), player->o, camdir, t=0, orient); // just getting orient cur = lu; cor = vec(w).mul(2).div(gridsize); od = dimension(orient); d = dimension(sel.orient); if(hmapedit==1 && dimcoord(horient) == (camdir[dimension(horient)]<0)) { hmapsel = isheightmap(horient, dimension(horient), false, c); if(hmapsel) od = dimension(orient = horient); } if(dragging) { updateselection(); sel.cx = min(cor[R[d]], lastcor[R[d]]); sel.cy = min(cor[C[d]], lastcor[C[d]]); sel.cxs = max(cor[R[d]], lastcor[R[d]]); sel.cys = max(cor[C[d]], lastcor[C[d]]); if(!selectcorners) { sel.cx &= ~1; sel.cy &= ~1; sel.cxs &= ~1; sel.cys &= ~1; sel.cxs -= sel.cx-2; sel.cys -= sel.cy-2; } else { sel.cxs -= sel.cx-1; sel.cys -= sel.cy-1; } sel.cx &= 1; sel.cy &= 1; havesel = true; } else if(!havesel) { sel.o = lu; sel.s.x = sel.s.y = sel.s.z = 1; sel.cx = sel.cy = 0; sel.cxs = sel.cys = 2; sel.grid = gridsize; sel.orient = orient; d = od; } sel.corner = (cor[R[d]]-(lu[R[d]]*2)/gridsize)+(cor[C[d]]-(lu[C[d]]*2)/gridsize)*2; selchildcount = 0; selchildmat = -1; countselchild(worldroot, ivec(0, 0, 0), worldsize/2); if(mag>=1 && selchildcount==1) { selchildmat = c->material; if(mag>1) selchildcount = -mag; } } } glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); // cursors lineshader->set(); renderentselection(player->o, camdir, entmoving!=0); enablepolygonoffset(GL_POLYGON_OFFSET_LINE); if(!moving && !hovering && !hidecursor) { if(hmapedit==1) glColor3ub(0, hmapsel ? 255 : 40, 0); else glColor3ub(120,120,120); boxs(orient, lu.tovec(), vec(lusize)); } // selections if(havesel) { d = dimension(sel.orient); glColor3ub(50,50,50); // grid boxsgrid(sel.orient, sel.o.tovec(), sel.s.tovec(), sel.grid); glColor3ub(200,0,0); // 0 reference boxs3D(sel.o.tovec().sub(0.5f*min(gridsize*0.25f, 2.0f)), vec(min(gridsize*0.25f, 2.0f)), 1); glColor3ub(200,200,200);// 2D selection box vec co(sel.o.v), cs(sel.s.v); co[R[d]] += 0.5f*(sel.cx*gridsize); co[C[d]] += 0.5f*(sel.cy*gridsize); cs[R[d]] = 0.5f*(sel.cxs*gridsize); cs[C[d]] = 0.5f*(sel.cys*gridsize); cs[D[d]] *= gridsize; boxs(sel.orient, co, cs); if(hmapedit==1) // 3D selection box glColor3ub(0,120,0); else glColor3ub(0,0,120); boxs3D(sel.o.tovec(), sel.s.tovec(), sel.grid); } disablepolygonoffset(GL_POLYGON_OFFSET_LINE); notextureshader->set(); glDisable(GL_BLEND); } void tryedit() { extern int hidehud; if(!editmode || hidehud || mainmenu) return; if(blendpaintmode) trypaintblendmap(); } //////////// ready changes to vertex arrays //////////// static bool haschanged = false; void readychanges(block3 &b, cube *c, const ivec &cor, int size) { loopoctabox(cor, size, b.o, b.s) { ivec o(i, cor.x, cor.y, cor.z, size); if(c[i].ext) { if(c[i].ext->va) // removes va s so that octarender will recreate { int hasmerges = c[i].ext->va->hasmerges; destroyva(c[i].ext->va); c[i].ext->va = NULL; if(hasmerges) invalidatemerges(c[i], o, size, true); } freeoctaentities(c[i]); c[i].ext->tjoints = -1; } if(c[i].children) { if(size<=1) { solidfaces(c[i]); discardchildren(c[i], true); brightencube(c[i]); } else readychanges(b, c[i].children, o, size/2); } else brightencube(c[i]); } } void commitchanges(bool force) { if(!force && !haschanged) return; haschanged = false; extern vector valist; int oldlen = valist.length(); resetclipplanes(); entitiesinoctanodes(); inbetweenframes = false; octarender(); inbetweenframes = true; setupmaterials(oldlen); invalidatepostfx(); updatevabbs(); resetblobs(); } void changed(const block3 &sel, bool commit = true) { if(sel.s.iszero()) return; block3 b = sel; loopi(3) b.s[i] *= b.grid; b.grid = 1; loopi(3) // the changed blocks are the selected cubes { b.o[i] -= 1; b.s[i] += 2; readychanges(b, worldroot, ivec(0, 0, 0), worldsize/2); b.o[i] += 1; b.s[i] -= 2; } haschanged = true; if(commit) commitchanges(); } //////////// copy and undo ///////////// static inline void copycube(const cube &src, cube &dst) { dst = src; dst.visible = 0; dst.merged = 0; dst.ext = NULL; // src cube is responsible for va destruction if(src.children) { dst.children = newcubes(F_EMPTY); loopi(8) copycube(src.children[i], dst.children[i]); } } static inline void pastecube(const cube &src, cube &dst) { discardchildren(dst); copycube(src, dst); } void blockcopy(const block3 &s, int rgrid, block3 *b) { *b = s; cube *q = b->c(); loopxyz(s, rgrid, copycube(c, *q++)); } block3 *blockcopy(const block3 &s, int rgrid) { int bsize = sizeof(block3)+sizeof(cube)*s.size(); if(bsize <= 0 || bsize > (100<<20)) return 0; block3 *b = (block3 *)new uchar[bsize]; blockcopy(s, rgrid, b); return b; } void freeblock(block3 *b, bool alloced = true) { cube *q = b->c(); loopi(b->size()) discardchildren(*q++); if(alloced) delete[] b; } void selgridmap(selinfo &sel, int *g) // generates a map of the cube sizes at each grid point { loopxyz(sel, -sel.grid, (*g++ = lusize, (void)c)); } void freeundo(undoblock *u) { if(!u->numents) freeblock(u->block(), false); delete[] (uchar *)u; } void pasteundo(undoblock *u) { if(u->numents) pasteundoents(u); else { block3 *b = u->block(); cube *s = b->c(); int *g = u->gridmap(); loopxyz(*b, *g++, pastecube(*s++, c)); } } static inline int undosize(undoblock *u) { if(u->numents) return u->numents*sizeof(undoent); else { block3 *b = u->block(); cube *q = b->c(); int size = b->size(), total = size*sizeof(int); loopj(size) total += familysize(*q++)*sizeof(cube); return total; } } struct undolist { undoblock *first, *last; undolist() : first(NULL), last(NULL) {} bool empty() { return !first; } void add(undoblock *u) { u->next = NULL; u->prev = last; if(!first) first = last = u; else { last->next = u; last = u; } } undoblock *popfirst() { undoblock *u = first; first = first->next; if(first) first->prev = NULL; else last = NULL; return u; } undoblock *poplast() { undoblock *u = last; last = last->prev; if(last) last->next = NULL; else first = NULL; return u; } }; undolist undos, redos; VARP(undomegs, 0, 5, 100); // bounded by n megs int totalundos = 0; void pruneundos(int maxremain) // bound memory { while(totalundos > maxremain && !undos.empty()) { undoblock *u = undos.popfirst(); totalundos -= u->size; freeundo(u); } //conoutf(CON_DEBUG, "undo: %d of %d(%%%d)", totalundos, undomegs<<20, totalundos*100/(undomegs<<20)); while(!redos.empty()) { undoblock *u = redos.popfirst(); totalundos -= u->size; freeundo(u); } } void clearundos() { pruneundos(0); } COMMAND(clearundos, ""); undoblock *newundocube(selinfo &s) { int ssize = s.size(), selgridsize = ssize*sizeof(int), blocksize = sizeof(block3)+ssize*sizeof(cube); if(blocksize <= 0 || blocksize > (undomegs<<20)) return NULL; undoblock *u = (undoblock *)new uchar[sizeof(undoblock) + blocksize + selgridsize]; u->numents = 0; block3 *b = (block3 *)(u + 1); blockcopy(s, -s.grid, b); int *g = (int *)((uchar *)b + blocksize); selgridmap(s, g); return u; } void addundo(undoblock *u) { u->size = undosize(u); u->timestamp = totalmillis; undos.add(u); totalundos += u->size; pruneundos(undomegs<<20); } VARP(nompedit, 0, 1, 1); void makeundoex(selinfo &s) { if(nompedit && multiplayer(false)) return; undoblock *u = newundocube(s); if(u) addundo(u); } void makeundo() // stores state of selected cubes before editing { if(lastsel==sel || sel.s.iszero()) return; lastsel=sel; makeundoex(sel); } void swapundo(undolist &a, undolist &b, const char *s) { if(noedit() || (nompedit && multiplayer())) return; if(a.empty()) { conoutf(CON_WARN, "nothing more to %s", s); return; } int ts = a.last->timestamp; selinfo l = sel; while(!a.empty() && ts==a.last->timestamp) { undoblock *u = a.poplast(), *r; if(u->numents) r = copyundoents(u); else { block3 *ub = u->block(); l.o = ub->o; l.s = ub->s; l.grid = ub->grid; l.orient = ub->orient; r = newundocube(l); } if(r) { r->size = u->size; r->timestamp = totalmillis; b.add(r); } pasteundo(u); if(!u->numents) changed(l, false); freeundo(u); } commitchanges(); if(!hmapsel) { sel = l; reorient(); } forcenextundo(); } void editundo() { swapundo(undos, redos, "undo"); } void editredo() { swapundo(redos, undos, "redo"); } // guard against subdivision #define protectsel(f) { undoblock *_u = newundocube(sel); f; if(_u) { pasteundo(_u); freeundo(_u); } } vector editinfos; editinfo *localedit = NULL; template static void packcube(cube &c, B &buf) { if(c.children) { buf.put(0xFF); loopi(8) packcube(c.children[i], buf); } else { cube data = c; lilswap(data.texture, 6); buf.put(c.material&0xFF); buf.put(c.material>>8); buf.put(data.edges, sizeof(data.edges)); buf.put((uchar *)data.texture, sizeof(data.texture)); } } template static bool packblock(block3 &b, B &buf) { if(b.size() <= 0 || b.size() > (1<<20)) return false; block3 hdr = b; lilswap(hdr.o.v, 3); lilswap(hdr.s.v, 3); lilswap(&hdr.grid, 1); lilswap(&hdr.orient, 1); buf.put((const uchar *)&hdr, sizeof(hdr)); cube *c = b.c(); loopi(b.size()) packcube(c[i], buf); return true; } template static void unpackcube(cube &c, B &buf) { int mat = buf.get(); if(mat == 0xFF) { c.children = newcubes(F_EMPTY); loopi(8) unpackcube(c.children[i], buf); } else { c.material = mat | (buf.get()<<8); buf.get(c.edges, sizeof(c.edges)); buf.get((uchar *)c.texture, sizeof(c.texture)); lilswap(c.texture, 6); } } template static bool unpackblock(block3 *&b, B &buf) { if(b) { freeblock(b); b = NULL; } block3 hdr; buf.get((uchar *)&hdr, sizeof(hdr)); lilswap(hdr.o.v, 3); lilswap(hdr.s.v, 3); lilswap(&hdr.grid, 1); lilswap(&hdr.orient, 1); if(hdr.size() > (1<<20)) return false; b = (block3 *)new uchar[sizeof(block3)+hdr.size()*sizeof(cube)]; *b = hdr; cube *c = b->c(); memset(c, 0, b->size()*sizeof(cube)); loopi(b->size()) unpackcube(c[i], buf); return true; } static bool compresseditinfo(const uchar *inbuf, int inlen, uchar *&outbuf, int &outlen) { uLongf len = compressBound(inlen); if(len > (1<<20)) return false; outbuf = new uchar[len]; if(compress2((Bytef *)outbuf, &len, (const Bytef *)inbuf, inlen, Z_BEST_COMPRESSION) != Z_OK || len > (1<<16)) { delete[] outbuf; outbuf = NULL; return false; } outlen = len; return true; } static bool uncompresseditinfo(const uchar *inbuf, int inlen, uchar *&outbuf, int &outlen) { if(compressBound(outlen) > (1<<20)) return false; uLongf len = outlen; outbuf = new uchar[len]; if(uncompress((Bytef *)outbuf, &len, (const Bytef *)inbuf, inlen) != Z_OK) { delete[] outbuf; outbuf = NULL; return false; } outlen = len; return true; } bool packeditinfo(editinfo *e, int &inlen, uchar *&outbuf, int &outlen) { vector buf; if(!e || !e->copy || !packblock(*e->copy, buf)) return false; inlen = buf.length(); return compresseditinfo(buf.getbuf(), buf.length(), outbuf, outlen); } bool unpackeditinfo(editinfo *&e, const uchar *inbuf, int inlen, int outlen) { if(e && e->copy) { freeblock(e->copy); e->copy = NULL; } uchar *outbuf = NULL; if(!uncompresseditinfo(inbuf, inlen, outbuf, outlen)) return false; ucharbuf buf(outbuf, outlen); if(!e) e = editinfos.add(new editinfo); if(!unpackblock(e->copy, buf)) { delete[] outbuf; return false; } delete[] outbuf; return true; } void freeeditinfo(editinfo *&e) { if(!e) return; editinfos.removeobj(e); if(e->copy) freeblock(e->copy); delete e; e = NULL; } struct octabrushheader { char magic[4]; int version; }; struct octabrush : editinfo { char *name; octabrush() : name(NULL) {} ~octabrush() { DELETEA(name); if(copy) freeblock(copy); } }; static inline bool htcmp(const char *key, const octabrush &b) { return !strcmp(key, b.name); } static hashset octabrushes; void delbrush(char *name) { if(octabrushes.remove(name)) conoutf("deleted brush %s", name); } COMMAND(delbrush, "s"); void savebrush(char *name) { if(!name[0] || noedit(true) || (nompedit && multiplayer())) return; octabrush *b = octabrushes.access(name); if(!b) { b = &octabrushes[name]; b->name = newstring(name); } if(b->copy) freeblock(b->copy); protectsel(b->copy = blockcopy(block3(sel), sel.grid)); changed(sel); defformatstring(filename)(strpbrk(name, "/\\") ? "packages/%s.obr" : "packages/brush/%s.obr", name); path(filename); stream *f = opengzfile(filename, "wb"); if(!f) { conoutf(CON_ERROR, "could not write brush to %s", filename); return; } octabrushheader hdr; memcpy(hdr.magic, "OEBR", 4); hdr.version = 0; lilswap(&hdr.version, 1); f->write(&hdr, sizeof(hdr)); streambuf s(f); if(!packblock(*b->copy, s)) { delete f; conoutf(CON_ERROR, "could not pack brush %s", filename); return; } delete f; conoutf("wrote brush file %s", filename); } COMMAND(savebrush, "s"); void pasteblock(block3 &b, selinfo &sel, bool local) { sel.s = b.s; int o = sel.orient; sel.orient = b.orient; cube *s = b.c(); loopselxyz(if(!isempty(*s) || s->children || s->material != MAT_AIR) pastecube(*s, c); s++); // 'transparent'. old opaque by 'delcube; paste' sel.orient = o; } void pastebrush(char *name) { if(!name[0] || noedit() || (nompedit && multiplayer())) return; octabrush *b = octabrushes.access(name); if(!b) { defformatstring(filename)(strpbrk(name, "/\\") ? "packages/%s.obr" : "packages/brush/%s.obr", name); path(filename); stream *f = opengzfile(filename, "rb"); if(!f) { conoutf(CON_ERROR, "could not read brush %s", filename); return; } octabrushheader hdr; if(f->read(&hdr, sizeof(hdr)) != sizeof(octabrushheader) || memcmp(hdr.magic, "OEBR", 4)) { delete f; conoutf(CON_ERROR, "brush %s has malformatted header", filename); return; } lilswap(&hdr.version, 1); if(hdr.version != 0) { delete f; conoutf(CON_ERROR, "brush %s uses unsupported version", filename); return; } streambuf s(f); block3 *copy = NULL; if(!unpackblock(copy, s)) { delete f; conoutf(CON_ERROR, "could not unpack brush %s", filename); return; } delete f; b = &octabrushes[name]; b->name = newstring(name); b->copy = copy; } pasteblock(*b->copy, sel, true); } COMMAND(pastebrush, "s"); void mpcopy(editinfo *&e, selinfo &sel, bool local) { if(local) game::edittrigger(sel, EDIT_COPY); if(e==NULL) e = editinfos.add(new editinfo); if(e->copy) freeblock(e->copy); e->copy = NULL; protectsel(e->copy = blockcopy(block3(sel), sel.grid)); changed(sel); } void mppaste(editinfo *&e, selinfo &sel, bool local) { if(e==NULL) return; if(local) game::edittrigger(sel, EDIT_PASTE); if(e->copy) pasteblock(*e->copy, sel, local); } void copy() { if(noedit(true)) return; mpcopy(localedit, sel, true); } void pastehilite() { if(!localedit) return; sel.s = localedit->copy->s; reorient(); havesel = true; } void paste() { if(noedit()) return; mppaste(localedit, sel, true); } COMMAND(copy, ""); COMMAND(pastehilite, ""); COMMAND(paste, ""); COMMANDN(undo, editundo, ""); COMMANDN(redo, editredo, ""); static VSlot *editingvslot = NULL; void compacteditvslots() { if(editingvslot && editingvslot->layer) compactvslot(editingvslot->layer); loopv(editinfos) { editinfo *e = editinfos[i]; compactvslots(e->copy->c(), e->copy->size()); } for(undoblock *u = undos.first; u; u = u->next) if(!u->numents) compactvslots(u->block()->c(), u->block()->size()); for(undoblock *u = redos.first; u; u = u->next) if(!u->numents) compactvslots(u->block()->c(), u->block()->size()); } ///////////// height maps //////////////// #define MAXBRUSH 64 #define MAXBRUSHC 63 #define MAXBRUSH2 32 int brush[MAXBRUSH][MAXBRUSH]; VAR(brushx, 0, MAXBRUSH2, MAXBRUSH); VAR(brushy, 0, MAXBRUSH2, MAXBRUSH); bool paintbrush = 0; int brushmaxx = 0, brushminx = MAXBRUSH; int brushmaxy = 0, brushminy = MAXBRUSH; void clearbrush() { memset(brush, 0, sizeof brush); brushmaxx = brushmaxy = 0; brushminx = brushminy = MAXBRUSH; paintbrush = false; } void brushvert(int *x, int *y, int *v) { *x += MAXBRUSH2 - brushx + 1; // +1 for automatic padding *y += MAXBRUSH2 - brushy + 1; if(*x<0 || *y<0 || *x>=MAXBRUSH || *y>=MAXBRUSH) return; brush[*x][*y] = clamp(*v, 0, 8); paintbrush = paintbrush || (brush[*x][*y] > 0); brushmaxx = min(MAXBRUSH-1, max(brushmaxx, *x+1)); brushmaxy = min(MAXBRUSH-1, max(brushmaxy, *y+1)); brushminx = max(0, min(brushminx, *x-1)); brushminy = max(0, min(brushminy, *y-1)); } vector htextures; COMMAND(clearbrush, ""); COMMAND(brushvert, "iii"); ICOMMAND(hmapcancel, "", (), htextures.setsize(0); ); ICOMMAND(hmapselect, "", (), int t = lookupcube(cur.x, cur.y, cur.z).texture[orient]; int i = htextures.find(t); if(i<0) htextures.add(t); else htextures.remove(i); ); inline bool ishtexture(int t) { loopv(htextures) if(t == htextures[i]) return false; return true; } VARP(bypassheightmapcheck, 0, 0, 1); // temp inline bool isheightmap(int o, int d, bool empty, cube *c) { return havesel || (empty && isempty(*c)) || ishtexture(c->texture[o]); } namespace hmap { # define PAINTED 1 # define NOTHMAP 2 # define MAPPED 16 uchar flags[MAXBRUSH][MAXBRUSH]; cube *cmap[MAXBRUSHC][MAXBRUSHC][4]; int mapz[MAXBRUSHC][MAXBRUSHC]; int map [MAXBRUSH][MAXBRUSH]; selinfo changes; bool selecting; int d, dc, dr, dcr, biasup, br, hws, fg; int gx, gy, gz, mx, my, mz, nx, ny, nz, bmx, bmy, bnx, bny; uint fs; selinfo hundo; cube *getcube(ivec t, int f) { t[d] += dcr*f*gridsize; if(t[d] > nz || t[d] < mz) return NULL; cube *c = &lookupcube(t.x, t.y, t.z, gridsize); if(c->children) forcemip(*c, false); discardchildren(*c, true); if(!isheightmap(sel.orient, d, true, c)) return NULL; if (t.x < changes.o.x) changes.o.x = t.x; else if(t.x > changes.s.x) changes.s.x = t.x; if (t.y < changes.o.y) changes.o.y = t.y; else if(t.y > changes.s.y) changes.s.y = t.y; if (t.z < changes.o.z) changes.o.z = t.z; else if(t.z > changes.s.z) changes.s.z = t.z; return c; } uint getface(cube *c, int d) { return 0x0f0f0f0f & ((dc ? c->faces[d] : 0x88888888 - c->faces[d]) >> fs); } void pushside(cube &c, int d, int x, int y, int z) { ivec a; getcubevector(c, d, x, y, z, a); a[R[d]] = 8 - a[R[d]]; setcubevector(c, d, x, y, z, a); } void addpoint(int x, int y, int z, int v) { if(!(flags[x][y] & MAPPED)) map[x][y] = v + (z*8); flags[x][y] |= MAPPED; } void select(int x, int y, int z) { if((NOTHMAP & flags[x][y]) || (PAINTED & flags[x][y])) return; ivec t(d, x+gx, y+gy, dc ? z : hws-z); t.shl(gridpower); // selections may damage; must makeundo before hundo.o = t; hundo.o[D[d]] -= dcr*gridsize*2; makeundoex(hundo); cube **c = cmap[x][y]; loopk(4) c[k] = NULL; c[1] = getcube(t, 0); if(!c[1] || !isempty(*c[1])) { // try up c[2] = c[1]; c[1] = getcube(t, 1); if(!c[1] || isempty(*c[1])) { c[0] = c[1]; c[1] = c[2]; c[2] = NULL; } else { z++; t[d]+=fg; } } else // drop down { z--; t[d]-= fg; c[0] = c[1]; c[1] = getcube(t, 0); } if(!c[1] || isempty(*c[1])) { flags[x][y] |= NOTHMAP; return; } flags[x][y] |= PAINTED; mapz [x][y] = z; if(!c[0]) c[0] = getcube(t, 1); if(!c[2]) c[2] = getcube(t, -1); c[3] = getcube(t, -2); c[2] = !c[2] || isempty(*c[2]) ? NULL : c[2]; c[3] = !c[3] || isempty(*c[3]) ? NULL : c[3]; uint face = getface(c[1], d); if(face == 0x08080808 && (!c[0] || !isempty(*c[0]))) { flags[x][y] |= NOTHMAP; return; } if(c[1]->faces[R[d]] == F_SOLID) // was single face += 0x08080808; else // was pair face += c[2] ? getface(c[2], d) : 0x08080808; face += 0x08080808; // c[3] uchar *f = (uchar*)&face; addpoint(x, y, z, f[0]); addpoint(x+1, y, z, f[1]); addpoint(x, y+1, z, f[2]); addpoint(x+1, y+1, z, f[3]); if(selecting) // continue to adjacent cubes { if(x>bmx) select(x-1, y, z); if(xbmy) select(x, y-1, z); if(y, <, 1, 0, -); else pullhmap(worldsize*8, <, >, 0, 8, +); cube **c = cmap[x][y]; int e[2][2]; int notempty = 0; loopk(4) if(c[k]) { loopi(2) loopj(2) { e[i][j] = min(8, map[x+i][y+j] - (mapz[x][y]+3-k)*8); notempty |= e[i][j] > 0; } if(notempty) { c[k]->texture[sel.orient] = c[1]->texture[sel.orient]; solidfaces(*c[k]); loopi(2) loopj(2) { int f = e[i][j]; if(f<0 || (f==0 && e[1-i][j]==0 && e[i][1-j]==0)) { f=0; pushside(*c[k], d, i, j, 0); pushside(*c[k], d, i, j, 1); } edgeset(cubeedge(*c[k], d, i, j), dc, dc ? f : 8-f); } } else emptyfaces(*c[k]); } if(!changed) return; if(x>mx) ripple(x-1, y, mapz[x][y], true); if(xmy) ripple(x, y-1, mapz[x][y], true); if(ymx && y>my)); // do diagonals because adjacents DIAGONAL_RIPPLE(-1, +1, (x>mx && ymy)); } #define loopbrush(i) for(int x=bmx; x<=bnx+i; x++) for(int y=bmy; y<=bny+i; y++) void paint() { loopbrush(1) map[x][y] -= dr * brush[x][y]; } void smooth() { int sum, div; loopbrush(-2) { sum = 0; div = 9; loopi(3) loopj(3) if(flags[x+i][y+j] & MAPPED) sum += map[x+i][y+j]; else div--; if(div) map[x+1][y+1] = sum / div; } } void rippleandset() { loopbrush(0) ripple(x, y, gz, false); } void run(int dir, int mode) { d = dimension(sel.orient); dc = dimcoord(sel.orient); dcr= dc ? 1 : -1; dr = dir>0 ? 1 : -1; br = dir>0 ? 0x08080808 : 0; // biasup = mode == dir<0; biasup = dir<0; bool paintme = paintbrush; int cx = (sel.corner&1 ? 0 : -1); int cy = (sel.corner&2 ? 0 : -1); hws= (worldsize>>gridpower); gx = (cur[R[d]] >> gridpower) + cx - MAXBRUSH2; gy = (cur[C[d]] >> gridpower) + cy - MAXBRUSH2; gz = (cur[D[d]] >> gridpower); fs = dc ? 4 : 0; fg = dc ? gridsize : -gridsize; mx = max(0, -gx); // ripple range my = max(0, -gy); nx = min(MAXBRUSH-1, hws-gx) - 1; ny = min(MAXBRUSH-1, hws-gy) - 1; if(havesel) { // selection range bmx = mx = max(mx, (sel.o[R[d]]>>gridpower)-gx); bmy = my = max(my, (sel.o[C[d]]>>gridpower)-gy); bnx = nx = min(nx, (sel.s[R[d]]+(sel.o[R[d]]>>gridpower))-gx-1); bny = ny = min(ny, (sel.s[C[d]]+(sel.o[C[d]]>>gridpower))-gy-1); } if(havesel && mode<0) // -ve means smooth selection paintme = false; else { // brush range bmx = max(mx, brushminx); bmy = max(my, brushminy); bnx = min(nx, brushmaxx-1); bny = min(ny, brushmaxy-1); } nz = worldsize-gridsize; mz = 0; hundo.s = ivec(d,1,1,5); hundo.orient = sel.orient; hundo.grid = gridsize; forcenextundo(); changes.grid = gridsize; changes.s = changes.o = cur; memset(map, 0, sizeof map); memset(flags, 0, sizeof flags); selecting = true; select(clamp(MAXBRUSH2-cx, bmx, bnx), clamp(MAXBRUSH2-cy, bmy, bny), dc ? gz : hws - gz); selecting = false; if(paintme) paint(); else smooth(); rippleandset(); // pull up points to cubify, and set changes.s.sub(changes.o).shr(gridpower).add(1); changed(changes); } } void edithmap(int dir, int mode) { if((nompedit && multiplayer()) || !hmapsel) return; hmap::run(dir, mode); } ///////////// main cube edit //////////////// int bounded(int n) { return n<0 ? 0 : (n>8 ? 8 : n); } void pushedge(uchar &edge, int dir, int dc) { int ne = bounded(edgeget(edge, dc)+dir); edgeset(edge, dc, ne); int oe = edgeget(edge, 1-dc); if((dir<0 && dc && oe>ne) || (dir>0 && dc==0 && oe0) == dc && h<=0) || ((dir<0) == dc && h>=worldsize)) return; if(dir<0) sel.o[d] += sel.grid * seldir; } if(dc) sel.o[d] += sel.us(d)-sel.grid; sel.s[d] = 1; loopselxyz( if(c.children) solidfaces(c); ushort mat = getmaterial(c); discardchildren(c, true); c.material = mat; if(mode==1) // fill command { if(dir<0) { solidfaces(c); cube &o = blockcube(x, y, 1, sel, -sel.grid); loopi(6) c.texture[i] = o.children ? DEFAULT_GEOM : o.texture[i]; } else emptyfaces(c); } else { uint bak = c.faces[d]; uchar *p = (uchar *)&c.faces[d]; if(mode==2) linkedpush(c, d, sel.corner&1, sel.corner>>1, dc, seldir); // corner command else { loop(mx,2) loop(my,2) // pull/push edges command { if(x==0 && mx==0 && sel.cx) continue; if(y==0 && my==0 && sel.cy) continue; if(x==sel.s[R[d]]-1 && mx==1 && (sel.cx+sel.cxs)&1) continue; if(y==sel.s[C[d]]-1 && my==1 && (sel.cy+sel.cys)&1) continue; if(p[mx+my*2] != ((uchar *)&bak)[mx+my*2]) continue; linkedpush(c, d, mx, my, dc, seldir); } } optiface(p, c); if(invalidcubeguard==1 && !isvalidcube(c)) { uint newbak = c.faces[d]; uchar *m = (uchar *)&bak; uchar *n = (uchar *)&newbak; loopk(4) if(n[k] != m[k]) // tries to find partial edit that is valid { c.faces[d] = bak; c.edges[d*4+k] = n[k]; if(isvalidcube(c)) m[k] = n[k]; } c.faces[d] = bak; } } ); if (mode==1 && dir>0) sel.o[d] += sel.grid * seldir; } void editface(int *dir, int *mode) { if(noedit(moving!=0)) return; if(hmapedit!=1) mpeditface(*dir, *mode, sel, true); else edithmap(*dir, *mode); } VAR(selectionsurf, 0, 0, 1); void pushsel(int *dir) { if(noedit(moving!=0)) return; int d = dimension(orient); int s = dimcoord(orient) ? -*dir : *dir; sel.o[d] += s*sel.grid; if(selectionsurf==1) { player->o[d] += s*sel.grid; player->resetinterp(); } } void mpdelcube(selinfo &sel, bool local) { if(local) game::edittrigger(sel, EDIT_DELCUBE); loopselxyz(discardchildren(c, true); emptyfaces(c)); } void delcube() { if(noedit()) return; mpdelcube(sel, true); } COMMAND(pushsel, "i"); COMMAND(editface, "ii"); COMMAND(delcube, ""); /////////// texture editing ////////////////// int curtexindex = -1, lasttex = 0, lasttexmillis = -1; int texpaneltimer = 0; vector texmru; void tofronttex() // maintain most recently used of the texture lists when applying texture { int c = curtexindex; if(c>=0) { texmru.insert(0, texmru.remove(c)); curtexindex = -1; } } selinfo repsel; int reptex = -1; struct vslotmap { int index; VSlot *vslot; vslotmap() {} vslotmap(int index, VSlot *vslot) : index(index), vslot(vslot) {} }; static vector remappedvslots; VAR(usevdelta, 1, 0, 0); static VSlot *remapvslot(int index, const VSlot &ds) { loopv(remappedvslots) if(remappedvslots[i].index == index) return remappedvslots[i].vslot; VSlot &vs = lookupvslot(index, false); if(vs.index < 0 || vs.index == DEFAULT_SKY) return NULL; VSlot *edit = NULL; if(usevdelta) { VSlot ms; mergevslot(ms, vs, ds); edit = ms.changed ? editvslot(vs, ms) : vs.slot->variants; } else edit = ds.changed ? editvslot(vs, ds) : vs.slot->variants; if(!edit) edit = &vs; remappedvslots.add(vslotmap(vs.index, edit)); return edit; } static void remapvslots(cube &c, const VSlot &ds, int orient, bool &findrep, VSlot *&findedit) { if(c.children) { loopi(8) remapvslots(c.children[i], ds, orient, findrep, findedit); return; } static VSlot ms; if(orient<0) loopi(6) { VSlot *edit = remapvslot(c.texture[i], ds); if(edit) { c.texture[i] = edit->index; if(!findedit) findedit = edit; } } else { int i = visibleorient(c, orient); VSlot *edit = remapvslot(c.texture[i], ds); if(edit) { if(findrep) { if(reptex < 0) reptex = c.texture[i]; else if(reptex != c.texture[i]) findrep = false; } c.texture[i] = edit->index; if(!findedit) findedit = edit; } } } void edittexcube(cube &c, int tex, int orient, bool &findrep) { if(orient<0) loopi(6) c.texture[i] = tex; else { int i = visibleorient(c, orient); if(findrep) { if(reptex < 0) reptex = c.texture[i]; else if(reptex != c.texture[i]) findrep = false; } c.texture[i] = tex; } if(c.children) loopi(8) edittexcube(c.children[i], tex, orient, findrep); } VAR(allfaces, 0, 0, 1); void mpeditvslot(VSlot &ds, int allfaces, selinfo &sel, bool local) { if(local) { if(!(lastsel==sel)) tofronttex(); if(allfaces || !(repsel == sel)) reptex = -1; repsel = sel; } bool findrep = local && !allfaces && reptex < 0; VSlot *findedit = NULL; editingvslot = &ds; loopselxyz(remapvslots(c, ds, allfaces ? -1 : sel.orient, findrep, findedit)); editingvslot = NULL; remappedvslots.setsize(0); if(local && findedit) { lasttex = findedit->index; lasttexmillis = totalmillis; curtexindex = texmru.find(lasttex); if(curtexindex < 0) { curtexindex = texmru.length(); texmru.add(lasttex); } } } void vdelta(char *body) { if(noedit() || (nompedit && multiplayer())) return; usevdelta++; execute(body); usevdelta--; } COMMAND(vdelta, "s"); void vrotate(int *n) { if(noedit() || (nompedit && multiplayer())) return; VSlot ds; ds.changed = 1<=vslots.length()) { if(curtexindex > i) curtexindex--; else if(curtexindex == i) curtexindex = -1; texmru.remove(i); } loopv(vslots) if(texmru.find(i)<0) texmru.add(i); } } void compactmruvslots() { remappedvslots.setsize(0); loopvrev(texmru) { if(vslots.inrange(texmru[i])) { VSlot &vs = *vslots[texmru[i]]; if(vs.index >= 0) { texmru[i] = vs.index; continue; } } if(curtexindex > i) curtexindex--; else if(curtexindex == i) curtexindex = -1; texmru.remove(i); } if(vslots.inrange(lasttex)) { VSlot &vs = *vslots[lasttex]; lasttex = vs.index >= 0 ? vs.index : 0; } else lasttex = 0; reptex = vslots.inrange(reptex) ? vslots[reptex]->index : -1; } void edittex(int i, bool save = true) { lasttex = i; lasttexmillis = totalmillis; if(save) { loopvj(texmru) if(texmru[j]==lasttex) { curtexindex = j; break; } } mpedittex(i, allfaces, sel, true); } void edittex_(int *dir) { if(noedit()) return; filltexlist(); texpaneltimer = 5000; if(!(lastsel==sel)) tofronttex(); curtexindex = clamp(curtexindex<0 ? 0 : curtexindex+*dir, 0, texmru.length()-1); edittex(texmru[curtexindex], false); } void gettex() { if(noedit(true)) return; filltexlist(); int tex = -1; loopxyz(sel, sel.grid, tex = c.texture[sel.orient]); loopv(texmru) if(texmru[i]==tex) { curtexindex = i; tofronttex(); return; } } void getcurtex() { if(noedit(true)) return; filltexlist(); int index = curtexindex < 0 ? 0 : curtexindex; if(!texmru.inrange(index)) return; intret(texmru[index]); } void getseltex() { if(noedit(true)) return; cube &c = lookupcube(sel.o.x, sel.o.y, sel.o.z, -sel.grid); if(c.children || isempty(c)) return; intret(c.texture[sel.orient]); } void gettexname(int *tex, int *subslot) { if(noedit(true) || *tex<0) return; VSlot &vslot = lookupvslot(*tex, false); Slot &slot = *vslot.slot; if(!slot.sts.inrange(*subslot)) return; result(slot.sts[*subslot].name); } COMMANDN(edittex, edittex_, "i"); COMMAND(gettex, ""); COMMAND(getcurtex, ""); COMMAND(getseltex, ""); ICOMMAND(getreptex, "", (), { if(!noedit()) intret(vslots.inrange(reptex) ? reptex : -1); }); COMMAND(gettexname, "ii"); void replacetexcube(cube &c, int oldtex, int newtex) { loopi(6) if(c.texture[i] == oldtex) c.texture[i] = newtex; if(c.children) loopi(8) replacetexcube(c.children[i], oldtex, newtex); } void mpreplacetex(int oldtex, int newtex, bool insel, selinfo &sel, bool local) { if(local) game::edittrigger(sel, EDIT_REPLACE, oldtex, newtex, insel ? 1 : 0); if(insel) { loopselxyz(replacetexcube(c, oldtex, newtex)); } else { loopi(8) replacetexcube(worldroot[i], oldtex, newtex); } allchanged(); } void replace(bool insel) { if(noedit()) return; if(reptex < 0) { conoutf(CON_ERROR, "can only replace after a texture edit"); return; } mpreplacetex(reptex, lasttex, insel, sel, true); } ICOMMAND(replace, "", (), replace(false)); ICOMMAND(replacesel, "", (), replace(true)); ////////// flip and rotate /////////////// uint dflip(uint face) { return face==F_EMPTY ? face : 0x88888888 - (((face&0xF0F0F0F0)>>4) | ((face&0x0F0F0F0F)<<4)); } uint cflip(uint face) { return ((face&0xFF00FF00)>>8) | ((face&0x00FF00FF)<<8); } uint rflip(uint face) { return ((face&0xFFFF0000)>>16)| ((face&0x0000FFFF)<<16); } uint mflip(uint face) { return (face&0xFF0000FF) | ((face&0x00FF0000)>>8) | ((face&0x0000FF00)<<8); } void flipcube(cube &c, int d) { swap(c.texture[d*2], c.texture[d*2+1]); c.faces[D[d]] = dflip(c.faces[D[d]]); c.faces[C[d]] = cflip(c.faces[C[d]]); c.faces[R[d]] = rflip(c.faces[R[d]]); if(c.children) { loopi(8) if(i&octadim(d)) swap(c.children[i], c.children[i-octadim(d)]); loopi(8) flipcube(c.children[i], d); } } void rotatequad(cube &a, cube &b, cube &c, cube &d) { cube t = a; a = b; b = c; c = d; d = t; } void rotatecube(cube &c, int d) // rotates cube clockwise. see pics in cvs for help. { c.faces[D[d]] = cflip (mflip(c.faces[D[d]])); c.faces[C[d]] = dflip (mflip(c.faces[C[d]])); c.faces[R[d]] = rflip (mflip(c.faces[R[d]])); swap(c.faces[R[d]], c.faces[C[d]]); swap(c.texture[2*R[d]], c.texture[2*C[d]+1]); swap(c.texture[2*C[d]], c.texture[2*R[d]+1]); swap(c.texture[2*C[d]], c.texture[2*C[d]+1]); if(c.children) { int row = octadim(R[d]); int col = octadim(C[d]); for(int i=0; i<=octadim(d); i+=octadim(d)) rotatequad ( c.children[i+row], c.children[i], c.children[i+col], c.children[i+col+row] ); loopi(8) rotatecube(c.children[i], d); } } void mpflip(selinfo &sel, bool local) { if(local) { game::edittrigger(sel, EDIT_FLIP); makeundo(); } int zs = sel.s[dimension(sel.orient)]; loopxy(sel) { loop(z,zs) flipcube(selcube(x, y, z), dimension(sel.orient)); loop(z,zs/2) { cube &a = selcube(x, y, z); cube &b = selcube(x, y, zs-z-1); swap(a, b); } } changed(sel); } void flip() { if(noedit()) return; mpflip(sel, true); } void mprotate(int cw, selinfo &sel, bool local) { if(local) { game::edittrigger(sel, EDIT_ROTATE, cw); makeundo(); } int d = dimension(sel.orient); if(!dimcoord(sel.orient)) cw = -cw; int m = sel.s[C[d]] < sel.s[R[d]] ? C[d] : R[d]; int ss = sel.s[m] = max(sel.s[R[d]], sel.s[C[d]]); loop(z,sel.s[D[d]]) loopi(cw>0 ? 1 : 3) { loopxy(sel) rotatecube(selcube(x,y,z), d); loop(y,ss/2) loop(x,ss-1-y*2) rotatequad ( selcube(ss-1-y, x+y, z), selcube(x+y, y, z), selcube(y, ss-1-x-y, z), selcube(ss-1-x-y, ss-1-y, z) ); } changed(sel); } void rotate(int *cw) { if(noedit()) return; mprotate(*cw, sel, true); } COMMAND(flip, ""); COMMAND(rotate, "i"); enum { EDITMATF_EMPTY = 0x10000, EDITMATF_NOTEMPTY = 0x20000, EDITMATF_SOLID = 0x30000, EDITMATF_NOTSOLID = 0x40000 }; static const struct { const char *name; int filter; } editmatfilters[] = { { "empty", EDITMATF_EMPTY }, { "notempty", EDITMATF_NOTEMPTY }, { "solid", EDITMATF_SOLID }, { "notsolid", EDITMATF_NOTSOLID } }; void setmat(cube &c, ushort mat, ushort matmask, ushort filtermat, ushort filtermask, int filtergeom) { if(c.children) loopi(8) setmat(c.children[i], mat, matmask, filtermat, filtermask, filtergeom); else if((c.material&filtermask) == filtermat) { switch(filtergeom) { case EDITMATF_EMPTY: if(isempty(c)) break; return; case EDITMATF_NOTEMPTY: if(!isempty(c)) break; return; case EDITMATF_SOLID: if(isentirelysolid(c)) break; return; case EDITMATF_NOTSOLID: if(!isentirelysolid(c)) break; return; } if(mat!=MAT_AIR) { c.material &= matmask; c.material |= mat; } else c.material = MAT_AIR; } } void mpeditmat(int matid, int filter, selinfo &sel, bool local) { if(local) game::edittrigger(sel, EDIT_MAT, matid, filter); ushort filtermat = 0, filtermask = 0, matmask; int filtergeom = 0; if(filter >= 0) { filtermat = filter&0xFFFF; filtermask = filtermat&(MATF_VOLUME|MATF_INDEX) ? MATF_VOLUME|MATF_INDEX : (filtermat&MATF_CLIP ? MATF_CLIP : filtermat); filtergeom = filter&~0xFFFF; } if(matid < 0) { matid = 0; matmask = filtermask; if(isclipped(filtermat&MATF_VOLUME)) matmask &= ~MATF_CLIP; if(isdeadly(filtermat&MATF_VOLUME)) matmask &= ~MAT_DEATH; } else { matmask = matid&(MATF_VOLUME|MATF_INDEX) ? 0 : (matid&MATF_CLIP ? ~MATF_CLIP : ~matid); if(isclipped(matid&MATF_VOLUME)) matid |= MAT_CLIP; if(isdeadly(matid&MATF_VOLUME)) matid |= MAT_DEATH; } loopselxyz(setmat(c, matid, matmask, filtermat, filtermask, filtergeom)); } void editmat(char *name, char *filtername) { if(noedit()) return; int filter = -1; if(filtername[0]) { loopi(sizeof(editmatfilters)/sizeof(editmatfilters[0])) if(!strcmp(editmatfilters[i].name, filtername)) { filter = editmatfilters[i].filter; break; } if(filter < 0) filter = findmaterial(filtername); if(filter < 0) { conoutf(CON_ERROR, "unknown material \"%s\"", filtername); return; } } int id = -1; if(name[0] || filter < 0) { id = findmaterial(name); if(id<0) { conoutf(CON_ERROR, "unknown material \"%s\"", name); return; } } mpeditmat(id, filter, sel, true); } COMMAND(editmat, "ss"); extern int menudistance, menuautoclose; VARP(texguiwidth, 1, 12, 1000); VARP(texguiheight, 1, 8, 1000); VARP(texguitime, 0, 25, 1000); static int lastthumbnail = 0; VARP(texgui2d, 0, 1, 1); struct texturegui : g3d_callback { bool menuon; vec menupos; int menustart, menutab; texturegui() : menustart(-1) {} void gui(g3d_gui &g, bool firstpass) { int origtab = menutab, numtabs = max((slots.length() + texguiwidth*texguiheight - 1)/(texguiwidth*texguiheight), 1); g.start(menustart, 0.04f, &menutab); loopi(numtabs) { g.tab(!i ? "Textures" : NULL, 0xAAFFAA); if(i+1 != origtab) continue; //don't load textures on non-visible tabs! loop(h, texguiheight) { g.pushlist(); loop(w, texguiwidth) { extern VSlot dummyvslot; int ti = (i*texguiheight+h)*texguiwidth+w; if(tiindex, 0, slots.length()-1)/(texguiwidth*texguiheight); menupos = menuinfrontofplayer(); menustart = starttime(); } } void show() { if(!menuon) return; filltexlist(); extern int usegui2d; if(!editmode || ((!texgui2d || !usegui2d) && camera1->o.dist(menupos) > menuautoclose)) menuon = false; else g3d_addgui(this, menupos, texgui2d ? GUI_2D : 0); } } gui; void g3d_texturemenu() { gui.show(); } void showtexgui(int *n) { if(!editmode) { conoutf(CON_ERROR, "operation only allowed in edit mode"); return; } gui.showtextures(*n==0 ? !gui.menuon : *n==1); } // 0/noargs = toggle, 1 = on, other = off - will autoclose if too far away or exit editmode COMMAND(showtexgui, "i"); void rendertexturepanel(int w, int h) { if((texpaneltimer -= curtime)>0 && editmode) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); glScalef(h/1800.0f, h/1800.0f, 1); int y = 50, gap = 10; SETSHADER(rgbonly); loopi(7) { int s = (i == 3 ? 285 : 220), ti = curtexindex+i-3; if(ti>=0 && tislot->sts.empty() ? notexture : layer->slot->sts[0].t; } float sx = min(1.0f, tex->xs/(float)tex->ys), sy = min(1.0f, tex->ys/(float)tex->xs); int x = w*1800/h-s-50, r = s; float tc[4][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }; float xoff = vslot.xoffset, yoff = vslot.yoffset; if(vslot.rotation) { if((vslot.rotation&5) == 1) { swap(xoff, yoff); loopk(4) swap(tc[k][0], tc[k][1]); } if(vslot.rotation >= 2 && vslot.rotation <= 4) { xoff *= -1; loopk(4) tc[k][0] *= -1; } if(vslot.rotation <= 2 || vslot.rotation == 5) { yoff *= -1; loopk(4) tc[k][1] *= -1; } } loopk(4) { tc[k][0] = tc[k][0]/sx - xoff/tex->xs; tc[k][1] = tc[k][1]/sy - yoff/tex->ys; } glBindTexture(GL_TEXTURE_2D, tex->id); loopj(glowtex ? 3 : 2) { if(j < 2) glColor4f(j*vslot.colorscale.x, j*vslot.colorscale.y, j*vslot.colorscale.z, texpaneltimer/1000.0f); else { glBindTexture(GL_TEXTURE_2D, glowtex->id); glBlendFunc(GL_SRC_ALPHA, GL_ONE); glColor4f(vslot.glowcolor.x, vslot.glowcolor.y, vslot.glowcolor.z, texpaneltimer/1000.0f); } glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(x, y); glTexCoord2fv(tc[1]); glVertex2f(x+r, y); glTexCoord2fv(tc[3]); glVertex2f(x, y+r); glTexCoord2fv(tc[2]); glVertex2f(x+r, y+r); glEnd(); xtraverts += 4; if(j==1 && layertex) { glColor4f(layer->colorscale.x, layer->colorscale.y, layer->colorscale.z, texpaneltimer/1000.0f); glBindTexture(GL_TEXTURE_2D, layertex->id); glBegin(GL_TRIANGLE_STRIP); glTexCoord2fv(tc[0]); glVertex2f(x+r/2, y+r/2); glTexCoord2fv(tc[1]); glVertex2f(x+r, y+r/2); glTexCoord2fv(tc[3]); glVertex2f(x+r/2, y+r); glTexCoord2fv(tc[2]); glVertex2f(x+r, y+r); glEnd(); xtraverts += 4; } if(!j) { r -= 10; x += 5; y += 5; } else if(j == 2) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } y += s+gap; } defaultshader->set(); glPopMatrix(); } } sauerbraten-0.0.20130203.dfsg/engine/lensflare.h0000644000175000017500000001420711755225303020775 0ustar vincentvincentstatic struct flaretype { int type; /* flaretex index, 0..5, -1 for 6+random shine */ float loc; /* postion on axis */ float scale; /* texture scaling */ uchar alpha; /* color alpha */ } flaretypes[] = { {2, 1.30f, 0.04f, 153}, //flares {3, 1.00f, 0.10f, 102}, {1, 0.50f, 0.20f, 77}, {3, 0.20f, 0.05f, 77}, {0, 0.00f, 0.04f, 77}, {5, -0.25f, 0.07f, 127}, {5, -0.40f, 0.02f, 153}, {5, -0.60f, 0.04f, 102}, {5, -1.00f, 0.03f, 51}, {-1, 1.00f, 0.30f, 255}, //shine - red, green, blue {-2, 1.00f, 0.20f, 255}, {-3, 1.00f, 0.25f, 255} }; struct flare { vec o, center; float size; uchar color[3]; bool sparkle; }; VAR(flarelights, 0, 0, 1); VARP(flarecutoff, 0, 1000, 10000); VARP(flaresize, 20, 100, 500); struct flarerenderer : partrenderer { int maxflares, numflares; unsigned int shinetime; flare *flares; flarerenderer(const char *texname, int maxflares) : partrenderer(texname, 3, PT_FLARE), maxflares(maxflares), shinetime(0) { flares = new flare[maxflares]; } void reset() { numflares = 0; } void newflare(vec &o, const vec ¢er, uchar r, uchar g, uchar b, float mod, float size, bool sun, bool sparkle) { if(numflares >= maxflares) return; vec target; //occlusion check (neccessary as depth testing is turned off) if(!raycubelos(o, camera1->o, target)) return; flare &f = flares[numflares++]; f.o = o; f.center = center; f.size = size; f.color[0] = uchar(r*mod); f.color[1] = uchar(g*mod); f.color[2] = uchar(b*mod); f.sparkle = sparkle; } void addflare(vec &o, uchar r, uchar g, uchar b, bool sun, bool sparkle) { //frustrum + fog check if(isvisiblesphere(0.0f, o) > (sun?VFC_FOGGED:VFC_FULL_VISIBLE)) return; //find closest point between camera line of sight and flare pos vec flaredir = vec(o).sub(camera1->o); vec center = vec(camdir).mul(flaredir.dot(camdir)).add(camera1->o); float mod, size; if(sun) //fixed size { mod = 1.0; size = flaredir.magnitude() * flaresize / 100.0f; } else { mod = (flarecutoff-vec(o).sub(center).squaredlen())/flarecutoff; if(mod < 0.0f) return; size = flaresize / 5.0f; } newflare(o, center, r, g, b, mod, size, sun, sparkle); } void makelightflares() { numflares = 0; //regenerate flarelist each frame shinetime = lastmillis/10; if(editmode || !flarelights) return; const vector &ents = entities::getents(); extern const vector &checklightcache(int x, int y); const vector &lights = checklightcache(int(camera1->o.x), int(camera1->o.y)); loopv(lights) { entity &e = *ents[lights[i]]; if(e.type != ET_LIGHT) continue; bool sun = (e.attr1==0); float radius = float(e.attr1); vec flaredir = vec(e.o).sub(camera1->o); float len = flaredir.magnitude(); if(!sun && (len > radius)) continue; if(isvisiblesphere(0.0f, e.o) > (sun?VFC_FOGGED:VFC_FULL_VISIBLE)) continue; vec center = vec(camdir).mul(flaredir.dot(camdir)).add(camera1->o); float mod, size; if(sun) //fixed size { mod = 1.0; size = len * flaresize / 100.0f; } else { mod = (radius-len)/radius; size = flaresize / 5.0f; } newflare(e.o, center, e.attr2, e.attr3, e.attr4, mod, size, sun, sun); } } int count() { return numflares; } bool haswork() { return (numflares != 0) && !glaring && !reflecting && !refracting; } void render() { glDisable(GL_FOG); defaultshader->set(); glDisable(GL_DEPTH_TEST); if(!tex) tex = textureload(texname); glBindTexture(GL_TEXTURE_2D, tex->id); glBegin(GL_QUADS); loopi(numflares) { flare *f = flares+i; vec center = f->center; vec axis = vec(f->o).sub(center); uchar color[4] = {f->color[0], f->color[1], f->color[2], 255}; loopj(f->sparkle?12:9) { const flaretype &ft = flaretypes[j]; vec o = vec(axis).mul(ft.loc).add(center); float sz = ft.scale * f->size; int tex = ft.type; if(ft.type < 0) //sparkles - always done last { shinetime = (shinetime + 1) % 10; tex = 6+shinetime; color[0] = 0; color[1] = 0; color[2] = 0; color[-ft.type-1] = f->color[-ft.type-1]; //only want a single channel } color[3] = ft.alpha; glColor4ubv(color); const float tsz = 0.25; //flares are aranged in 4x4 grid float tx = tsz*(tex&0x03); float ty = tsz*((tex>>2)&0x03); glTexCoord2f(tx, ty+tsz); glVertex3f(o.x+(-camright.x+camup.x)*sz, o.y+(-camright.y+camup.y)*sz, o.z+(-camright.z+camup.z)*sz); glTexCoord2f(tx+tsz, ty+tsz); glVertex3f(o.x+( camright.x+camup.x)*sz, o.y+( camright.y+camup.y)*sz, o.z+( camright.z+camup.z)*sz); glTexCoord2f(tx+tsz, ty); glVertex3f(o.x+( camright.x-camup.x)*sz, o.y+( camright.y-camup.y)*sz, o.z+( camright.z-camup.z)*sz); glTexCoord2f(tx, ty); glVertex3f(o.x+(-camright.x-camup.x)*sz, o.y+(-camright.y-camup.y)*sz, o.z+(-camright.z-camup.z)*sz); } } glEnd(); glEnable(GL_DEPTH_TEST); glEnable(GL_FOG); } //square per round hole - use addflare(..) instead particle *addpart(const vec &o, const vec &d, int fade, int color, float size, int gravity = 0) { return NULL; } }; static flarerenderer flares("packages/particles/lensflares.png", 64); sauerbraten-0.0.20130203.dfsg/engine/vertmodel.h0000644000175000017500000006022112077017136021021 0ustar vincentvincentstruct vertmodel : animmodel { struct vert { vec pos, norm; }; struct vvertff { vec pos; float u, v; }; struct vvert : vvertff { vec norm; }; struct vvertbump : vvert { vec tangent; float bitangent; }; struct tcvert { float u, v; }; struct bumpvert { vec tangent; float bitangent; }; struct tri { ushort vert[3]; }; struct vbocacheentry { uchar *vdata; GLuint vbuf; animstate as; int millis; vbocacheentry() : vdata(NULL), vbuf(0) { as.cur.fr1 = as.prev.fr1 = -1; } }; struct vertmesh : mesh { vert *verts; tcvert *tcverts; bumpvert *bumpverts; tri *tris; int numverts, numtris; int voffset, eoffset, elen; ushort minvert, maxvert; vertmesh() : verts(0), tcverts(0), bumpverts(0), tris(0) { } virtual ~vertmesh() { DELETEA(verts); DELETEA(tcverts); DELETEA(bumpverts); DELETEA(tris); } void smoothnorms(float limit = 0, bool areaweight = true) { if(((vertmeshgroup *)group)->numframes != 1) { buildnorms(areaweight); return; } mesh::smoothnorms(verts, numverts, tris, numtris, limit, areaweight); } void buildnorms(bool areaweight = true) { loopk(((vertmeshgroup *)group)->numframes) mesh::buildnorms(&verts[k*numverts], numverts, tris, numtris, areaweight); } void calctangents(bool areaweight = true) { if(bumpverts) return; bumpverts = new bumpvert[((vertmeshgroup *)group)->numframes*numverts]; loopk(((vertmeshgroup *)group)->numframes) mesh::calctangents(&bumpverts[k*numverts], &verts[k*numverts], tcverts, numverts, tris, numtris, areaweight); } void calcbb(int frame, vec &bbmin, vec &bbmax, const matrix3x4 &m) { vert *fverts = &verts[frame*numverts]; loopj(numverts) { vec v = m.transform(fverts[j].pos); loopi(3) { bbmin[i] = min(bbmin[i], v[i]); bbmax[i] = max(bbmax[i], v[i]); } } } void gentris(int frame, Texture *tex, vector *out, const matrix3x4 &m) { vert *fverts = &verts[frame*numverts]; loopj(numtris) { BIH::tri &t = out[noclip ? 1 : 0].add(); t.tex = tex; t.a = m.transform(fverts[tris[j].vert[0]].pos); t.b = m.transform(fverts[tris[j].vert[1]].pos); t.c = m.transform(fverts[tris[j].vert[2]].pos); tcvert &av = tcverts[tris[j].vert[0]], &bv = tcverts[tris[j].vert[1]], &cv = tcverts[tris[j].vert[2]]; t.tc[0] = av.u; t.tc[1] = av.v; t.tc[2] = bv.u; t.tc[3] = bv.v; t.tc[4] = cv.u; t.tc[5] = cv.v; } } static inline bool comparevert(vvertff &w, int j, tcvert &tc, vert &v) { return tc.u==w.u && tc.v==w.v && v.pos==w.pos; } static inline bool comparevert(vvert &w, int j, tcvert &tc, vert &v) { return tc.u==w.u && tc.v==w.v && v.pos==w.pos && v.norm==w.norm; } inline bool comparevert(vvertbump &w, int j, tcvert &tc, vert &v) { return tc.u==w.u && tc.v==w.v && v.pos==w.pos && v.norm==w.norm && (!bumpverts || (bumpverts[j].tangent==w.tangent && bumpverts[j].bitangent==w.bitangent)); } static inline void assignvert(vvertff &vv, int j, tcvert &tc, vert &v) { vv.pos = v.pos; vv.u = tc.u; vv.v = tc.v; } static inline void assignvert(vvert &vv, int j, tcvert &tc, vert &v) { vv.pos = v.pos; vv.norm = v.norm; vv.u = tc.u; vv.v = tc.v; } inline void assignvert(vvertbump &vv, int j, tcvert &tc, vert &v) { vv.pos = v.pos; vv.norm = v.norm; vv.u = tc.u; vv.v = tc.v; if(bumpverts) { vv.tangent = bumpverts[j].tangent; vv.bitangent = bumpverts[j].bitangent; } } template int genvbo(vector &idxs, int offset, vector &vverts, int *htdata, int htlen) { voffset = offset; eoffset = idxs.length(); minvert = 0xFFFF; loopi(numtris) { tri &t = tris[i]; loopj(3) { int index = t.vert[j]; tcvert &tc = tcverts[index]; vert &v = verts[index]; int htidx = hthash(v.pos)&(htlen-1); loopk(htlen) { int &vidx = htdata[(htidx+k)&(htlen-1)]; if(vidx < 0) { vidx = idxs.add(ushort(vverts.length())); assignvert(vverts.add(), index, tc, v); break; } else if(comparevert(vverts[vidx], index, tc, v)) { minvert = min(minvert, idxs.add(ushort(vidx))); break; } } } } minvert = min(minvert, ushort(voffset)); maxvert = max(minvert, ushort(vverts.length()-1)); elen = idxs.length()-eoffset; return vverts.length()-voffset; } int genvbo(vector &idxs, int offset) { voffset = offset; eoffset = idxs.length(); loopi(numtris) { tri &t = tris[i]; loopj(3) idxs.add(voffset+t.vert[j]); } minvert = voffset; maxvert = voffset + numverts-1; elen = idxs.length()-eoffset; return numverts; } void filltc(uchar *vdata, size_t stride) { vdata = (uchar *)&((vvertff *)&vdata[voffset*stride])->u; loopi(numverts) { *(tcvert *)vdata = tcverts[i]; vdata += stride; } } void interpverts(const animstate &as, bool norms, bool tangents, void * RESTRICT vdata, skin &s) { const vert * RESTRICT vert1 = &verts[as.cur.fr1 * numverts], * RESTRICT vert2 = &verts[as.cur.fr2 * numverts], * RESTRICT pvert1 = as.interp<1 ? &verts[as.prev.fr1 * numverts] : NULL, * RESTRICT pvert2 = as.interp<1 ? &verts[as.prev.fr2 * numverts] : NULL; #define ipvert(attrib) v.attrib.lerp(vert1[i].attrib, vert2[i].attrib, as.cur.t) #define ipbvert(attrib) v.attrib.lerp(bvert1[i].attrib, bvert2[i].attrib, as.cur.t) #define ipvertp(attrib) v.attrib.lerp(pvert1[i].attrib, pvert2[i].attrib, as.prev.t).lerp(vec().lerp(vert1[i].attrib, vert2[i].attrib, as.cur.t), as.interp) #define ipbvertp(attrib) v.attrib.lerp(bpvert1[i].attrib, bpvert2[i].attrib, as.prev.t).lerp(vec().lerp(bvert1[i].attrib, bvert2[i].attrib, as.cur.t), as.interp) #define iploop(type, body) \ loopi(numverts) \ { \ type &v = ((type * RESTRICT)vdata)[i]; \ body; \ } if(tangents) { const bumpvert * RESTRICT bvert1 = &bumpverts[as.cur.fr1 * numverts], * RESTRICT bvert2 = &bumpverts[as.cur.fr2 * numverts], * RESTRICT bpvert1 = as.interp<1 ? &bumpverts[as.prev.fr1 * numverts] : NULL, * RESTRICT bpvert2 = as.interp<1 ? &bumpverts[as.prev.fr2 * numverts] : NULL; if(as.interp<1) iploop(vvertbump, { ipvertp(pos); ipvertp(norm); ipbvertp(tangent); v.bitangent = bvert1[i].bitangent; }) else iploop(vvertbump, { ipvert(pos); ipvert(norm); ipbvert(tangent); v.bitangent = bvert1[i].bitangent; }) } else if(norms) { if(as.interp<1) iploop(vvert, { ipvertp(pos); ipvertp(norm); }) else iploop(vvert, { ipvert(pos); ipvert(norm); }) } else if(as.interp<1) iploop(vvertff, ipvertp(pos)) else iploop(vvertff, ipvert(pos)) #undef iploop #undef ipvert #undef ipbvert #undef ipvertp #undef ipbvertp } void render(const animstate *as, skin &s, vbocacheentry &vc) { if(!(as->cur.anim&ANIM_NOSKIN)) { if(s.multitextured()) { if(!enablemtc || lastmtcbuf!=lastvbuf) { glClientActiveTexture_(GL_TEXTURE1_ARB); if(!enablemtc) glEnableClientState(GL_TEXTURE_COORD_ARRAY); if(lastmtcbuf!=lastvbuf) { vvertff *vverts = hasVBO ? 0 : (vvertff *)vc.vdata; glTexCoordPointer(2, GL_FLOAT, ((vertmeshgroup *)group)->vertsize, &vverts->u); } glClientActiveTexture_(GL_TEXTURE0_ARB); lastmtcbuf = lastvbuf; enablemtc = true; } } else if(enablemtc) disablemtc(); if(s.tangents()) { if(!enabletangents || lastxbuf!=lastvbuf) { if(!enabletangents) glEnableVertexAttribArray_(1); if(lastxbuf!=lastvbuf) { vvertbump *vverts = hasVBO ? 0 : (vvertbump *)vc.vdata; glVertexAttribPointer_(1, 4, GL_FLOAT, GL_FALSE, ((vertmeshgroup *)group)->vertsize, &vverts->tangent.x); } lastxbuf = lastvbuf; enabletangents = true; } } else if(enabletangents) disabletangents(); if(renderpath==R_FIXEDFUNCTION && (s.scrollu || s.scrollv)) { glMatrixMode(GL_TEXTURE); glPushMatrix(); glTranslatef(s.scrollu*lastmillis/1000.0f, s.scrollv*lastmillis/1000.0f, 0); if(s.multitextured()) { glActiveTexture_(GL_TEXTURE1_ARB); glPushMatrix(); glTranslatef(s.scrollu*lastmillis/1000.0f, s.scrollv*lastmillis/1000.0f, 0); } } } if(hasDRE) glDrawRangeElements_(GL_TRIANGLES, minvert, maxvert, elen, GL_UNSIGNED_SHORT, &((vertmeshgroup *)group)->edata[eoffset]); else glDrawElements(GL_TRIANGLES, elen, GL_UNSIGNED_SHORT, &((vertmeshgroup *)group)->edata[eoffset]); glde++; xtravertsva += numverts; if(renderpath==R_FIXEDFUNCTION && !(as->cur.anim&ANIM_NOSKIN) && (s.scrollu || s.scrollv)) { if(s.multitextured()) { glPopMatrix(); glActiveTexture_(GL_TEXTURE0_ARB); } glPopMatrix(); glMatrixMode(GL_MODELVIEW); } return; } }; struct tag { char *name; matrix3x4 transform; tag() : name(NULL) {} ~tag() { DELETEA(name); } }; struct vertmeshgroup : meshgroup { int numframes; tag *tags; int numtags; static const int MAXVBOCACHE = 16; vbocacheentry vbocache[MAXVBOCACHE]; ushort *edata; GLuint ebuf; bool vnorms, vtangents; int vlen, vertsize; uchar *vdata; vertmeshgroup() : numframes(0), tags(NULL), numtags(0), edata(NULL), ebuf(0), vnorms(false), vtangents(false), vlen(0), vertsize(0), vdata(NULL) { } virtual ~vertmeshgroup() { DELETEA(tags); if(ebuf) glDeleteBuffers_(1, &ebuf); loopi(MAXVBOCACHE) { DELETEA(vbocache[i].vdata); if(vbocache[i].vbuf) glDeleteBuffers_(1, &vbocache[i].vbuf); } DELETEA(vdata); } int findtag(const char *name) { loopi(numtags) if(!strcmp(tags[i].name, name)) return i; return -1; } int totalframes() const { return numframes; } void concattagtransform(part *p, int frame, int i, const matrix3x4 &m, matrix3x4 &n) { n.mul(m, tags[frame*numtags + i].transform); n.translate(m.transformnormal(p->translate).mul(p->model->scale)); } void calctagmatrix(part *p, int i, const animstate &as, glmatrixf &matrix) { const matrix3x4 &tag1 = tags[as.cur.fr1*numtags + i].transform, &tag2 = tags[as.cur.fr2*numtags + i].transform; matrix3x4 tag; tag.lerp(tag1, tag2, as.cur.t); if(as.interp<1) { const matrix3x4 &tag1p = tags[as.prev.fr1*numtags + i].transform, &tag2p = tags[as.prev.fr2*numtags + i].transform; matrix3x4 tagp; tagp.lerp(tag1p, tag2p, as.prev.t); tag.lerp(tagp, tag, as.interp); } matrix = glmatrixf(tag); matrix[12] = (matrix[12] + p->translate.x) * p->model->scale; matrix[13] = (matrix[13] + p->translate.y) * p->model->scale; matrix[14] = (matrix[14] + p->translate.z) * p->model->scale; } void genvbo(bool norms, bool tangents, vbocacheentry &vc) { if(hasVBO) { if(!vc.vbuf) glGenBuffers_(1, &vc.vbuf); if(ebuf) return; } else if(edata) { #define ALLOCVDATA(vdata) \ do \ { \ DELETEA(vdata); \ vdata = new uchar[vlen*vertsize]; \ loopv(meshes) ((vertmesh *)meshes[i])->filltc(vdata, vertsize); \ } while(0) if(!vc.vdata) ALLOCVDATA(vc.vdata); return; } vector idxs; vnorms = norms; vtangents = tangents; vertsize = tangents ? sizeof(vvertbump) : (norms ? sizeof(vvert) : sizeof(vvertff)); vlen = 0; if(numframes>1) { loopv(meshes) vlen += ((vertmesh *)meshes[i])->genvbo(idxs, vlen); DELETEA(vdata); if(hasVBO) ALLOCVDATA(vdata); else ALLOCVDATA(vc.vdata); } else { if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, vc.vbuf); #define GENVBO(type) \ do \ { \ vector vverts; \ loopv(meshes) vlen += ((vertmesh *)meshes[i])->genvbo(idxs, vlen, vverts, htdata, htlen); \ if(hasVBO) glBufferData_(GL_ARRAY_BUFFER_ARB, vverts.length()*sizeof(type), vverts.getbuf(), GL_STATIC_DRAW_ARB); \ else \ { \ DELETEA(vc.vdata); \ vc.vdata = new uchar[vverts.length()*sizeof(type)]; \ memcpy(vc.vdata, vverts.getbuf(), vverts.length()*sizeof(type)); \ } \ } while(0) int numverts = 0, htlen = 128; loopv(meshes) numverts += ((vertmesh *)meshes[i])->numverts; while(htlen < numverts) htlen *= 2; if(numverts*4 > htlen*3) htlen *= 2; int *htdata = new int[htlen]; memset(htdata, -1, htlen*sizeof(int)); if(tangents) GENVBO(vvertbump); else if(norms) GENVBO(vvert); else GENVBO(vvertff); delete[] htdata; if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); } if(hasVBO) { glGenBuffers_(1, &ebuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, ebuf); glBufferData_(GL_ELEMENT_ARRAY_BUFFER_ARB, idxs.length()*sizeof(ushort), idxs.getbuf(), GL_STATIC_DRAW_ARB); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } else { edata = new ushort[idxs.length()]; memcpy(edata, idxs.getbuf(), idxs.length()*sizeof(ushort)); } #undef GENVBO #undef ALLOCVDATA } void bindvbo(const animstate *as, vbocacheentry &vc) { vvert *vverts = hasVBO ? 0 : (vvert *)vc.vdata; if(hasVBO && lastebuf!=ebuf) { glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, ebuf); lastebuf = ebuf; } if(lastvbuf != (hasVBO ? (void *)(size_t)vc.vbuf : vc.vdata)) { if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, vc.vbuf); if(!lastvbuf) glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, vertsize, &vverts->pos); lastvbuf = hasVBO ? (void *)(size_t)vc.vbuf : vc.vdata; } if(as->cur.anim&ANIM_NOSKIN) { if(enabletc) disabletc(); if(enablenormals) disablenormals(); } else { if(vnorms || vtangents) { if(!enablenormals) { glEnableClientState(GL_NORMAL_ARRAY); enablenormals = true; } if(lastnbuf!=lastvbuf) { glNormalPointer(GL_FLOAT, vertsize, &vverts->norm); lastnbuf = lastvbuf; } } else if(enablenormals) disablenormals(); if(!enabletc) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); enabletc = true; } if(lasttcbuf!=lastvbuf) { glTexCoordPointer(2, GL_FLOAT, vertsize, &vverts->u); lasttcbuf = lastvbuf; } } if(enablebones) disablebones(); } void cleanup() { loopi(MAXVBOCACHE) { vbocacheentry &c = vbocache[i]; if(c.vbuf) { glDeleteBuffers_(1, &c.vbuf); c.vbuf = 0; } DELETEA(c.vdata); c.as.cur.fr1 = -1; } if(hasVBO) { if(ebuf) { glDeleteBuffers_(1, &ebuf); ebuf = 0; } } else DELETEA(vdata); } void preload(part *p) { if(numframes > 1) return; bool norms = false, tangents = false; loopv(p->skins) { if(p->skins[i].normals()) norms = true; if(p->skins[i].tangents()) tangents = true; } if(norms!=vnorms || tangents!=vtangents) cleanup(); if(hasVBO ? !vbocache->vbuf : !vbocache->vdata) genvbo(norms, tangents, *vbocache); } void render(const animstate *as, float pitch, const vec &axis, const vec &forward, dynent *d, part *p) { if(as->cur.anim&ANIM_NORENDER) { loopv(p->links) calctagmatrix(p, p->links[i].tag, *as, p->links[i].matrix); return; } bool norms = false, tangents = false; loopv(p->skins) { if(p->skins[i].normals()) norms = true; if(p->skins[i].tangents()) tangents = true; } if(norms!=vnorms || tangents!=vtangents) { cleanup(); disablevbo(); } vbocacheentry *vc = NULL; if(numframes<=1) vc = vbocache; else { loopi(MAXVBOCACHE) { vbocacheentry &c = vbocache[i]; if(hasVBO ? !c.vbuf : !c.vdata) continue; if(c.as==*as) { vc = &c; break; } } if(!vc) loopi(MAXVBOCACHE) { vc = &vbocache[i]; if((hasVBO ? !vc->vbuf : !vc->vdata) || vc->millis < lastmillis) break; } } if(hasVBO ? !vc->vbuf : !vc->vdata) genvbo(norms, tangents, *vc); if(numframes>1) { if(vc->as!=*as) { vc->as = *as; vc->millis = lastmillis; loopv(meshes) { vertmesh &m = *(vertmesh *)meshes[i]; m.interpverts(*as, norms, tangents, (hasVBO ? vdata : vc->vdata) + m.voffset*vertsize, p->skins[i]); } if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, vc->vbuf); glBufferData_(GL_ARRAY_BUFFER_ARB, vlen*vertsize, vdata, GL_STREAM_DRAW_ARB); } } vc->millis = lastmillis; } bindvbo(as, *vc); loopv(meshes) { vertmesh *m = (vertmesh *)meshes[i]; p->skins[i].bind(m, as); m->render(as, p->skins[i], *vc); } loopv(p->links) calctagmatrix(p, p->links[i].tag, *as, p->links[i].matrix); } }; vertmodel(const char *name) : animmodel(name) { } }; template struct vertloader : modelloader { }; template struct vertcommands : modelcommands { typedef struct MDL::part part; typedef struct MDL::skin skin; static void loadpart(char *model, float *smooth) { if(!MDL::loading) { conoutf("not loading an %s", MDL::formatname()); return; } defformatstring(filename)("%s/%s", MDL::dir, model); part &mdl = *new part; MDL::loading->parts.add(&mdl); mdl.model = MDL::loading; mdl.index = MDL::loading->parts.length()-1; if(mdl.index) mdl.pitchscale = mdl.pitchoffset = mdl.pitchmin = mdl.pitchmax = 0; mdl.meshes = MDL::loading->sharemeshes(path(filename), double(*smooth > 0 ? cos(clamp(*smooth, 0.0f, 180.0f)*RAD) : 2)); if(!mdl.meshes) conoutf("could not load %s", filename); else mdl.initskins(); } static void setpitch(float *pitchscale, float *pitchoffset, float *pitchmin, float *pitchmax) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } part &mdl = *MDL::loading->parts.last(); mdl.pitchscale = *pitchscale; mdl.pitchoffset = *pitchoffset; if(*pitchmin || *pitchmax) { mdl.pitchmin = *pitchmin; mdl.pitchmax = *pitchmax; } else { mdl.pitchmin = -360*fabs(mdl.pitchscale) + mdl.pitchoffset; mdl.pitchmax = 360*fabs(mdl.pitchscale) + mdl.pitchoffset; } } static void setanim(char *anim, int *frame, int *range, float *speed, int *priority) { if(!MDL::loading || MDL::loading->parts.empty()) { conoutf("not loading an %s", MDL::formatname()); return; } vector anims; findanims(anim, anims); if(anims.empty()) conoutf("could not find animation %s", anim); else loopv(anims) { MDL::loading->parts.last()->setanim(0, anims[i], *frame, *range, *speed, *priority); } } vertcommands() { if(MDL::multiparted()) this->modelcommand(loadpart, "load", "sf"); this->modelcommand(setpitch, "pitch", "ffff"); if(MDL::animated()) this->modelcommand(setanim, "anim", "siiff"); } }; sauerbraten-0.0.20130203.dfsg/engine/sound.cpp0000644000175000017500000005053112077011536020504 0ustar vincentvincent// sound.cpp: basic positional sound using sdl_mixer #include "engine.h" #include "SDL_mixer.h" #define MAXVOL MIX_MAX_VOLUME bool nosound = true; struct soundsample { char *name; Mix_Chunk *chunk; soundsample() : name(NULL), chunk(NULL) {} ~soundsample() { DELETEA(name); } void cleanup() { if(chunk) { Mix_FreeChunk(chunk); chunk = NULL; } } }; struct soundslot { soundsample *sample; int volume; }; struct soundconfig { int slots, numslots; int maxuses; bool hasslot(const soundslot *p, const vector &v) const { return p >= v.getbuf() + slots && p < v.getbuf() + slots+numslots && slots+numslots < v.length(); } int chooseslot() const { return numslots > 1 ? slots + rnd(numslots) : slots; } }; struct soundchannel { int id; bool inuse; vec loc; soundslot *slot; extentity *ent; int radius, volume, pan, flags; bool dirty; soundchannel(int id) : id(id) { reset(); } bool hasloc() const { return loc.x >= -1e15f; } void clearloc() { loc = vec(-1e16f, -1e16f, -1e16f); } void reset() { inuse = false; clearloc(); slot = NULL; ent = NULL; radius = 0; volume = -1; pan = -1; flags = 0; dirty = false; } }; vector channels; int maxchannels = 0; soundchannel &newchannel(int n, soundslot *slot, const vec *loc = NULL, extentity *ent = NULL, int flags = 0, int radius = 0) { if(ent) { loc = &ent->o; ent->visible = true; } while(!channels.inrange(n)) channels.add(channels.length()); soundchannel &chan = channels[n]; chan.reset(); chan.inuse = true; if(loc) chan.loc = *loc; chan.slot = slot; chan.ent = ent; chan.flags = 0; chan.radius = radius; return chan; } void freechannel(int n) { // Note that this can potentially be called from the SDL_mixer audio thread. // Be careful of race conditions when checking chan.inuse without locking audio. // Can't use Mix_Playing() checks due to bug with looping sounds in SDL_mixer. if(!channels.inrange(n) || !channels[n].inuse) return; soundchannel &chan = channels[n]; chan.inuse = false; if(chan.ent) chan.ent->visible = false; } void syncchannel(soundchannel &chan) { if(!chan.dirty) return; if(!Mix_FadingChannel(chan.id)) Mix_Volume(chan.id, chan.volume); Mix_SetPanning(chan.id, 255-chan.pan, chan.pan); chan.dirty = false; } void stopchannels() { loopv(channels) { soundchannel &chan = channels[i]; if(!chan.inuse) continue; Mix_HaltChannel(i); freechannel(i); } } void setmusicvol(int musicvol); VARFP(soundvol, 0, 255, 255, if(!soundvol) { stopchannels(); setmusicvol(0); }); VARFP(musicvol, 0, 128, 255, setmusicvol(soundvol ? musicvol : 0)); char *musicfile = NULL, *musicdonecmd = NULL; Mix_Music *music = NULL; SDL_RWops *musicrw = NULL; stream *musicstream = NULL; void setmusicvol(int musicvol) { if(nosound) return; if(music) Mix_VolumeMusic((musicvol*MAXVOL)/255); } void stopmusic() { if(nosound) return; DELETEA(musicfile); DELETEA(musicdonecmd); if(music) { Mix_HaltMusic(); Mix_FreeMusic(music); music = NULL; } if(musicrw) { SDL_FreeRW(musicrw); musicrw = NULL; } DELETEP(musicstream); } VARF(soundchans, 1, 32, 128, initwarning("sound configuration", INIT_RESET, CHANGE_SOUND)); VARF(soundfreq, 0, MIX_DEFAULT_FREQUENCY, 44100, initwarning("sound configuration", INIT_RESET, CHANGE_SOUND)); VARF(soundbufferlen, 128, 1024, 4096, initwarning("sound configuration", INIT_RESET, CHANGE_SOUND)); void initsound() { if(Mix_OpenAudio(soundfreq, MIX_DEFAULT_FORMAT, 2, soundbufferlen)<0) { nosound = true; conoutf(CON_ERROR, "sound init failed (SDL_mixer): %s", Mix_GetError()); return; } Mix_AllocateChannels(soundchans); Mix_ChannelFinished(freechannel); maxchannels = soundchans; nosound = false; } void musicdone() { if(music) { Mix_HaltMusic(); Mix_FreeMusic(music); music = NULL; } if(musicrw) { SDL_FreeRW(musicrw); musicrw = NULL; } DELETEP(musicstream); DELETEA(musicfile); if(!musicdonecmd) return; char *cmd = musicdonecmd; musicdonecmd = NULL; execute(cmd); delete[] cmd; } Mix_Music *loadmusic(const char *name) { if(!musicstream) musicstream = openzipfile(name, "rb"); if(musicstream) { if(!musicrw) musicrw = musicstream->rwops(); if(!musicrw) DELETEP(musicstream); } if(musicrw) music = Mix_LoadMUS_RW(musicrw); else music = Mix_LoadMUS(findfile(name, "rb")); if(!music) { if(musicrw) { SDL_FreeRW(musicrw); musicrw = NULL; } DELETEP(musicstream); } return music; } void startmusic(char *name, char *cmd) { if(nosound) return; stopmusic(); if(soundvol && musicvol && *name) { defformatstring(file)("packages/%s", name); path(file); if(loadmusic(file)) { DELETEA(musicfile); DELETEA(musicdonecmd); musicfile = newstring(file); if(cmd[0]) musicdonecmd = newstring(cmd); Mix_PlayMusic(music, cmd[0] ? 0 : -1); Mix_VolumeMusic((musicvol*MAXVOL)/255); intret(1); } else { conoutf(CON_ERROR, "could not play music: %s", file); intret(0); } } } COMMANDN(music, startmusic, "ss"); static hashtable samples; static vector gameslots, mapslots; static vector gamesounds, mapsounds; static int findsound(const char *name, int vol, vector &sounds, vector &slots) { loopv(sounds) { soundconfig &s = sounds[i]; loopj(s.numslots) { soundslot &c = slots[s.slots+j]; if(!strcmp(c.sample->name, name) && (!vol || c.volume==vol)) return i; } } return -1; } static int addslot(const char *name, int vol, vector &slots) { soundsample *s = samples.access(name); if(!s) { char *n = newstring(name); s = &samples[n]; s->name = n; s->chunk = NULL; } soundslot *oldslots = slots.getbuf(); int oldlen = slots.length(); soundslot &slot = slots.add(); // soundslots.add() may relocate slot pointers if(slots.getbuf() != oldslots) loopv(channels) { soundchannel &chan = channels[i]; if(chan.inuse && chan.slot >= oldslots && chan.slot < &oldslots[oldlen]) chan.slot = &slots[chan.slot - oldslots]; } slot.sample = s; slot.volume = vol ? vol : 100; return oldlen; } static int addsound(const char *name, int vol, int maxuses, vector &sounds, vector &slots) { soundconfig &s = sounds.add(); s.slots = addslot(name, vol, slots); s.numslots = 1; s.maxuses = maxuses; return sounds.length()-1; } void registersound(char *name, int *vol) { intret(addsound(name, *vol, 0, gamesounds, gameslots)); } COMMAND(registersound, "si"); void mapsound(char *name, int *vol, int *maxuses) { intret(addsound(name, *vol, *maxuses < 0 ? 0 : max(1, *maxuses), mapsounds, mapslots)); } COMMAND(mapsound, "sii"); void altsound(char *name, int *vol) { if(gamesounds.empty()) return; addslot(name, *vol, gameslots); gamesounds.last().numslots++; } COMMAND(altsound, "si"); void altmapsound(char *name, int *vol) { if(mapsounds.empty()) return; addslot(name, *vol, mapslots); mapsounds.last().numslots++; } COMMAND(altmapsound, "si"); void resetchannels() { loopv(channels) if(channels[i].inuse) freechannel(i); channels.shrink(0); } void clear_sound() { closemumble(); if(nosound) return; stopmusic(); enumerate(samples, soundsample, s, s.cleanup()); Mix_CloseAudio(); resetchannels(); gameslots.setsize(0); gamesounds.setsize(0); mapslots.setsize(0); mapsounds.setsize(0); samples.clear(); } void stopmapsounds() { loopv(channels) if(channels[i].inuse && channels[i].ent) { Mix_HaltChannel(i); freechannel(i); } } void clearmapsounds() { stopmapsounds(); mapslots.setsize(0); mapsounds.setsize(0); } void stopmapsound(extentity *e) { loopv(channels) { soundchannel &chan = channels[i]; if(chan.inuse && chan.ent == e) { Mix_HaltChannel(i); freechannel(i); } } } void checkmapsounds() { const vector &ents = entities::getents(); loopv(ents) { extentity &e = *ents[i]; if(e.type!=ET_SOUND) continue; if(camera1->o.dist(e.o) < e.attr2) { if(!e.visible) playsound(e.attr1, NULL, &e, SND_MAP, -1); } else if(e.visible) stopmapsound(&e); } } VAR(stereo, 0, 1, 1); VARP(maxsoundradius, 0, 340, 10000); bool updatechannel(soundchannel &chan) { if(!chan.slot) return false; int vol = soundvol, pan = 255/2; if(chan.hasloc()) { vec v; float dist = chan.loc.dist(camera1->o, v); int rad = maxsoundradius; if(chan.ent) { rad = chan.ent->attr2; if(chan.ent->attr3) { rad -= chan.ent->attr3; dist -= chan.ent->attr3; } } else if(chan.radius > 0) rad = maxsoundradius ? min(maxsoundradius, chan.radius) : chan.radius; if(rad > 0) vol -= int(clamp(dist/rad, 0.0f, 1.0f)*soundvol); // simple mono distance attenuation if(stereo && (v.x != 0 || v.y != 0) && dist>0) { v.rotate_around_z(-camera1->yaw*RAD); pan = int(255.9f*(0.5f - 0.5f*v.x/v.magnitude2())); // range is from 0 (left) to 255 (right) } } vol = (vol*MAXVOL*chan.slot->volume)/255/255; vol = min(vol, MAXVOL); if(vol == chan.volume && pan == chan.pan) return false; chan.volume = vol; chan.pan = pan; chan.dirty = true; return true; } void updatesounds() { updatemumble(); if(nosound) return; if(minimized) stopsounds(); else if(mainmenu) stopmapsounds(); else checkmapsounds(); int dirty = 0; loopv(channels) { soundchannel &chan = channels[i]; if(chan.inuse && chan.hasloc() && updatechannel(chan)) dirty++; } if(dirty) { SDL_LockAudio(); // workaround for race conditions inside Mix_SetPanning loopv(channels) { soundchannel &chan = channels[i]; if(chan.inuse && chan.dirty) syncchannel(chan); } SDL_UnlockAudio(); } if(music) { if(!Mix_PlayingMusic()) musicdone(); else if(Mix_PausedMusic()) Mix_ResumeMusic(); } } VARP(maxsoundsatonce, 0, 7, 100); VAR(dbgsound, 0, 0, 1); static Mix_Chunk *loadwav(const char *name) { Mix_Chunk *c = NULL; stream *z = openzipfile(name, "rb"); if(z) { SDL_RWops *rw = z->rwops(); if(rw) { c = Mix_LoadWAV_RW(rw, 0); SDL_FreeRW(rw); } delete z; } if(!c) c = Mix_LoadWAV(findfile(name, "rb")); return c; } static bool loadsoundslot(soundslot &slot, bool msg = false) { if(slot.sample->chunk) return true; if(!slot.sample->name[0]) return false; static const char * const exts[] = { "", ".wav", ".ogg" }; string filename; loopi(sizeof(exts)/sizeof(exts[0])) { formatstring(filename)("packages/sounds/%s%s", slot.sample->name, exts[i]); if(msg && !i) renderprogress(0, filename); path(filename); slot.sample->chunk = loadwav(filename); if(slot.sample->chunk) return true; } conoutf(CON_ERROR, "failed to load sample: packages/sounds/%s", slot.sample->name); return false; } static inline void preloadsound(vector &sounds, vector &slots, int n) { if(!sounds.inrange(n)) return; soundconfig &config = sounds[n]; loopk(config.numslots) loadsoundslot(slots[config.slots+k], true); } void preloadsound(int n) { preloadsound(gamesounds, gameslots, n); } void preloadmapsound(int n) { preloadsound(mapsounds, mapslots, n); } void preloadmapsounds() { const vector &ents = entities::getents(); loopv(ents) { extentity &e = *ents[i]; if(e.type==ET_SOUND) preloadsound(mapsounds, mapslots, e.attr1); } } int playsound(int n, const vec *loc, extentity *ent, int flags, int loops, int fade, int chanid, int radius, int expire) { if(nosound || !soundvol || minimized) return -1; vector &slots = ent || flags&SND_MAP ? mapslots : gameslots; vector &sounds = ent || flags&SND_MAP ? mapsounds : gamesounds; if(!sounds.inrange(n)) { conoutf(CON_WARN, "unregistered sound: %d", n); return -1; } soundconfig &config = sounds[n]; if(loc && (maxsoundradius || radius > 0)) { // cull sounds that are unlikely to be heard int rad = radius > 0 ? (maxsoundradius ? min(maxsoundradius, radius) : radius) : maxsoundradius; if(camera1->o.dist(*loc) > 1.5f*rad) { if(channels.inrange(chanid) && channels[chanid].inuse && config.hasslot(channels[chanid].slot, slots)) { Mix_HaltChannel(chanid); freechannel(chanid); } return -1; } } if(chanid < 0) { if(config.maxuses) { int uses = 0; loopv(channels) if(channels[i].inuse && config.hasslot(channels[i].slot, slots) && ++uses >= config.maxuses) return -1; } // avoid bursts of sounds with heavy packetloss and in sp static int soundsatonce = 0, lastsoundmillis = 0; if(totalmillis == lastsoundmillis) soundsatonce++; else soundsatonce = 1; lastsoundmillis = totalmillis; if(maxsoundsatonce && soundsatonce > maxsoundsatonce) return -1; } if(channels.inrange(chanid)) { soundchannel &chan = channels[chanid]; if(chan.inuse && config.hasslot(chan.slot, slots)) { if(loc) chan.loc = *loc; else if(chan.hasloc()) chan.clearloc(); return chanid; } } if(fade < 0) return -1; soundslot &slot = slots[config.chooseslot()]; if(!slot.sample->chunk && !loadsoundslot(slot)) return -1; if(dbgsound) conoutf("sound: %s", slot.sample->name); chanid = -1; loopv(channels) if(!channels[i].inuse) { chanid = i; break; } if(chanid < 0 && channels.length() < maxchannels) chanid = channels.length(); if(chanid < 0) loopv(channels) if(!channels[i].volume) { chanid = i; break; } if(chanid < 0) return -1; SDL_LockAudio(); // must lock here to prevent freechannel/Mix_SetPanning race conditions if(channels.inrange(chanid) && channels[chanid].inuse) { Mix_HaltChannel(chanid); freechannel(chanid); } soundchannel &chan = newchannel(chanid, &slot, loc, ent, flags, radius); updatechannel(chan); int playing = -1; if(fade) { Mix_Volume(chanid, chan.volume); playing = expire >= 0 ? Mix_FadeInChannelTimed(chanid, slot.sample->chunk, loops, fade, expire) : Mix_FadeInChannel(chanid, slot.sample->chunk, loops, fade); } else playing = expire >= 0 ? Mix_PlayChannelTimed(chanid, slot.sample->chunk, loops, expire) : Mix_PlayChannel(chanid, slot.sample->chunk, loops); if(playing >= 0) syncchannel(chan); else freechannel(chanid); SDL_UnlockAudio(); return playing; } void stopsounds() { loopv(channels) if(channels[i].inuse) { Mix_HaltChannel(i); freechannel(i); } } bool stopsound(int n, int chanid, int fade) { if(!channels.inrange(chanid) || !channels[chanid].inuse || !gamesounds.inrange(n) || !gamesounds[n].hasslot(channels[chanid].slot, gameslots)) return false; if(dbgsound) conoutf("stopsound: %s", channels[chanid].slot->sample->name); if(!fade || !Mix_FadeOutChannel(chanid, fade)) { Mix_HaltChannel(chanid); freechannel(chanid); } return true; } int playsoundname(const char *s, const vec *loc, int vol, int flags, int loops, int fade, int chanid, int radius, int expire) { if(!vol) vol = 100; int id = findsound(s, vol, gamesounds, gameslots); if(id < 0) id = addsound(s, vol, 0, gamesounds, gameslots); return playsound(id, loc, NULL, flags, loops, fade, chanid, radius, expire); } void sound(int *n) { playsound(*n); } COMMAND(sound, "i"); void resetsound() { const SDL_version *v = Mix_Linked_Version(); if(SDL_VERSIONNUM(v->major, v->minor, v->patch) <= SDL_VERSIONNUM(1, 2, 8)) { conoutf(CON_ERROR, "Sound reset not available in-game due to SDL_mixer-1.2.8 bug. Please restart for changes to take effect."); return; } clearchanges(CHANGE_SOUND); if(!nosound) { enumerate(samples, soundsample, s, s.cleanup()); if(music) { Mix_HaltMusic(); Mix_FreeMusic(music); } if(musicstream) musicstream->seek(0, SEEK_SET); Mix_CloseAudio(); } initsound(); resetchannels(); if(nosound) { DELETEA(musicfile); DELETEA(musicdonecmd); music = NULL; gamesounds.setsize(0); mapsounds.setsize(0); samples.clear(); return; } if(music && loadmusic(musicfile)) { Mix_PlayMusic(music, musicdonecmd ? 0 : -1); Mix_VolumeMusic((musicvol*MAXVOL)/255); } else { DELETEA(musicfile); DELETEA(musicdonecmd); } } COMMAND(resetsound, ""); #ifdef WIN32 #include #else #include #ifdef _POSIX_SHARED_MEMORY_OBJECTS #include #include #include #include #include #endif #endif #if defined(WIN32) || defined(_POSIX_SHARED_MEMORY_OBJECTS) struct MumbleInfo { int version, timestamp; vec pos, front, top; wchar_t name[256]; }; #endif #ifdef WIN32 static HANDLE mumblelink = NULL; static MumbleInfo *mumbleinfo = NULL; #define VALID_MUMBLELINK (mumblelink && mumbleinfo) #elif defined(_POSIX_SHARED_MEMORY_OBJECTS) static int mumblelink = -1; static MumbleInfo *mumbleinfo = (MumbleInfo *)-1; #define VALID_MUMBLELINK (mumblelink >= 0 && mumbleinfo != (MumbleInfo *)-1) #endif #ifdef VALID_MUMBLELINK VARFP(mumble, 0, 1, 1, { if(mumble) initmumble(); else closemumble(); }); #else VARFP(mumble, 0, 0, 1, { if(mumble) initmumble(); else closemumble(); }); #endif void initmumble() { if(!mumble) return; #ifdef VALID_MUMBLELINK if(VALID_MUMBLELINK) return; #ifdef WIN32 mumblelink = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, "MumbleLink"); if(mumblelink) { mumbleinfo = (MumbleInfo *)MapViewOfFile(mumblelink, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(MumbleInfo)); if(mumbleinfo) wcsncpy(mumbleinfo->name, L"Sauerbraten", 256); } #elif defined(_POSIX_SHARED_MEMORY_OBJECTS) defformatstring(shmname)("/MumbleLink.%d", getuid()); mumblelink = shm_open(shmname, O_RDWR, 0); if(mumblelink >= 0) { mumbleinfo = (MumbleInfo *)mmap(NULL, sizeof(MumbleInfo), PROT_READ|PROT_WRITE, MAP_SHARED, mumblelink, 0); if(mumbleinfo != (MumbleInfo *)-1) wcsncpy(mumbleinfo->name, L"Sauerbraten", 256); } #endif if(!VALID_MUMBLELINK) closemumble(); #else conoutf(CON_ERROR, "Mumble positional audio is not available on this platform."); #endif } void closemumble() { #ifdef WIN32 if(mumbleinfo) { UnmapViewOfFile(mumbleinfo); mumbleinfo = NULL; } if(mumblelink) { CloseHandle(mumblelink); mumblelink = NULL; } #elif defined(_POSIX_SHARED_MEMORY_OBJECTS) if(mumbleinfo != (MumbleInfo *)-1) { munmap(mumbleinfo, sizeof(MumbleInfo)); mumbleinfo = (MumbleInfo *)-1; } if(mumblelink >= 0) { close(mumblelink); mumblelink = -1; } #endif } static inline vec mumblevec(const vec &v, bool pos = false) { // change from X left, Z up, Y forward to X right, Y up, Z forward // 8 cube units = 1 meter vec m(-v.x, v.z, v.y); if(pos) m.div(8); return m; } void updatemumble() { #ifdef VALID_MUMBLELINK if(!VALID_MUMBLELINK) return; static int timestamp = 0; mumbleinfo->version = 1; mumbleinfo->timestamp = ++timestamp; mumbleinfo->pos = mumblevec(player->o, true); mumbleinfo->front = mumblevec(vec(RAD*player->yaw, RAD*player->pitch)); mumbleinfo->top = mumblevec(vec(RAD*player->yaw, RAD*(player->pitch+90))); #endif } sauerbraten-0.0.20130203.dfsg/engine/md3.h0000644000175000017500000001604712072642735017516 0ustar vincentvincentstruct md3; struct md3frame { vec bbmin, bbmax, origin; float radius; uchar name[16]; }; struct md3tag { char name[64]; vec pos; float rotation[3][3]; }; struct md3vertex { short vertex[3]; short normal; }; struct md3triangle { int vertexindices[3]; }; struct md3header { char id[4]; int version; char name[64]; int flags; int numframes, numtags, nummeshes, numskins; int ofs_frames, ofs_tags, ofs_meshes, ofs_eof; // offsets }; struct md3meshheader { char id[4]; char name[64]; int flags; int numframes, numshaders, numvertices, numtriangles; int ofs_triangles, ofs_shaders, ofs_uv, ofs_vertices, meshsize; // offsets }; struct md3 : vertmodel, vertloader { md3(const char *name) : vertmodel(name) {} static const char *formatname() { return "md3"; } int type() const { return MDL_MD3; } struct md3meshgroup : vertmeshgroup { bool load(const char *path) { stream *f = openfile(path, "rb"); if(!f) return false; md3header header; f->read(&header, sizeof(md3header)); lilswap(&header.version, 1); lilswap(&header.flags, 9); if(strncmp(header.id, "IDP3", 4) != 0 || header.version != 15) // header check { delete f; conoutf("md3: corrupted header"); return false; } name = newstring(path); numframes = header.numframes; int mesh_offset = header.ofs_meshes; loopi(header.nummeshes) { vertmesh &m = *new vertmesh; m.group = this; meshes.add(&m); md3meshheader mheader; f->seek(mesh_offset, SEEK_SET); f->read(&mheader, sizeof(md3meshheader)); lilswap(&mheader.flags, 10); m.name = newstring(mheader.name); m.numtris = mheader.numtriangles; m.tris = new tri[m.numtris]; f->seek(mesh_offset + mheader.ofs_triangles, SEEK_SET); loopj(m.numtris) { md3triangle tri; f->read(&tri, sizeof(md3triangle)); // read the triangles lilswap(tri.vertexindices, 3); loopk(3) m.tris[j].vert[k] = (ushort)tri.vertexindices[k]; } m.numverts = mheader.numvertices; m.tcverts = new tcvert[m.numverts]; f->seek(mesh_offset + mheader.ofs_uv , SEEK_SET); f->read(m.tcverts, m.numverts*2*sizeof(float)); // read the UV data lilswap(&m.tcverts[0].u, 2*m.numverts); m.verts = new vert[numframes*m.numverts]; f->seek(mesh_offset + mheader.ofs_vertices, SEEK_SET); loopj(numframes*m.numverts) { md3vertex v; f->read(&v, sizeof(md3vertex)); // read the vertices lilswap(v.vertex, 4); m.verts[j].pos.x = v.vertex[0]/64.0f; m.verts[j].pos.y = -v.vertex[1]/64.0f; m.verts[j].pos.z = v.vertex[2]/64.0f; float lng = (v.normal&0xFF)*PI2/255.0f; // decode vertex normals float lat = ((v.normal>>8)&0xFF)*PI2/255.0f; m.verts[j].norm.x = cosf(lat)*sinf(lng); m.verts[j].norm.y = -sinf(lat)*sinf(lng); m.verts[j].norm.z = cosf(lng); } mesh_offset += mheader.meshsize; } numtags = header.numtags; if(numtags) { tags = new tag[numframes*numtags]; f->seek(header.ofs_tags, SEEK_SET); md3tag tag; loopi(header.numframes*header.numtags) { f->read(&tag, sizeof(md3tag)); lilswap(&tag.pos.x, 12); if(tag.name[0] && iload(name)) { delete group; return NULL; } return group; } bool loaddefaultparts() { const char *pname = parentdir(loadname); part &mdl = *new part; parts.add(&mdl); mdl.model = this; mdl.index = 0; defformatstring(name1)("packages/models/%s/tris.md3", loadname); mdl.meshes = sharemeshes(path(name1)); if(!mdl.meshes) { defformatstring(name2)("packages/models/%s/tris.md3", pname); // try md3 in parent folder (vert sharing) mdl.meshes = sharemeshes(path(name2)); if(!mdl.meshes) return false; } Texture *tex, *masks; loadskin(loadname, pname, tex, masks); mdl.initskins(tex, masks); if(tex==notexture) conoutf("could not load model skin for %s", name1); return true; } bool load() { if(loaded) return true; formatstring(dir)("packages/models/%s", loadname); defformatstring(cfgname)("packages/models/%s/md3.cfg", loadname); loading = this; identflags &= ~IDF_PERSIST; if(execfile(cfgname, false) && parts.length()) // configured md3, will call the md3* commands below { identflags |= IDF_PERSIST; loading = NULL; loopv(parts) if(!parts[i]->meshes) return false; } else // md3 without configuration, try default tris and skin { identflags |= IDF_PERSIST; loading = NULL; if(!loaddefaultparts()) return false; } scale /= 4; translate.y = -translate.y; parts[0]->translate = translate; loopv(parts) parts[i]->meshes->shared++; return loaded = true; } }; vertcommands md3commands; sauerbraten-0.0.20130203.dfsg/engine/bih.cpp0000644000175000017500000002436711700024234020115 0ustar vincentvincent#include "engine.h" bool BIH::triintersect(tri &t, const vec &o, const vec &ray, float maxdist, float &dist, int mode, tri *noclip) { vec p; p.cross(ray, t.c); float det = t.b.dot(p); if(det == 0) return false; vec r(o); r.sub(t.a); float u = r.dot(p) / det; if(u < 0 || u > 1) return false; vec q; q.cross(r, t.b); float v = ray.dot(q) / det; if(v < 0 || u + v > 1) return false; float f = t.c.dot(q) / det; if(f < 0 || f > maxdist) return false; if(!(mode&RAY_SHADOW) && &t >= noclip) return false; if(t.tex && (mode&RAY_ALPHAPOLY)==RAY_ALPHAPOLY && (t.tex->alphamask || (lightmapping <= 1 && (loadalphamask(t.tex), t.tex->alphamask)))) { int si = clamp(int(t.tex->xs * (t.tc[0] + u*(t.tc[2] - t.tc[0]) + v*(t.tc[4] - t.tc[0]))), 0, t.tex->xs-1), ti = clamp(int(t.tex->ys * (t.tc[1] + u*(t.tc[3] - t.tc[1]) + v*(t.tc[5] - t.tc[1]))), 0, t.tex->ys-1); if(!(t.tex->alphamask[ti*((t.tex->xs+7)/8) + si/8] & (1<<(si%8)))) return false; } dist = f; return true; } struct BIHStack { BIHNode *node; float tmin, tmax; }; inline bool BIH::traverse(const vec &o, const vec &ray, const vec &invray, float maxdist, float &dist, int mode, BIHNode *curnode, float tmin, float tmax) { BIHStack stack[128]; int stacksize = 0; ivec order(ray.x>0 ? 0 : 1, ray.y>0 ? 0 : 1, ray.z>0 ? 0 : 1); for(;;) { int axis = curnode->axis(); int nearidx = order[axis], faridx = nearidx^1; float nearsplit = (curnode->split[nearidx] - o[axis])*invray[axis], farsplit = (curnode->split[faridx] - o[axis])*invray[axis]; if(nearsplit <= tmin) { if(farsplit < tmax) { if(!curnode->isleaf(faridx)) { curnode = &nodes[curnode->childindex(faridx)]; tmin = max(tmin, farsplit); continue; } else if(triintersect(tris[curnode->childindex(faridx)], o, ray, maxdist, dist, mode, noclip)) return true; } } else if(curnode->isleaf(nearidx)) { if(triintersect(tris[curnode->childindex(nearidx)], o, ray, maxdist, dist, mode, noclip)) return true; if(farsplit < tmax) { if(!curnode->isleaf(faridx)) { curnode = &nodes[curnode->childindex(faridx)]; tmin = max(tmin, farsplit); continue; } else if(triintersect(tris[curnode->childindex(faridx)], o, ray, maxdist, dist, mode, noclip)) return true; } } else { if(farsplit < tmax) { if(!curnode->isleaf(faridx)) { if(stacksize < int(sizeof(stack)/sizeof(stack[0]))) { BIHStack &save = stack[stacksize++]; save.node = &nodes[curnode->childindex(faridx)]; save.tmin = max(tmin, farsplit); save.tmax = tmax; } else { if(traverse(o, ray, invray, maxdist, dist, mode, &nodes[curnode->childindex(nearidx)], tmin, min(tmax, nearsplit))) return true; curnode = &nodes[curnode->childindex(faridx)]; tmin = max(tmin, farsplit); continue; } } else if(triintersect(tris[curnode->childindex(faridx)], o, ray, maxdist, dist, mode, noclip)) return true; } curnode = &nodes[curnode->childindex(nearidx)]; tmax = min(tmax, nearsplit); continue; } if(stacksize <= 0) return false; BIHStack &restore = stack[--stacksize]; curnode = restore.node; tmin = restore.tmin; tmax = restore.tmax; } } inline bool BIH::traverse(const vec &o, const vec &ray, float maxdist, float &dist, int mode) { if(!numnodes) return false; vec invray(ray.x ? 1/ray.x : 1e16f, ray.y ? 1/ray.y : 1e16f, ray.z ? 1/ray.z : 1e16f); float tmin, tmax; float t1 = (bbmin.x - o.x)*invray.x, t2 = (bbmax.x - o.x)*invray.x; if(invray.x > 0) { tmin = t1; tmax = t2; } else { tmin = t2; tmax = t1; } t1 = (bbmin.y - o.y)*invray.y; t2 = (bbmax.y - o.y)*invray.y; if(invray.y > 0) { tmin = max(tmin, t1); tmax = min(tmax, t2); } else { tmin = max(tmin, t2); tmax = min(tmax, t1); } t1 = (bbmin.z - o.z)*invray.z; t2 = (bbmax.z - o.z)*invray.z; if(invray.z > 0) { tmin = max(tmin, t1); tmax = min(tmax, t2); } else { tmin = max(tmin, t2); tmax = min(tmax, t1); } if(tmin >= maxdist || tmin>=tmax) return false; tmax = min(tmax, maxdist); return BIH::traverse(o, ray, invray, maxdist, dist, mode, &nodes[0], tmin, tmax); } void BIH::build(vector &buildnodes, ushort *indices, int numindices, const vec &vmin, const vec &vmax, int depth) { maxdepth = max(maxdepth, depth); int axis = 2; loopk(2) if(vmax[k] - vmin[k] > vmax[axis] - vmin[axis]) axis = k; vec leftmin, leftmax, rightmin, rightmax; float splitleft, splitright; int left, right; loopk(3) { leftmin = rightmin = vec(1e16f, 1e16f, 1e16f); leftmax = rightmax = vec(-1e16f, -1e16f, -1e16f); float split = 0.5f*(vmax[axis] + vmin[axis]); for(left = 0, right = numindices, splitleft = SHRT_MIN, splitright = SHRT_MAX; left < right;) { tri &tri = tris[indices[left]]; float amin = min(tri.a[axis], min(tri.b[axis], tri.c[axis])), amax = max(tri.a[axis], max(tri.b[axis], tri.c[axis])); if(max(split - amin, 0.0f) > max(amax - split, 0.0f)) { ++left; splitleft = max(splitleft, amax); leftmin.min(tri.a).min(tri.b).min(tri.c); leftmax.max(tri.a).max(tri.b).max(tri.c); } else { --right; swap(indices[left], indices[right]); splitright = min(splitright, amin); rightmin.min(tri.a).min(tri.b).min(tri.c); rightmax.max(tri.a).max(tri.b).max(tri.c); } } if(left > 0 && right < numindices) break; axis = (axis+1)%3; } if(!left || right==numindices) { leftmin = rightmin = vec(1e16f, 1e16f, 1e16f); leftmax = rightmax = vec(-1e16f, -1e16f, -1e16f); left = right = numindices/2; splitleft = SHRT_MIN; splitright = SHRT_MAX; loopi(numindices) { tri &tri = tris[indices[i]]; if(i < left) { splitleft = max(splitleft, max(tri.a[axis], max(tri.b[axis], tri.c[axis]))); leftmin.min(tri.a).min(tri.b).min(tri.c); leftmax.max(tri.a).max(tri.b).max(tri.c); } else { splitright = min(splitright, min(tri.a[axis], min(tri.b[axis], tri.c[axis]))); rightmin.min(tri.a).min(tri.b).min(tri.c); rightmax.max(tri.a).max(tri.b).max(tri.c); } } } int node = buildnodes.length(); buildnodes.add(); buildnodes[node].split[0] = short(ceil(splitleft)); buildnodes[node].split[1] = short(floor(splitright)); if(left==1) buildnodes[node].child[0] = (axis<<14) | indices[0]; else { buildnodes[node].child[0] = (axis<<14) | buildnodes.length(); build(buildnodes, indices, left, leftmin, leftmax, depth+1); } if(numindices-right==1) buildnodes[node].child[1] = (1<<15) | (left==1 ? 1<<14 : 0) | indices[right]; else { buildnodes[node].child[1] = (left==1 ? 1<<14 : 0) | buildnodes.length(); build(buildnodes, &indices[right], numindices-right, rightmin, rightmax, depth+1); } } BIH::BIH(vector *t) : maxdepth(0), numnodes(0), nodes(NULL), numtris(0), tris(NULL), noclip(NULL), bbmin(1e16f, 1e16f, 1e16f), bbmax(-1e16f, -1e16f, -1e16f) { numtris = t[0].length() + t[1].length(); if(!numtris) return; tris = new tri[numtris]; noclip = &tris[t[0].length()]; memcpy(tris, t[0].getbuf(), t[0].length()*sizeof(tri)); memcpy(noclip, t[1].getbuf(), t[1].length()*sizeof(tri)); loopi(numtris) { tri &tri = tris[i]; bbmin.min(tri.a).min(tri.b).min(tri.c); bbmax.max(tri.a).max(tri.b).max(tri.c); } radius = max(max(max(fabs(bbmin.x), fabs(bbmin.y)), fabs(bbmin.z)), max(max(fabs(bbmax.x), fabs(bbmax.y)), fabs(bbmax.z))); radius *= radius; vector buildnodes; ushort *indices = new ushort[numtris]; loopi(numtris) indices[i] = i; maxdepth = 0; build(buildnodes, indices, numtris, bbmin, bbmax); delete[] indices; numnodes = buildnodes.length(); nodes = new BIHNode[numnodes]; memcpy(nodes, buildnodes.getbuf(), numnodes*sizeof(BIHNode)); // convert tri.b/tri.c to edges loopi(numtris) { tri &tri = tris[i]; tri.b.sub(tri.a); tri.c.sub(tri.a); } } bool mmintersect(const extentity &e, const vec &o, const vec &ray, float maxdist, int mode, float &dist) { extern vector mapmodels; if(!mapmodels.inrange(e.attr2)) return false; model *m = mapmodels[e.attr2].m; if(!m) { m = loadmodel(NULL, e.attr2); if(!m) return false; } if(mode&RAY_SHADOW) { if(!m->shadow || e.flags&extentity::F_NOSHADOW) return false; } else if((mode&RAY_ENTS)!=RAY_ENTS && (!m->collide || e.flags&extentity::F_NOCOLLIDE)) return false; if(!m->bih && (lightmapping > 1 || !m->setBIH())) return false; vec mo = vec(o).sub(e.o), mray(ray); float v = mo.dot(mray), inside = m->bih->radius - mo.squaredlen(); if((inside < 0 && v > 0) || inside + v*v < 0) return false; int yaw = e.attr1; if(yaw != 0) { if(yaw < 0) yaw = 360 + yaw%360; else if(yaw >= 360) yaw %= 360; const vec2 &rot = sincos360[yaw]; mo.rotate_around_z(rot.x, -rot.y); mray.rotate_around_z(rot.x, -rot.y); } return m->bih->traverse(mo, mray, maxdist ? maxdist : 1e16f, dist, mode); } sauerbraten-0.0.20130203.dfsg/engine/dynlight.cpp0000644000175000017500000001571011543226325021177 0ustar vincentvincent#include "engine.h" VARP(ffdynlights, 0, min(5, DYNLIGHTMASK), DYNLIGHTMASK); VARP(maxdynlights, 0, min(3, MAXDYNLIGHTS), MAXDYNLIGHTS); VARP(dynlightdist, 0, 1024, 10000); struct dynlight { vec o, hud; float radius, initradius, curradius, dist; vec color, initcolor, curcolor; int fade, peak, expire, flags; physent *owner; void calcradius() { if(fade + peak > 0) { int remaining = expire - lastmillis; if(flags&DL_EXPAND) curradius = initradius + (radius - initradius) * (1.0f - remaining/float(fade + peak)); else if(!(flags&DL_FLASH) && remaining > fade) curradius = initradius + (radius - initradius) * (1.0f - float(remaining - fade)/peak); else if(flags&DL_SHRINK) curradius = (radius*remaining)/fade; else curradius = radius; } else curradius = radius; } void calccolor() { if(flags&DL_FLASH || peak <= 0) curcolor = color; else { int peaking = expire - lastmillis - fade; if(peaking <= 0) curcolor = color; else curcolor.lerp(initcolor, color, 1.0f - float(peaking)/peak); } float intensity = 1.0f; if(fade > 0) { int fading = expire - lastmillis; if(fading < fade) intensity = float(fading)/fade; } curcolor.mul(intensity); // KLUGE: this prevents nvidia drivers from trying to recompile dynlight fragment programs loopk(3) if(fmod(curcolor[k], 1.0f/256) < 0.001f) curcolor[k] += 0.001f; } }; vector dynlights; vector closedynlights; void adddynlight(const vec &o, float radius, const vec &color, int fade, int peak, int flags, float initradius, const vec &initcolor, physent *owner) { if(renderpath==R_FIXEDFUNCTION ? !ffdynlights || maxtmus<3 : !maxdynlights) return; if(o.dist(camera1->o) > dynlightdist || radius <= 0) return; int insert = 0, expire = fade + peak + lastmillis; loopvrev(dynlights) if(expire>=dynlights[i].expire) { insert = i+1; break; } dynlight d; d.o = d.hud = o; d.radius = radius; d.initradius = initradius; d.color = color; d.initcolor = initcolor; d.fade = fade; d.peak = peak; d.expire = expire; d.flags = flags; d.owner = owner; dynlights.insert(insert, d); } void cleardynlights() { int faded = -1; loopv(dynlights) if(lastmillis0) dynlights.remove(0, faded); } void removetrackeddynlights(physent *owner) { loopvrev(dynlights) if(owner ? dynlights[i].owner == owner : dynlights[i].owner != NULL) dynlights.remove(i); } void updatedynlights() { cleardynlights(); game::adddynlights(); loopv(dynlights) { dynlight &d = dynlights[i]; if(d.owner) game::dynlighttrack(d.owner, d.o, d.hud); d.calcradius(); d.calccolor(); } } int finddynlights() { closedynlights.setsize(0); if(renderpath==R_FIXEDFUNCTION ? !ffdynlights || maxtmus<3 : !maxdynlights) return 0; physent e; e.type = ENT_CAMERA; e.collidetype = COLLIDE_AABB; loopvj(dynlights) { dynlight &d = dynlights[j]; if(d.curradius <= 0) continue; d.dist = camera1->o.dist(d.o) - d.curradius; if(d.dist > dynlightdist || isfoggedsphere(d.curradius, d.o) || pvsoccluded(d.o, 2*int(d.curradius+1))) continue; if(reflecting || refracting > 0) { if(d.o.z + d.curradius < reflectz) continue; } else if(refracting < 0 && d.o.z - d.curradius > reflectz) continue; e.o = d.o; e.radius = e.xradius = e.yradius = e.eyeheight = e.aboveeye = d.curradius; if(collide(&e, vec(0, 0, 0), 0, false)) continue; int insert = 0; loopvrev(closedynlights) if(d.dist >= closedynlights[i]->dist) { insert = i+1; break; } closedynlights.insert(insert, &d); if(closedynlights.length() >= DYNLIGHTMASK) break; } if(renderpath==R_FIXEDFUNCTION && closedynlights.length() > ffdynlights) closedynlights.setsize(ffdynlights); return closedynlights.length(); } bool getdynlight(int n, vec &o, float &radius, vec &color) { if(!closedynlights.inrange(n)) return false; dynlight &d = *closedynlights[n]; o = d.o; radius = d.curradius; color = d.curcolor; return true; } void dynlightreaching(const vec &target, vec &color, vec &dir, bool hud) { vec dyncolor(0, 0, 0);//, dyndir(0, 0, 0); loopv(dynlights) { dynlight &d = dynlights[i]; if(d.curradius<=0) continue; vec ray(hud ? d.hud : d.o); ray.sub(target); float mag = ray.squaredlen(); if(mag >= d.curradius*d.curradius) continue; vec color = d.curcolor; color.mul(1 - sqrtf(mag)/d.curradius); dyncolor.add(color); //dyndir.add(ray.mul(intensity/mag)); } #if 0 if(!dyndir.iszero()) { dyndir.normalize(); float x = dyncolor.magnitude(), y = color.magnitude(); if(x+y>0) { dir.mul(x); dyndir.mul(y); dir.add(dyndir).div(x+y); if(dir.iszero()) dir = vec(0, 0, 1); else dir.normalize(); } } #endif color.add(dyncolor); } void calcdynlightmask(vtxarray *va) { uint mask = 0; int offset = 0; loopv(closedynlights) { dynlight &d = *closedynlights[i]; if(d.o.dist_to_bb(va->geommin, va->geommax) >= d.curradius) continue; mask |= (i+1)<= maxdynlights*DYNLIGHTBITS) break; } va->dynlightmask = mask; } int setdynlights(vtxarray *va) { if(closedynlights.empty() || !va->dynlightmask) return 0; static string posparams[MAXDYNLIGHTS] = { "" }, colorparams[MAXDYNLIGHTS] = { "" }, offsetparams[MAXDYNLIGHTS] = { "" }; if(!*posparams[0]) loopi(MAXDYNLIGHTS) { formatstring(posparams[i])("dynlight%dpos", i); formatstring(colorparams[i])("dynlight%dcolor", i); formatstring(offsetparams[i])("dynlight%doffset", i); } int index = 0; float scale0 = 1; vec origin0(0, 0, 0); for(uint mask = va->dynlightmask; mask; mask >>= DYNLIGHTBITS, index++) { dynlight &d = *closedynlights[(mask&DYNLIGHTMASK)-1]; float scale = 1.0f/d.curradius; vec origin = vec(d.o).mul(-scale); setenvparamf(posparams[index], SHPARAM_VERTEX, 10+index, origin.x, origin.y, origin.z, scale); if(index<=0) { scale0 = scale; origin0 = origin; } else { scale /= scale0; origin.sub(vec(origin0).mul(scale)); setenvparamf(offsetparams[index], SHPARAM_PIXEL, index-1, origin.x, origin.y, origin.z, scale); } setenvparamf(colorparams[index], SHPARAM_PIXEL, 10+index, d.curcolor.x, d.curcolor.y, d.curcolor.z); } return index; } sauerbraten-0.0.20130203.dfsg/engine/rendergl.cpp0000644000175000017500000025175512077450335021175 0ustar vincentvincent// rendergl.cpp: core opengl rendering stuff #include "engine.h" bool hasVBO = false, hasDRE = false, hasOQ = false, hasTR = false, hasFBO = false, hasDS = false, hasTF = false, hasBE = false, hasBC = false, hasCM = false, hasNP2 = false, hasTC = false, hasS3TC = false, hasFXT1 = false, hasTE = false, hasMT = false, hasD3 = false, hasAF = false, hasVP2 = false, hasVP3 = false, hasPP = false, hasMDA = false, hasTE3 = false, hasTE4 = false, hasVP = false, hasFP = false, hasGLSL = false, hasGM = false, hasNVFB = false, hasSGIDT = false, hasSGISH = false, hasDT = false, hasSH = false, hasNVPCF = false, hasRN = false, hasPBO = false, hasFBB = false, hasUBO = false, hasBUE = false, hasMBR = false, hasFC = false, hasTEX = false; int hasstencil = 0; VAR(renderpath, 1, 0, 0); VAR(glversion, 1, 0, 0); VAR(glslversion, 1, 0, 0); // GL_ARB_vertex_buffer_object, GL_ARB_pixel_buffer_object PFNGLGENBUFFERSARBPROC glGenBuffers_ = NULL; PFNGLBINDBUFFERARBPROC glBindBuffer_ = NULL; PFNGLMAPBUFFERARBPROC glMapBuffer_ = NULL; PFNGLUNMAPBUFFERARBPROC glUnmapBuffer_ = NULL; PFNGLBUFFERDATAARBPROC glBufferData_ = NULL; PFNGLBUFFERSUBDATAARBPROC glBufferSubData_ = NULL; PFNGLDELETEBUFFERSARBPROC glDeleteBuffers_ = NULL; PFNGLGETBUFFERSUBDATAARBPROC glGetBufferSubData_ = NULL; // GL_ARB_multitexture PFNGLACTIVETEXTUREARBPROC glActiveTexture_ = NULL; PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTexture_ = NULL; PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2f_ = NULL; PFNGLMULTITEXCOORD3FARBPROC glMultiTexCoord3f_ = NULL; PFNGLMULTITEXCOORD4FARBPROC glMultiTexCoord4f_ = NULL; // GL_ARB_vertex_program, GL_ARB_fragment_program PFNGLGENPROGRAMSARBPROC glGenProgramsARB_ = NULL; PFNGLDELETEPROGRAMSARBPROC glDeleteProgramsARB_ = NULL; PFNGLBINDPROGRAMARBPROC glBindProgramARB_ = NULL; PFNGLPROGRAMSTRINGARBPROC glProgramStringARB_ = NULL; PFNGLGETPROGRAMIVARBPROC glGetProgramivARB_ = NULL; PFNGLPROGRAMENVPARAMETER4FARBPROC glProgramEnvParameter4fARB_ = NULL; PFNGLPROGRAMENVPARAMETER4FVARBPROC glProgramEnvParameter4fvARB_ = NULL; // GL_EXT_gpu_program_parameters PFNGLPROGRAMENVPARAMETERS4FVEXTPROC glProgramEnvParameters4fv_ = NULL; PFNGLPROGRAMLOCALPARAMETERS4FVEXTPROC glProgramLocalParameters4fv_ = NULL; // GL_ARB_occlusion_query PFNGLGENQUERIESARBPROC glGenQueries_ = NULL; PFNGLDELETEQUERIESARBPROC glDeleteQueries_ = NULL; PFNGLBEGINQUERYARBPROC glBeginQuery_ = NULL; PFNGLENDQUERYARBPROC glEndQuery_ = NULL; PFNGLGETQUERYIVARBPROC glGetQueryiv_ = NULL; PFNGLGETQUERYOBJECTIVARBPROC glGetQueryObjectiv_ = NULL; PFNGLGETQUERYOBJECTUIVARBPROC glGetQueryObjectuiv_ = NULL; // GL_EXT_framebuffer_object PFNGLBINDRENDERBUFFEREXTPROC glBindRenderbuffer_ = NULL; PFNGLDELETERENDERBUFFERSEXTPROC glDeleteRenderbuffers_ = NULL; PFNGLGENFRAMEBUFFERSEXTPROC glGenRenderbuffers_ = NULL; PFNGLRENDERBUFFERSTORAGEEXTPROC glRenderbufferStorage_ = NULL; PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatus_ = NULL; PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebuffer_ = NULL; PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffers_ = NULL; PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffers_ = NULL; PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2D_ = NULL; PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbuffer_ = NULL; PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmap_ = NULL; // GL_EXT_framebuffer_blit PFNGLBLITFRAMEBUFFEREXTPROC glBlitFramebuffer_ = NULL; // OpenGL 2.0: GL_ARB_shading_language_100, GL_ARB_shader_objects, GL_ARB_fragment_shader, GL_ARB_vertex_shader #ifndef __APPLE__ PFNGLCREATEPROGRAMPROC glCreateProgram_ = NULL; PFNGLDELETEPROGRAMPROC glDeleteProgram_ = NULL; PFNGLUSEPROGRAMPROC glUseProgram_ = NULL; PFNGLCREATESHADERPROC glCreateShader_ = NULL; PFNGLDELETESHADERPROC glDeleteShader_ = NULL; PFNGLSHADERSOURCEPROC glShaderSource_ = NULL; PFNGLCOMPILESHADERPROC glCompileShader_ = NULL; PFNGLGETSHADERIVPROC glGetShaderiv_ = NULL; PFNGLGETPROGRAMIVPROC glGetProgramiv_ = NULL; PFNGLATTACHSHADERPROC glAttachShader_ = NULL; PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog_ = NULL; PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog_ = NULL; PFNGLLINKPROGRAMPROC glLinkProgram_ = NULL; PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation_ = NULL; PFNGLUNIFORM1FPROC glUniform1f_ = NULL; PFNGLUNIFORM2FPROC glUniform2f_ = NULL; PFNGLUNIFORM3FPROC glUniform3f_ = NULL; PFNGLUNIFORM4FPROC glUniform4f_ = NULL; PFNGLUNIFORM1FVPROC glUniform1fv_ = NULL; PFNGLUNIFORM2FVPROC glUniform2fv_ = NULL; PFNGLUNIFORM3FVPROC glUniform3fv_ = NULL; PFNGLUNIFORM4FVPROC glUniform4fv_ = NULL; PFNGLUNIFORM1IPROC glUniform1i_ = NULL; PFNGLBINDATTRIBLOCATIONPROC glBindAttribLocation_ = NULL; PFNGLGETACTIVEUNIFORMPROC glGetActiveUniform_ = NULL; PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray_ = NULL; PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray_ = NULL; PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer_ = NULL; PFNGLUNIFORMMATRIX2X3FVPROC glUniformMatrix2x3fv_ = NULL; PFNGLUNIFORMMATRIX3X2FVPROC glUniformMatrix3x2fv_ = NULL; PFNGLUNIFORMMATRIX2X4FVPROC glUniformMatrix2x4fv_ = NULL; PFNGLUNIFORMMATRIX4X2FVPROC glUniformMatrix4x2fv_ = NULL; PFNGLUNIFORMMATRIX3X4FVPROC glUniformMatrix3x4fv_ = NULL; PFNGLUNIFORMMATRIX4X3FVPROC glUniformMatrix4x3fv_ = NULL; #endif // GL_EXT_draw_range_elements PFNGLDRAWRANGEELEMENTSEXTPROC glDrawRangeElements_ = NULL; // GL_EXT_blend_minmax PFNGLBLENDEQUATIONEXTPROC glBlendEquation_ = NULL; // GL_EXT_blend_color PFNGLBLENDCOLOREXTPROC glBlendColor_ = NULL; // GL_EXT_multi_draw_arrays PFNGLMULTIDRAWARRAYSEXTPROC glMultiDrawArrays_ = NULL; PFNGLMULTIDRAWELEMENTSEXTPROC glMultiDrawElements_ = NULL; // GL_ARB_texture_compression PFNGLCOMPRESSEDTEXIMAGE3DARBPROC glCompressedTexImage3D_ = NULL; PFNGLCOMPRESSEDTEXIMAGE2DARBPROC glCompressedTexImage2D_ = NULL; PFNGLCOMPRESSEDTEXIMAGE1DARBPROC glCompressedTexImage1D_ = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC glCompressedTexSubImage3D_ = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC glCompressedTexSubImage2D_ = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC glCompressedTexSubImage1D_ = NULL; PFNGLGETCOMPRESSEDTEXIMAGEARBPROC glGetCompressedTexImage_ = NULL; // GL_ARB_uniform_buffer_object PFNGLGETUNIFORMINDICESPROC glGetUniformIndices_ = NULL; PFNGLGETACTIVEUNIFORMSIVPROC glGetActiveUniformsiv_ = NULL; PFNGLGETUNIFORMBLOCKINDEXPROC glGetUniformBlockIndex_ = NULL; PFNGLGETACTIVEUNIFORMBLOCKIVPROC glGetActiveUniformBlockiv_ = NULL; PFNGLUNIFORMBLOCKBINDINGPROC glUniformBlockBinding_ = NULL; PFNGLBINDBUFFERBASEPROC glBindBufferBase_ = NULL; PFNGLBINDBUFFERRANGEPROC glBindBufferRange_ = NULL; // GL_EXT_bindable_uniform PFNGLUNIFORMBUFFEREXTPROC glUniformBuffer_ = NULL; PFNGLGETUNIFORMBUFFERSIZEEXTPROC glGetUniformBufferSize_ = NULL; PFNGLGETUNIFORMOFFSETEXTPROC glGetUniformOffset_ = NULL; // GL_EXT_fog_coord PFNGLFOGCOORDPOINTEREXTPROC glFogCoordPointer_ = NULL; // GL_ARB_map_buffer_range PFNGLMAPBUFFERRANGEPROC glMapBufferRange_ = NULL; PFNGLFLUSHMAPPEDBUFFERRANGEPROC glFlushMappedBufferRange_ = NULL; void *getprocaddress(const char *name) { return SDL_GL_GetProcAddress(name); } VARP(ati_skybox_bug, 0, 0, 1); VAR(ati_oq_bug, 0, 0, 1); VAR(ati_minmax_bug, 0, 0, 1); VAR(ati_dph_bug, 0, 0, 1); VAR(ati_line_bug, 0, 0, 1); VAR(ati_cubemap_bug, 0, 0, 1); VAR(ati_ubo_bug, 0, 0, 1); VAR(nvidia_scissor_bug, 0, 0, 1); VAR(intel_immediate_bug, 0, 0, 1); VAR(intel_vertexarray_bug, 0, 0, 1); VAR(apple_glsldepth_bug, 0, 0, 1); VAR(apple_ff_bug, 0, 0, 1); VAR(apple_vp_bug, 0, 0, 1); VAR(sdl_backingstore_bug, -1, 0, 1); VAR(avoidshaders, 1, 0, 0); VAR(preferglsl, 1, 0, 0); VAR(minimizetcusage, 1, 0, 0); VAR(emulatefog, 1, 0, 0); VAR(usevp2, 1, 0, 0); VAR(usevp3, 1, 0, 0); VAR(usetexrect, 1, 0, 0); VAR(hasglsl, 1, 0, 0); VAR(useubo, 1, 0, 0); VAR(usebue, 1, 0, 0); VAR(usetexcompress, 1, 0, 0); VAR(rtscissor, 0, 1, 1); VAR(blurtile, 0, 1, 1); VAR(rtsharefb, 0, 1, 1); static bool checkseries(const char *s, int low, int high) { while(*s && !isdigit(*s)) ++s; if(!*s) return false; int n = 0; while(isdigit(*s)) n = n*10 + (*s++ - '0'); return n >= low && n < high; } VAR(dbgexts, 0, 0, 1); bool hasext(const char *exts, const char *ext) { int len = strlen(ext); if(len) for(const char *cur = exts; (cur = strstr(cur, ext)); cur += len) { if((cur == exts || cur[-1] == ' ') && (cur[len] == ' ' || !cur[len])) return true; } return false; } void gl_checkextensions() { const char *vendor = (const char *)glGetString(GL_VENDOR); const char *exts = (const char *)glGetString(GL_EXTENSIONS); const char *renderer = (const char *)glGetString(GL_RENDERER); const char *version = (const char *)glGetString(GL_VERSION); conoutf(CON_INIT, "Renderer: %s (%s)", renderer, vendor); conoutf(CON_INIT, "Driver: %s", version); #ifdef __APPLE__ extern int mac_osversion(); int osversion = mac_osversion(); /* 0x0A0500 = 10.5 (Leopard) */ sdl_backingstore_bug = -1; #endif bool mesa = false, intel = false, ati = false, nvidia = false; if(strstr(renderer, "Mesa") || strstr(version, "Mesa")) { mesa = true; if(strstr(renderer, "Intel")) intel = true; } else if(strstr(vendor, "NVIDIA")) nvidia = true; else if(strstr(vendor, "ATI") || strstr(vendor, "Advanced Micro Devices")) ati = true; else if(strstr(vendor, "Intel")) intel = true; uint glmajorversion, glminorversion; if(sscanf(version, " %u.%u", &glmajorversion, &glminorversion) != 2) glversion = 100; else glversion = glmajorversion*100 + glminorversion*10; //extern int shaderprecision; // default to low precision shaders on certain cards, can be overridden with -f3 // char *weakcards[] = { "GeForce FX", "Quadro FX", "6200", "9500", "9550", "9600", "9700", "9800", "X300", "X600", "FireGL", "Intel", "Chrome", NULL } // if(shaderprecision==2) for(char **wc = weakcards; *wc; wc++) if(strstr(renderer, *wc)) shaderprecision = 1; GLint val; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &val); hwtexsize = val; if(hasext(exts, "GL_EXT_texture_env_combine") || hasext(exts, "GL_ARB_texture_env_combine")) { hasTE = true; if(hasext(exts, "GL_ARB_texture_env_crossbar")) hasTEX = true; if(hasext(exts, "GL_ATI_texture_env_combine3")) hasTE3 = true; if(hasext(exts, "GL_NV_texture_env_combine4")) hasTE4 = true; if(hasext(exts, "GL_EXT_texture_env_dot3") || hasext(exts, "GL_ARB_texture_env_dot3")) hasD3 = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_texture_env_combine extension."); } else conoutf(CON_WARN, "WARNING: No texture_env_combine extension! (your video card is WAY too old)"); if(hasext(exts, "GL_ARB_multitexture")) { glActiveTexture_ = (PFNGLACTIVETEXTUREARBPROC) getprocaddress("glActiveTextureARB"); glClientActiveTexture_ = (PFNGLCLIENTACTIVETEXTUREARBPROC)getprocaddress("glClientActiveTextureARB"); glMultiTexCoord2f_ = (PFNGLMULTITEXCOORD2FARBPROC) getprocaddress("glMultiTexCoord2fARB"); glMultiTexCoord3f_ = (PFNGLMULTITEXCOORD3FARBPROC) getprocaddress("glMultiTexCoord3fARB"); glMultiTexCoord4f_ = (PFNGLMULTITEXCOORD4FARBPROC) getprocaddress("glMultiTexCoord4fARB"); hasMT = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_multitexture extension."); } else conoutf(CON_WARN, "WARNING: No multitexture extension!"); if(hasext(exts, "GL_ARB_vertex_buffer_object")) { hasVBO = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_vertex_buffer_object extension."); } else conoutf(CON_WARN, "WARNING: No vertex_buffer_object extension! (geometry heavy maps will be SLOW)"); #ifdef __APPLE__ /* VBOs over 256KB seem to destroy performance on 10.5, but not in 10.6 */ extern int maxvbosize; if(osversion < 0x0A0600) maxvbosize = min(maxvbosize, 8192); #endif if(hasext(exts, "GL_ARB_pixel_buffer_object")) { hasPBO = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_pixel_buffer_object extension."); } if(hasVBO || hasPBO) { glGenBuffers_ = (PFNGLGENBUFFERSARBPROC) getprocaddress("glGenBuffersARB"); glBindBuffer_ = (PFNGLBINDBUFFERARBPROC) getprocaddress("glBindBufferARB"); glMapBuffer_ = (PFNGLMAPBUFFERARBPROC) getprocaddress("glMapBufferARB"); glUnmapBuffer_ = (PFNGLUNMAPBUFFERARBPROC) getprocaddress("glUnmapBufferARB"); glBufferData_ = (PFNGLBUFFERDATAARBPROC) getprocaddress("glBufferDataARB"); glBufferSubData_ = (PFNGLBUFFERSUBDATAARBPROC) getprocaddress("glBufferSubDataARB"); glDeleteBuffers_ = (PFNGLDELETEBUFFERSARBPROC) getprocaddress("glDeleteBuffersARB"); glGetBufferSubData_ = (PFNGLGETBUFFERSUBDATAARBPROC)getprocaddress("glGetBufferSubDataARB"); } if(hasext(exts, "GL_EXT_draw_range_elements")) { glDrawRangeElements_ = (PFNGLDRAWRANGEELEMENTSEXTPROC)getprocaddress("glDrawRangeElementsEXT"); hasDRE = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_draw_range_elements extension."); } if(hasext(exts, "GL_EXT_multi_draw_arrays")) { glMultiDrawArrays_ = (PFNGLMULTIDRAWARRAYSEXTPROC) getprocaddress("glMultiDrawArraysEXT"); glMultiDrawElements_ = (PFNGLMULTIDRAWELEMENTSEXTPROC)getprocaddress("glMultiDrawElementsEXT"); hasMDA = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_multi_draw_arrays extension."); } #ifdef __APPLE__ // floating point FBOs not fully supported until 10.5 if(osversion>=0x0A0500) #endif if(hasext(exts, "GL_ARB_texture_float") || hasext(exts, "GL_ATI_texture_float")) { hasTF = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_texture_float extension."); shadowmap = 1; extern int smoothshadowmappeel; smoothshadowmappeel = 1; } if(hasext(exts, "GL_NV_float_buffer")) { hasNVFB = true; if(dbgexts) conoutf(CON_INIT, "Using GL_NV_float_buffer extension."); } if(hasext(exts, "GL_EXT_framebuffer_object")) { glBindRenderbuffer_ = (PFNGLBINDRENDERBUFFEREXTPROC) getprocaddress("glBindRenderbufferEXT"); glDeleteRenderbuffers_ = (PFNGLDELETERENDERBUFFERSEXTPROC) getprocaddress("glDeleteRenderbuffersEXT"); glGenRenderbuffers_ = (PFNGLGENFRAMEBUFFERSEXTPROC) getprocaddress("glGenRenderbuffersEXT"); glRenderbufferStorage_ = (PFNGLRENDERBUFFERSTORAGEEXTPROC) getprocaddress("glRenderbufferStorageEXT"); glCheckFramebufferStatus_ = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) getprocaddress("glCheckFramebufferStatusEXT"); glBindFramebuffer_ = (PFNGLBINDFRAMEBUFFEREXTPROC) getprocaddress("glBindFramebufferEXT"); glDeleteFramebuffers_ = (PFNGLDELETEFRAMEBUFFERSEXTPROC) getprocaddress("glDeleteFramebuffersEXT"); glGenFramebuffers_ = (PFNGLGENFRAMEBUFFERSEXTPROC) getprocaddress("glGenFramebuffersEXT"); glFramebufferTexture2D_ = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) getprocaddress("glFramebufferTexture2DEXT"); glFramebufferRenderbuffer_ = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)getprocaddress("glFramebufferRenderbufferEXT"); glGenerateMipmap_ = (PFNGLGENERATEMIPMAPEXTPROC) getprocaddress("glGenerateMipmapEXT"); hasFBO = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_framebuffer_object extension."); if(hasext(exts, "GL_EXT_framebuffer_blit")) { glBlitFramebuffer_ = (PFNGLBLITFRAMEBUFFEREXTPROC) getprocaddress("glBlitFramebufferEXT"); hasFBB = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_framebuffer_blit extension."); } } else conoutf(CON_WARN, "WARNING: No framebuffer object support. (reflective water may be slow)"); if(hasext(exts, "GL_ARB_occlusion_query")) { GLint bits; glGetQueryiv_ = (PFNGLGETQUERYIVARBPROC)getprocaddress("glGetQueryivARB"); glGetQueryiv_(GL_SAMPLES_PASSED_ARB, GL_QUERY_COUNTER_BITS_ARB, &bits); if(bits) { glGenQueries_ = (PFNGLGENQUERIESARBPROC) getprocaddress("glGenQueriesARB"); glDeleteQueries_ = (PFNGLDELETEQUERIESARBPROC) getprocaddress("glDeleteQueriesARB"); glBeginQuery_ = (PFNGLBEGINQUERYARBPROC) getprocaddress("glBeginQueryARB"); glEndQuery_ = (PFNGLENDQUERYARBPROC) getprocaddress("glEndQueryARB"); glGetQueryObjectiv_ = (PFNGLGETQUERYOBJECTIVARBPROC) getprocaddress("glGetQueryObjectivARB"); glGetQueryObjectuiv_ = (PFNGLGETQUERYOBJECTUIVARBPROC)getprocaddress("glGetQueryObjectuivARB"); hasOQ = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_occlusion_query extension."); #if defined(__APPLE__) && SDL_BYTEORDER == SDL_BIG_ENDIAN if(ati && (osversion<0x0A0500)) ati_oq_bug = 1; #endif //if(ati_oq_bug) conoutf(CON_WARN, "WARNING: Using ATI occlusion query bug workaround. (use \"/ati_oq_bug 0\" to disable if unnecessary)"); } } if(!hasOQ) { conoutf(CON_WARN, "WARNING: No occlusion query support! (large maps may be SLOW)"); extern int vacubesize; vacubesize = 64; waterreflect = 0; } if(hasext(exts, "GL_ARB_vertex_program") && hasext(exts, "GL_ARB_fragment_program")) { hasVP = hasFP = true; glGenProgramsARB_ = (PFNGLGENPROGRAMSARBPROC) getprocaddress("glGenProgramsARB"); glDeleteProgramsARB_ = (PFNGLDELETEPROGRAMSARBPROC) getprocaddress("glDeleteProgramsARB"); glBindProgramARB_ = (PFNGLBINDPROGRAMARBPROC) getprocaddress("glBindProgramARB"); glProgramStringARB_ = (PFNGLPROGRAMSTRINGARBPROC) getprocaddress("glProgramStringARB"); glGetProgramivARB_ = (PFNGLGETPROGRAMIVARBPROC) getprocaddress("glGetProgramivARB"); glProgramEnvParameter4fARB_ = (PFNGLPROGRAMENVPARAMETER4FARBPROC) getprocaddress("glProgramEnvParameter4fARB"); glProgramEnvParameter4fvARB_ = (PFNGLPROGRAMENVPARAMETER4FVARBPROC) getprocaddress("glProgramEnvParameter4fvARB"); #ifndef __APPLE__ glEnableVertexAttribArray_ = (PFNGLENABLEVERTEXATTRIBARRAYPROC) getprocaddress("glEnableVertexAttribArrayARB"); glDisableVertexAttribArray_ = (PFNGLDISABLEVERTEXATTRIBARRAYPROC) getprocaddress("glDisableVertexAttribArrayARB"); glVertexAttribPointer_ = (PFNGLVERTEXATTRIBPOINTERPROC) getprocaddress("glVertexAttribPointerARB"); #endif if(ati) ati_dph_bug = ati_line_bug = 1; #ifdef __APPLE__ if(osversion>=0x0A0500) // fixed in 1055 for some hardware.. but not all.. { apple_ff_bug = 1; //conoutf(CON_WARN, "WARNING: Using Leopard ARB_position_invariant bug workaround. (use \"/apple_ff_bug 0\" to disable if unnecessary)"); } #endif } if(glversion >= 200) { #ifndef __APPLE__ glCreateProgram_ = (PFNGLCREATEPROGRAMPROC) getprocaddress("glCreateProgram"); glDeleteProgram_ = (PFNGLDELETEPROGRAMPROC) getprocaddress("glDeleteProgram"); glUseProgram_ = (PFNGLUSEPROGRAMPROC) getprocaddress("glUseProgram"); glCreateShader_ = (PFNGLCREATESHADERPROC) getprocaddress("glCreateShader"); glDeleteShader_ = (PFNGLDELETESHADERPROC) getprocaddress("glDeleteShader"); glShaderSource_ = (PFNGLSHADERSOURCEPROC) getprocaddress("glShaderSource"); glCompileShader_ = (PFNGLCOMPILESHADERPROC) getprocaddress("glCompileShader"); glGetShaderiv_ = (PFNGLGETSHADERIVPROC) getprocaddress("glGetShaderiv"); glGetProgramiv_ = (PFNGLGETPROGRAMIVPROC) getprocaddress("glGetProgramiv"); glAttachShader_ = (PFNGLATTACHSHADERPROC) getprocaddress("glAttachShader"); glGetProgramInfoLog_ = (PFNGLGETPROGRAMINFOLOGPROC) getprocaddress("glGetProgramInfoLog"); glGetShaderInfoLog_ = (PFNGLGETSHADERINFOLOGPROC) getprocaddress("glGetShaderInfoLog"); glLinkProgram_ = (PFNGLLINKPROGRAMPROC) getprocaddress("glLinkProgram"); glGetUniformLocation_ = (PFNGLGETUNIFORMLOCATIONPROC) getprocaddress("glGetUniformLocation"); glUniform1f_ = (PFNGLUNIFORM1FPROC) getprocaddress("glUniform1f"); glUniform2f_ = (PFNGLUNIFORM2FPROC) getprocaddress("glUniform2f"); glUniform3f_ = (PFNGLUNIFORM3FPROC) getprocaddress("glUniform3f"); glUniform4f_ = (PFNGLUNIFORM4FPROC) getprocaddress("glUniform4f"); glUniform1fv_ = (PFNGLUNIFORM1FVPROC) getprocaddress("glUniform1fv"); glUniform2fv_ = (PFNGLUNIFORM2FVPROC) getprocaddress("glUniform2fv"); glUniform3fv_ = (PFNGLUNIFORM3FVPROC) getprocaddress("glUniform3fv"); glUniform4fv_ = (PFNGLUNIFORM4FVPROC) getprocaddress("glUniform4fv"); glUniform1i_ = (PFNGLUNIFORM1IPROC) getprocaddress("glUniform1i"); glBindAttribLocation_ = (PFNGLBINDATTRIBLOCATIONPROC) getprocaddress("glBindAttribLocation"); glGetActiveUniform_ = (PFNGLGETACTIVEUNIFORMPROC) getprocaddress("glGetActiveUniform"); glEnableVertexAttribArray_ = (PFNGLENABLEVERTEXATTRIBARRAYPROC) getprocaddress("glEnableVertexAttribArray"); glDisableVertexAttribArray_ = (PFNGLDISABLEVERTEXATTRIBARRAYPROC) getprocaddress("glDisableVertexAttribArray"); glVertexAttribPointer_ = (PFNGLVERTEXATTRIBPOINTERPROC) getprocaddress("glVertexAttribPointer"); if(glversion >= 210) { glUniformMatrix2x3fv_ = (PFNGLUNIFORMMATRIX2X3FVPROC) getprocaddress("glUniformMatrix2x3fv"); glUniformMatrix3x2fv_ = (PFNGLUNIFORMMATRIX3X2FVPROC) getprocaddress("glUniformMatrix3x2fv"); glUniformMatrix2x4fv_ = (PFNGLUNIFORMMATRIX2X4FVPROC) getprocaddress("glUniformMatrix2x4fv"); glUniformMatrix4x2fv_ = (PFNGLUNIFORMMATRIX4X2FVPROC) getprocaddress("glUniformMatrix4x2fv"); glUniformMatrix3x4fv_ = (PFNGLUNIFORMMATRIX3X4FVPROC) getprocaddress("glUniformMatrix3x4fv"); glUniformMatrix4x3fv_ = (PFNGLUNIFORMMATRIX4X3FVPROC) getprocaddress("glUniformMatrix4x3fv"); } #endif extern bool checkglslsupport(); if(checkglslsupport()) { hasGLSL = true; hasglsl = 1; #ifdef __APPLE__ //if(osversion<0x0A0500) ?? if(hasVP && hasFP) apple_glsldepth_bug = 1; #endif //if(apple_glsldepth_bug) conoutf(CON_WARN, "WARNING: Using Apple GLSL depth bug workaround. (use \"/apple_glsldepth_bug 0\" to disable if unnecessary"); const char *str = (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION); uint majorversion, minorversion; if(!str || sscanf(str, " %u.%u", &majorversion, &minorversion) != 2) glslversion = 100; else glslversion = majorversion*100 + minorversion; #ifdef __APPLE__ if(osversion >= 0x0A0600) { if(glslversion >= 120) preferglsl = 1; } else #endif if(glslversion >= 130) preferglsl = 1; } } extern int reservedynlighttc, reserveshadowmaptc, batchlightmaps, ffdynlights, fpdepthfx; if(ati) { //conoutf(CON_WARN, "WARNING: ATI cards may show garbage in skybox. (use \"/ati_skybox_bug 1\" to fix)"); reservedynlighttc = 2; reserveshadowmaptc = 3; minimizetcusage = 1; emulatefog = 1; if(hasTF && hasNVFB) fpdepthfx = 1; } else if(nvidia) { reservevpparams = 10; rtsharefb = 0; // work-around for strange driver stalls involving when using many FBOs extern int filltjoints; if(!hasext(exts, "GL_EXT_gpu_shader4")) filltjoints = 0; // DX9 or less NV cards seem to not cause many sparklies if(hasFBO && !hasTF) nvidia_scissor_bug = 1; // 5200 bug, clearing with scissor on an FBO messes up on reflections, may affect lesser cards too extern int fpdepthfx; if(hasTF && (!strstr(renderer, "GeForce") || !checkseries(renderer, 6000, 6600))) fpdepthfx = 1; // FP filtering causes software fallback on 6200? } else { if(intel) { #ifdef __APPLE__ apple_vp_bug = 1; intel_immediate_bug = 1; #endif #ifdef WIN32 intel_immediate_bug = 1; intel_vertexarray_bug = 1; #endif } if(!hasGLSL || !preferglsl) { avoidshaders = 1; if(hwtexsize < 4096) { maxtexsize = hwtexsize >= 2048 ? 512 : 256; batchlightmaps = 0; } if(!hasTF) ffdynlights = 0; } reservevpparams = 20; if(!hasOQ) waterrefract = 0; } bool hasshaders = (hasVP && hasFP) || hasGLSL; if(hasshaders) { extern int matskel; if(!avoidshaders) { matskel = 0; } } if(hasext(exts, "GL_NV_vertex_program2_option")) { usevp2 = 1; hasVP2 = true; } if(hasext(exts, "GL_NV_vertex_program3")) { usevp3 = 1; hasVP3 = true; } if(hasext(exts, "GL_EXT_gpu_program_parameters")) { glProgramEnvParameters4fv_ = (PFNGLPROGRAMENVPARAMETERS4FVEXTPROC) getprocaddress("glProgramEnvParameters4fvEXT"); glProgramLocalParameters4fv_ = (PFNGLPROGRAMLOCALPARAMETERS4FVEXTPROC)getprocaddress("glProgramLocalParameters4fvEXT"); hasPP = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_gpu_program_parameters extension."); } if(hasext(exts, "GL_ARB_map_buffer_range")) { glMapBufferRange_ = (PFNGLMAPBUFFERRANGEPROC) getprocaddress("glMapBufferRange"); glFlushMappedBufferRange_ = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)getprocaddress("glFlushMappedBufferRange"); hasMBR = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_map_buffer_range."); } if(hasext(exts, "GL_ARB_uniform_buffer_object")) { glGetUniformIndices_ = (PFNGLGETUNIFORMINDICESPROC) getprocaddress("glGetUniformIndices"); glGetActiveUniformsiv_ = (PFNGLGETACTIVEUNIFORMSIVPROC) getprocaddress("glGetActiveUniformsiv"); glGetUniformBlockIndex_ = (PFNGLGETUNIFORMBLOCKINDEXPROC) getprocaddress("glGetUniformBlockIndex"); glGetActiveUniformBlockiv_ = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)getprocaddress("glGetActiveUniformBlockiv"); glUniformBlockBinding_ = (PFNGLUNIFORMBLOCKBINDINGPROC) getprocaddress("glUniformBlockBinding"); glBindBufferBase_ = (PFNGLBINDBUFFERBASEPROC) getprocaddress("glBindBufferBase"); glBindBufferRange_ = (PFNGLBINDBUFFERRANGEPROC) getprocaddress("glBindBufferRange"); useubo = 1; hasUBO = true; if(ati) ati_ubo_bug = 1; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_uniform_buffer_object extension."); } else if(hasext(exts, "GL_EXT_bindable_uniform")) { glUniformBuffer_ = (PFNGLUNIFORMBUFFEREXTPROC) getprocaddress("glUniformBufferEXT"); glGetUniformBufferSize_ = (PFNGLGETUNIFORMBUFFERSIZEEXTPROC)getprocaddress("glGetUniformBufferSizeEXT"); glGetUniformOffset_ = (PFNGLGETUNIFORMOFFSETEXTPROC) getprocaddress("glGetUniformOffsetEXT"); usebue = 1; hasBUE = true; if(ati) ati_ubo_bug = 1; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_bindable_uniform extension."); } if(hasext(exts, "GL_EXT_texture_rectangle") || hasext(exts, "GL_ARB_texture_rectangle")) { usetexrect = 1; hasTR = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_texture_rectangle extension."); } else if(hasMT && hasshaders) conoutf(CON_WARN, "WARNING: No texture rectangle support. (no full screen shaders)"); if(hasext(exts, "GL_EXT_packed_depth_stencil") || hasext(exts, "GL_NV_packed_depth_stencil")) { hasDS = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_packed_depth_stencil extension."); } if(hasext(exts, "GL_EXT_blend_minmax")) { glBlendEquation_ = (PFNGLBLENDEQUATIONEXTPROC) getprocaddress("glBlendEquationEXT"); hasBE = true; if(ati) ati_minmax_bug = 1; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_blend_minmax extension."); } if(hasext(exts, "GL_EXT_blend_color")) { glBlendColor_ = (PFNGLBLENDCOLOREXTPROC) getprocaddress("glBlendColorEXT"); hasBC = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_blend_color extension."); } if(hasext(exts, "GL_EXT_fog_coord")) { glFogCoordPointer_ = (PFNGLFOGCOORDPOINTEREXTPROC) getprocaddress("glFogCoordPointerEXT"); hasFC = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_fog_coord extension."); } if(hasext(exts, "GL_ARB_texture_cube_map")) { GLint val; glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, &val); hwcubetexsize = val; hasCM = true; // On Catalyst 10.2, issuing an occlusion query on the first draw using a given cubemap texture causes a nasty crash if(ati) ati_cubemap_bug = 1; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_texture_cube_map extension."); } else conoutf(CON_WARN, "WARNING: No cube map texture support. (no reflective glass)"); extern int usenp2; if(hasext(exts, "GL_ARB_texture_non_power_of_two")) { hasNP2 = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_texture_non_power_of_two extension."); } else if(usenp2) conoutf(CON_WARN, "WARNING: Non-power-of-two textures not supported!"); if(hasext(exts, "GL_ARB_texture_compression")) { glCompressedTexImage3D_ = (PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) getprocaddress("glCompressedTexImage3DARB"); glCompressedTexImage2D_ = (PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) getprocaddress("glCompressedTexImage2DARB"); glCompressedTexImage1D_ = (PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) getprocaddress("glCompressedTexImage1DARB"); glCompressedTexSubImage3D_ = (PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC)getprocaddress("glCompressedTexSubImage3DARB"); glCompressedTexSubImage2D_ = (PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC)getprocaddress("glCompressedTexSubImage2DARB"); glCompressedTexSubImage1D_ = (PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC)getprocaddress("glCompressedTexSubImage1DARB"); glGetCompressedTexImage_ = (PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) getprocaddress("glGetCompressedTexImageARB"); hasTC = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_texture_compression."); if(hasext(exts, "GL_EXT_texture_compression_s3tc")) { hasS3TC = true; #ifdef __APPLE__ usetexcompress = 1; #else if(!mesa) usetexcompress = 2; #endif if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_texture_compression_s3tc extension."); } else if(hasext(exts, "GL_EXT_texture_compression_dxt1") && hasext(exts, "GL_ANGLE_texture_compression_dxt3") && hasext(exts, "GL_ANGLE_texture_compression_dxt5")) { hasS3TC = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_texture_compression_dxt1 extension."); } if(hasext(exts, "GL_3DFX_texture_compression_FXT1")) { hasFXT1 = true; if(mesa) usetexcompress = max(usetexcompress, 1); if(dbgexts) conoutf(CON_INIT, "Using GL_3DFX_texture_compression_FXT1."); } } if(hasext(exts, "GL_EXT_texture_filter_anisotropic")) { GLint val; glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &val); hwmaxaniso = val; hasAF = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_texture_filter_anisotropic extension."); } if(hasext(exts, "GL_SGIS_generate_mipmap")) { hasGM = true; if(dbgexts) conoutf(CON_INIT, "Using GL_SGIS_generate_mipmap extension."); } if(hasext(exts, "GL_ARB_depth_texture")) { hasSGIDT = hasDT = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_depth_texture extension."); } else if(hasext(exts, "GL_SGIX_depth_texture")) { hasSGIDT = true; if(dbgexts) conoutf(CON_INIT, "Using GL_SGIX_depth_texture extension."); } if(hasext(exts, "GL_ARB_shadow")) { hasSGISH = hasSH = true; if(nvidia || (ati && strstr(renderer, "Radeon HD"))) hasNVPCF = true; if(dbgexts) conoutf(CON_INIT, "Using GL_ARB_shadow extension."); } else if(hasext(exts, "GL_SGIX_shadow")) { hasSGISH = true; if(dbgexts) conoutf(CON_INIT, "Using GL_SGIX_shadow extension."); } if(hasext(exts, "GL_EXT_rescale_normal")) { hasRN = true; if(dbgexts) conoutf(CON_INIT, "Using GL_EXT_rescale_normal extension."); } if(!hasSGIDT && !hasSGISH) shadowmap = 0; if(hasext(exts, "GL_EXT_gpu_shader4") && !avoidshaders) { // on DX10 or above class cards (i.e. GF8 or RadeonHD) enable expensive features extern int grass, glare, maxdynlights, depthfxsize, depthfxrect, depthfxfilter, blurdepthfx; grass = 1; if(hasOQ) { waterfallrefract = 1; glare = 1; maxdynlights = MAXDYNLIGHTS; if(hasTR) { depthfxsize = 10; depthfxrect = 1; depthfxfilter = 0; blurdepthfx = 0; } } } } void glext(char *ext) { const char *exts = (const char *)glGetString(GL_EXTENSIONS); intret(hasext(exts, ext) ? 1 : 0); } COMMAND(glext, "s"); void gl_init(int w, int h, int bpp, int depth, int fsaa) { glViewport(0, 0, w, h); glClearColor(0, 0, 0, 0); glClearDepth(1); glDepthFunc(GL_LESS); glDisable(GL_DEPTH_TEST); glShadeModel(GL_SMOOTH); glDisable(GL_FOG); glFogi(GL_FOG_MODE, GL_LINEAR); //glHint(GL_FOG_HINT, GL_NICEST); GLfloat fogcolor[4] = { 0, 0, 0, 0 }; glFogfv(GL_FOG_COLOR, fogcolor); glEnable(GL_LINE_SMOOTH); //glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glFrontFace(GL_CW); glCullFace(GL_BACK); glDisable(GL_CULL_FACE); #ifdef __APPLE__ if(sdl_backingstore_bug) { if(fsaa) { sdl_backingstore_bug = 1; // since SDL doesn't add kCGLPFABackingStore to the pixelformat and so it isn't guaranteed to be preserved - only manifests when using fsaa? //conoutf(CON_WARN, "WARNING: Using SDL backingstore workaround. (use \"/sdl_backingstore_bug 0\" to disable if unnecessary)"); } else sdl_backingstore_bug = -1; } #endif extern int useshaders, forceglsl; bool hasshaders = (hasVP && hasFP) || hasGLSL; if(!useshaders || (useshaders<0 && avoidshaders) || !hasMT || !hasshaders) { if(!hasMT || !hasshaders) conoutf(CON_WARN, "WARNING: No shader support! Using fixed-function fallback. (no fancy visuals for you)"); else if(useshaders<0 && avoidshaders) conoutf(CON_WARN, "WARNING: Disabling shaders for extra performance. (use \"/shaders 1\" to enable shaders if desired)"); renderpath = R_FIXEDFUNCTION; } else renderpath = hasGLSL ? ((forceglsl && (forceglsl > 0 || preferglsl)) || !hasVP || !hasFP ? (forceglsl ? R_GLSLANG : R_FIXEDFUNCTION) : R_ASMGLSLANG) : R_ASMSHADER; extern void setupshaders(); setupshaders(); static const char * const rpnames[4] = { "fixed-function", "assembly shader", "GLSL shader", "assembly/GLSL shader" }; conoutf(CON_INIT, "Rendering using the OpenGL %s path.", rpnames[renderpath]); inittmus(); setuptexcompress(); } void cleanupgl() { extern int nomasks, nolights, nowater; nomasks = nolights = nowater = 0; extern void cleanupmotionblur(); cleanupmotionblur(); extern void clearminimap(); clearminimap(); } #define VARRAY_INTERNAL #include "varray.h" VAR(wireframe, 0, 0, 1); ICOMMAND(getcamyaw, "", (), floatret(camera1->yaw)); ICOMMAND(getcampitch, "", (), floatret(camera1->pitch)); ICOMMAND(getcamroll, "", (), floatret(camera1->roll)); ICOMMAND(getcampos, "", (), { defformatstring(pos)("%s %s %s", floatstr(camera1->o.x), floatstr(camera1->o.y), floatstr(camera1->o.z)); result(pos); }); vec worldpos, camdir, camright, camup; void findorientation() { vecfromyawpitch(camera1->yaw, camera1->pitch, 1, 0, camdir); vecfromyawpitch(camera1->yaw, 0, 0, -1, camright); vecfromyawpitch(camera1->yaw, camera1->pitch+90, 1, 0, camup); if(raycubepos(camera1->o, camdir, worldpos, 0, RAY_CLIPMAT|RAY_SKIPFIRST) == -1) worldpos = vec(camdir).mul(2*worldsize).add(camera1->o); //otherwise 3dgui won't work when outside of map } void transplayer() { // move from RH to Z-up LH quake style worldspace glLoadMatrixf(viewmatrix.v); glRotatef(camera1->roll, 0, 1, 0); glRotatef(camera1->pitch, -1, 0, 0); glRotatef(camera1->yaw, 0, 0, -1); glTranslatef(-camera1->o.x, -camera1->o.y, -camera1->o.z); } float curfov = 100, curavatarfov = 65, fovy, aspect; int farplane; VARP(zoominvel, 0, 250, 5000); VARP(zoomoutvel, 0, 100, 5000); VARP(zoomfov, 10, 35, 60); VARP(fov, 10, 100, 150); VAR(avatarzoomfov, 10, 25, 60); VAR(avatarfov, 10, 65, 150); FVAR(avatardepth, 0, 0.5f, 1); FVARNP(aspect, forceaspect, 0, 0, 1e3f); static int zoommillis = 0; VARF(zoom, -1, 0, 1, if(zoom) zoommillis = totalmillis; ); void disablezoom() { zoom = 0; zoommillis = totalmillis; } void computezoom() { if(!zoom) { curfov = fov; curavatarfov = avatarfov; return; } if(zoom < 0 && curfov >= fov) { zoom = 0; curfov = fov; curavatarfov = avatarfov; return; } // don't zoom-out if not zoomed-in int zoomvel = zoom > 0 ? zoominvel : zoomoutvel, oldfov = zoom > 0 ? fov : zoomfov, newfov = zoom > 0 ? zoomfov : fov, oldavatarfov = zoom > 0 ? avatarfov : avatarzoomfov, newavatarfov = zoom > 0 ? avatarzoomfov : avatarfov; float t = zoomvel ? float(zoomvel - (totalmillis - zoommillis)) / zoomvel : 0; if(t <= 0) { if(!zoomvel && fabs(newfov - curfov) >= 1) { curfov = newfov; curavatarfov = newavatarfov; } zoom = max(zoom, 0); } else { curfov = oldfov*t + newfov*(1 - t); curavatarfov = oldavatarfov*t + newavatarfov*(1 - t); } } FVARP(zoomsens, 1e-3f, 1, 1000); FVARP(zoomaccel, 0, 0, 1000); VARP(zoomautosens, 0, 1, 1); FVARP(sensitivity, 1e-3f, 3, 1000); FVARP(sensitivityscale, 1e-3f, 1, 1000); VARP(invmouse, 0, 0, 1); FVARP(mouseaccel, 0, 0, 1000); VAR(thirdperson, 0, 0, 2); FVAR(thirdpersondistance, 0, 20, 50); FVAR(thirdpersonup, -25, 0, 25); FVAR(thirdpersonside, -25, 0, 25); physent *camera1 = NULL; bool detachedcamera = false; bool isthirdperson() { return player!=camera1 || detachedcamera || reflecting; } void fixcamerarange() { const float MAXPITCH = 90.0f; if(camera1->pitch>MAXPITCH) camera1->pitch = MAXPITCH; if(camera1->pitch<-MAXPITCH) camera1->pitch = -MAXPITCH; while(camera1->yaw<0.0f) camera1->yaw += 360.0f; while(camera1->yaw>=360.0f) camera1->yaw -= 360.0f; } void mousemove(int dx, int dy) { if(!game::allowmouselook()) return; float cursens = sensitivity, curaccel = mouseaccel; if(zoom) { if(zoomautosens) { cursens = float(sensitivity*zoomfov)/fov; curaccel = float(mouseaccel*zoomfov)/fov; } else { cursens = zoomsens; curaccel = zoomaccel; } } if(curaccel && curtime && (dx || dy)) cursens += curaccel * sqrtf(dx*dx + dy*dy)/curtime; cursens /= 33.0f*sensitivityscale; camera1->yaw += dx*cursens; camera1->pitch -= dy*cursens*(invmouse ? -1 : 1); fixcamerarange(); if(camera1!=player && !detachedcamera) { player->yaw = camera1->yaw; player->pitch = camera1->pitch; } } void recomputecamera() { game::setupcamera(); computezoom(); bool shoulddetach = thirdperson > 1 || game::detachcamera(); if(!thirdperson && !shoulddetach) { camera1 = player; detachedcamera = false; } else { static physent tempcamera; camera1 = &tempcamera; if(detachedcamera && shoulddetach) camera1->o = player->o; else { *camera1 = *player; detachedcamera = shoulddetach; } camera1->reset(); camera1->type = ENT_CAMERA; camera1->collidetype = COLLIDE_AABB; camera1->move = -1; camera1->eyeheight = camera1->aboveeye = camera1->radius = camera1->xradius = camera1->yradius = 2; vec dir, up, side; vecfromyawpitch(camera1->yaw, camera1->pitch, -1, 0, dir); vecfromyawpitch(camera1->yaw, camera1->pitch+90, 1, 0, up); vecfromyawpitch(camera1->yaw, 0, 0, -1, side); if(game::collidecamera()) { movecamera(camera1, dir, thirdpersondistance, 1); movecamera(camera1, dir, clamp(thirdpersondistance - camera1->o.dist(player->o), 0.0f, 1.0f), 0.1f); if(thirdpersonup) { vec pos = camera1->o; float dist = fabs(thirdpersonup); if(thirdpersonup < 0) up.neg(); movecamera(camera1, up, dist, 1); movecamera(camera1, up, clamp(dist - camera1->o.dist(pos), 0.0f, 1.0f), 0.1f); } if(thirdpersonside) { vec pos = camera1->o; float dist = fabs(thirdpersonside); if(thirdpersonside < 0) side.neg(); movecamera(camera1, side, dist, 1); movecamera(camera1, side, clamp(dist - camera1->o.dist(pos), 0.0f, 1.0f), 0.1f); } } else { camera1->o.add(vec(dir).mul(thirdpersondistance)); if(thirdpersonup) camera1->o.add(vec(up).mul(thirdpersonup)); if(thirdpersonside) camera1->o.add(vec(side).mul(thirdpersonside)); } } setviewcell(camera1->o); } extern const glmatrixf viewmatrix(vec4(-1, 0, 0, 0), vec4(0, 0, 1, 0), vec4(0, -1, 0, 0)); glmatrixf mvmatrix, projmatrix, mvpmatrix, invmvmatrix, invmvpmatrix; void readmatrices() { glGetFloatv(GL_MODELVIEW_MATRIX, mvmatrix.v); glGetFloatv(GL_PROJECTION_MATRIX, projmatrix.v); mvpmatrix.mul(projmatrix, mvmatrix); invmvmatrix.invert(mvmatrix); invmvpmatrix.invert(mvpmatrix); } FVAR(nearplane, 0.01f, 0.54f, 2.0f); void project(float fovy, float aspect, int farplane, bool flipx = false, bool flipy = false, bool swapxy = false, float zscale = 1) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); if(swapxy) glRotatef(90, 0, 0, 1); if(flipx || flipy!=swapxy || zscale!=1) glScalef(flipx ? -1 : 1, flipy!=swapxy ? -1 : 1, zscale); GLdouble ydist = nearplane * tan(fovy/2*RAD), xdist = ydist * aspect; glFrustum(-xdist, xdist, -ydist, ydist, nearplane, farplane); glMatrixMode(GL_MODELVIEW); } vec calcavatarpos(const vec &pos, float dist) { vec eyepos; mvmatrix.transform(pos, eyepos); GLdouble ydist = nearplane * tan(curavatarfov/2*RAD), xdist = ydist * aspect; vec4 scrpos; scrpos.x = eyepos.x*nearplane/xdist; scrpos.y = eyepos.y*nearplane/ydist; scrpos.z = (eyepos.z*(farplane + nearplane) - 2*nearplane*farplane) / (farplane - nearplane); scrpos.w = -eyepos.z; vec worldpos = invmvpmatrix.perspectivetransform(scrpos); vec dir = vec(worldpos).sub(camera1->o).rescale(dist); return dir.add(camera1->o); } VAR(reflectclip, 0, 6, 64); VAR(reflectclipavatar, -64, 0, 64); glmatrixf clipmatrix; static const glmatrixf dummymatrix; static int projectioncount = 0; void pushprojection(const glmatrixf &m = dummymatrix) { glMatrixMode(GL_PROJECTION); if(projectioncount <= 0) glPushMatrix(); if(&m != &dummymatrix) glLoadMatrixf(m.v); if(fogging) { glMultMatrixf(mvmatrix.v); glMultMatrixf(invfogmatrix.v); } glMatrixMode(GL_MODELVIEW); projectioncount++; } void popprojection() { --projectioncount; glMatrixMode(GL_PROJECTION); glPopMatrix(); if(projectioncount > 0) { glPushMatrix(); if(fogging) { glMultMatrixf(mvmatrix.v); glMultMatrixf(invfogmatrix.v); } } glMatrixMode(GL_MODELVIEW); } FVAR(polygonoffsetfactor, -1e4f, -3.0f, 1e4f); FVAR(polygonoffsetunits, -1e4f, -3.0f, 1e4f); FVAR(depthoffset, -1e4f, 0.01f, 1e4f); void enablepolygonoffset(GLenum type) { if(!depthoffset) { glPolygonOffset(polygonoffsetfactor, polygonoffsetunits); glEnable(type); return; } bool clipped = reflectz < 1e15f && reflectclip; glmatrixf offsetmatrix = clipped ? clipmatrix : projmatrix; offsetmatrix[14] += depthoffset * projmatrix[10]; glMatrixMode(GL_PROJECTION); if(!clipped) glPushMatrix(); glLoadMatrixf(offsetmatrix.v); if(fogging) { glMultMatrixf(mvmatrix.v); glMultMatrixf(invfogmatrix.v); } glMatrixMode(GL_MODELVIEW); } void disablepolygonoffset(GLenum type) { if(!depthoffset) { glDisable(type); return; } bool clipped = reflectz < 1e15f && reflectclip; glMatrixMode(GL_PROJECTION); if(clipped) { glLoadMatrixf(clipmatrix.v); if(fogging) { glMultMatrixf(mvmatrix.v); glMultMatrixf(invfogmatrix.v); } } else glPopMatrix(); glMatrixMode(GL_MODELVIEW); } void calcspherescissor(const vec ¢er, float size, float &sx1, float &sy1, float &sx2, float &sy2) { vec worldpos(center); if(reflecting) worldpos.z = 2*reflectz - worldpos.z; vec e(mvmatrix.transformx(worldpos), mvmatrix.transformy(worldpos), mvmatrix.transformz(worldpos)); if(e.z > 2*size) { sx1 = sy1 = 1; sx2 = sy2 = -1; return; } float zzrr = e.z*e.z - size*size, dx = e.x*e.x + zzrr, dy = e.y*e.y + zzrr, focaldist = 1.0f/tan(fovy*0.5f*RAD); sx1 = sy1 = -1; sx2 = sy2 = 1; #define CHECKPLANE(c, dir, focaldist, low, high) \ do { \ float nzc = (cz*cz + 1) / (cz dir drt) - cz, \ pz = (d##c)/(nzc*e.c - e.z); \ if(pz > 0) \ { \ float c = (focaldist)*nzc, \ pc = pz*nzc; \ if(pc < e.c) low = c; \ else if(pc > e.c) high = c; \ } \ } while(0) if(dx > 0) { float cz = e.x/e.z, drt = sqrtf(dx)/size; CHECKPLANE(x, -, focaldist/aspect, sx1, sx2); CHECKPLANE(x, +, focaldist/aspect, sx1, sx2); } if(dy > 0) { float cz = e.y/e.z, drt = sqrtf(dy)/size; CHECKPLANE(y, -, focaldist, sy1, sy2); CHECKPLANE(y, +, focaldist, sy1, sy2); } } static int scissoring = 0; static GLint oldscissor[4]; int pushscissor(float sx1, float sy1, float sx2, float sy2) { scissoring = 0; if(sx1 <= -1 && sy1 <= -1 && sx2 >= 1 && sy2 >= 1) return 0; sx1 = max(sx1, -1.0f); sy1 = max(sy1, -1.0f); sx2 = min(sx2, 1.0f); sy2 = min(sy2, 1.0f); GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); int sx = viewport[0] + int(floor((sx1+1)*0.5f*viewport[2])), sy = viewport[1] + int(floor((sy1+1)*0.5f*viewport[3])), sw = viewport[0] + int(ceil((sx2+1)*0.5f*viewport[2])) - sx, sh = viewport[1] + int(ceil((sy2+1)*0.5f*viewport[3])) - sy; if(sw <= 0 || sh <= 0) return 0; if(glIsEnabled(GL_SCISSOR_TEST)) { glGetIntegerv(GL_SCISSOR_BOX, oldscissor); sw += sx; sh += sy; sx = max(sx, int(oldscissor[0])); sy = max(sy, int(oldscissor[1])); sw = min(sw, int(oldscissor[0] + oldscissor[2])) - sx; sh = min(sh, int(oldscissor[1] + oldscissor[3])) - sy; if(sw <= 0 || sh <= 0) return 0; scissoring = 2; } else scissoring = 1; glScissor(sx, sy, sw, sh); if(scissoring<=1) glEnable(GL_SCISSOR_TEST); return scissoring; } void popscissor() { if(scissoring>1) glScissor(oldscissor[0], oldscissor[1], oldscissor[2], oldscissor[3]); else if(scissoring) glDisable(GL_SCISSOR_TEST); scissoring = 0; } glmatrixf envmatrix; void setenvmatrix() { envmatrix = fogging ? fogmatrix : mvmatrix; if(reflecting) envmatrix.reflectz(reflectz); envmatrix.transpose(); } VARR(fog, 16, 4000, 1000024); bvec fogcolor(0x80, 0x99, 0xB3); HVARFR(fogcolour, 0, 0x8099B3, 0xFFFFFF, { fogcolor = bvec((fogcolour>>16)&0xFF, (fogcolour>>8)&0xFF, fogcolour&0xFF); }); static float findsurface(int fogmat, const vec &v, int &abovemat) { fogmat &= MATF_VOLUME; ivec o(v), co; int csize; do { cube &c = lookupcube(o.x, o.y, o.z, 0, co, csize); int mat = c.material&MATF_VOLUME; if(mat != fogmat) { abovemat = isliquid(mat) ? c.material : MAT_AIR; return o.z; } o.z = co.z + csize; } while(o.z < worldsize); abovemat = MAT_AIR; return worldsize; } static void blendfog(int fogmat, float blend, float logblend, float &start, float &end, float *fogc) { switch(fogmat&MATF_VOLUME) { case MAT_WATER: { const bvec &wcol = getwatercolor(fogmat); int wfog = getwaterfog(fogmat); loopk(3) fogc[k] += blend*wcol[k]/255.0f; end += logblend*min(fog, max(wfog*4, 32)); break; } case MAT_LAVA: { const bvec &lcol = getlavacolor(fogmat); int lfog = getlavafog(fogmat); loopk(3) fogc[k] += blend*lcol[k]/255.0f; end += logblend*min(fog, max(lfog*4, 32)); break; } default: loopk(3) fogc[k] += blend*fogcolor[k]/255.0f; start += logblend*(fog+64)/8; end += logblend*fog; break; } } static void setfog(int fogmat, float below = 1, int abovemat = MAT_AIR) { float fogc[4] = { 0, 0, 0, 1 }; float start = 0, end = 0; float logscale = 256, logblend = log(1 + (logscale - 1)*below) / log(logscale); blendfog(fogmat, below, logblend, start, end, fogc); if(below < 1) blendfog(abovemat, 1-below, 1-logblend, start, end, fogc); glFogf(GL_FOG_START, start); glFogf(GL_FOG_END, end); glFogfv(GL_FOG_COLOR, fogc); glClearColor(fogc[0], fogc[1], fogc[2], 1.0f); } static void blendfogoverlay(int fogmat, float blend, float *overlay) { float maxc; switch(fogmat&MATF_VOLUME) { case MAT_WATER: { const bvec &wcol = getwatercolor(fogmat); maxc = max(wcol[0], max(wcol[1], wcol[2])); loopk(3) overlay[k] += blend*max(0.4f, wcol[k]/min(32.0f + maxc*7.0f/8.0f, 255.0f)); break; } case MAT_LAVA: { const bvec &lcol = getlavacolor(fogmat); maxc = max(lcol[0], max(lcol[1], lcol[2])); loopk(3) overlay[k] += blend*max(0.4f, lcol[k]/min(32.0f + maxc*7.0f/8.0f, 255.0f)); break; } default: loopk(3) overlay[k] += blend; break; } } void drawfogoverlay(int fogmat, float fogblend, int abovemat) { notextureshader->set(); glDisable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_ZERO, GL_SRC_COLOR); float overlay[3] = { 0, 0, 0 }; blendfogoverlay(fogmat, fogblend, overlay); blendfogoverlay(abovemat, 1-fogblend, overlay); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glColor3fv(overlay); glBegin(GL_TRIANGLE_STRIP); glVertex2f(-1, -1); glVertex2f(1, -1); glVertex2f(-1, 1); glVertex2f(1, 1); glEnd(); glDisable(GL_BLEND); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glEnable(GL_TEXTURE_2D); defaultshader->set(); } bool renderedgame = false; void rendergame(bool mainpass) { game::rendergame(mainpass); if(!shadowmapping) renderedgame = true; } VARP(skyboxglare, 0, 1, 1); void drawglare() { glaring = true; refracting = -1; float oldfogstart, oldfogend, oldfogcolor[4], zerofog[4] = { 0, 0, 0, 1 }; glGetFloatv(GL_FOG_START, &oldfogstart); glGetFloatv(GL_FOG_END, &oldfogend); glGetFloatv(GL_FOG_COLOR, oldfogcolor); glFogf(GL_FOG_START, (fog+64)/8); glFogf(GL_FOG_END, fog); glFogfv(GL_FOG_COLOR, zerofog); glClearColor(0, 0, 0, 1); glClear((skyboxglare ? 0 : GL_COLOR_BUFFER_BIT) | GL_DEPTH_BUFFER_BIT); rendergeom(); if(skyboxglare) drawskybox(farplane, false); renderreflectedmapmodels(); rendergame(); if(!isthirdperson()) { project(curavatarfov, aspect, farplane, false, false, false, avatardepth); game::renderavatar(); project(fovy, aspect, farplane); } renderwater(); rendermaterials(); renderalphageom(); renderparticles(); glFogf(GL_FOG_START, oldfogstart); glFogf(GL_FOG_END, oldfogend); glFogfv(GL_FOG_COLOR, oldfogcolor); refracting = 0; glaring = false; } VARP(reflectmms, 0, 1, 1); VARR(refractsky, 0, 0, 1); glmatrixf fogmatrix, invfogmatrix; void drawreflection(float z, bool refract, int fogdepth, const bvec &col) { reflectz = z < 0 ? 1e16f : z; reflecting = !refract; refracting = refract ? (z < 0 || camera1->o.z >= z ? -1 : 1) : 0; fading = renderpath!=R_FIXEDFUNCTION && waterrefract && waterfade && hasFBO && z>=0; fogging = refracting<0 && z>=0; refractfog = fogdepth; refractcolor = fogging ? col : fogcolor; float oldfogstart, oldfogend, oldfogcolor[4]; glGetFloatv(GL_FOG_START, &oldfogstart); glGetFloatv(GL_FOG_END, &oldfogend); glGetFloatv(GL_FOG_COLOR, oldfogcolor); if(fogging) { glFogf(GL_FOG_START, camera1->o.z - z); glFogf(GL_FOG_END, camera1->o.z - (z-max(refractfog, 1))); GLfloat m[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -camera1->o.x, -camera1->o.y, -camera1->o.z, 1 }; memcpy(fogmatrix.v, m, sizeof(m)); invfogmatrix.invert(fogmatrix); pushprojection(); glPushMatrix(); glLoadMatrixf(fogmatrix.v); float fogc[4] = { col.x/255.0f, col.y/255.0f, col.z/255.0f, 1.0f }; glFogfv(GL_FOG_COLOR, fogc); } else { glFogf(GL_FOG_START, (fog+64)/8); glFogf(GL_FOG_END, fog); float fogc[4] = { fogcolor.x/255.0f, fogcolor.y/255.0f, fogcolor.z/255.0f, 1.0f }; glFogfv(GL_FOG_COLOR, fogc); } if(fading) { float scale = fogging ? -0.25f : 0.25f, offset = 2*fabs(scale) - scale*z; setenvparamf("waterfadeparams", SHPARAM_VERTEX, 8, scale, offset, -scale, offset + camera1->o.z*scale); setenvparamf("waterfadeparams", SHPARAM_PIXEL, 8, scale, offset, -scale, offset + camera1->o.z*scale); } if(reflecting) { glPushMatrix(); glTranslatef(0, 0, 2*z); glScalef(1, 1, -1); glFrontFace(GL_CCW); } setenvmatrix(); if(reflectclip && z>=0) { float zoffset = reflectclip/4.0f, zclip; if(refracting<0) { zclip = z+zoffset; if(camera1->o.z<=zclip) zclip = z; } else { zclip = z-zoffset; if(camera1->o.z>=zclip && camera1->o.z<=z+4.0f) zclip = z; if(reflecting) zclip = 2*z - zclip; } plane clipplane; invmvmatrix.transposedtransform(plane(0, 0, refracting>0 ? 1 : -1, refracting>0 ? -zclip : zclip), clipplane); clipmatrix.clip(clipplane, projmatrix); pushprojection(clipmatrix); } renderreflectedgeom(refracting<0 && z>=0 && caustics, fogging); if(reflecting || refracting>0 || (refracting<0 && refractsky) || z<0) { if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); if(reflectclip && z>=0) popprojection(); if(fogging) { popprojection(); glPopMatrix(); } drawskybox(farplane, false); if(fogging) { pushprojection(); glPushMatrix(); glLoadMatrixf(fogmatrix.v); } if(reflectclip && z>=0) pushprojection(clipmatrix); if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); } else if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); renderdecals(); if(reflectmms) renderreflectedmapmodels(); rendergame(); if(refracting && z>=0 && !isthirdperson() && fabs(camera1->o.z-z) <= 0.5f*(player->eyeheight + player->aboveeye)) { glmatrixf avatarproj; avatarproj.perspective(curavatarfov, aspect, nearplane, farplane); if(reflectclip) { popprojection(); glmatrixf avatarclip; plane clipplane; invmvmatrix.transposedtransform(plane(0, 0, refracting, reflectclipavatar/4.0f - refracting*z), clipplane); avatarclip.clip(clipplane, avatarproj); pushprojection(avatarclip); } else pushprojection(avatarproj); game::renderavatar(); popprojection(); if(reflectclip) pushprojection(clipmatrix); } if(refracting) rendergrass(); rendermaterials(); renderalphageom(fogging); renderparticles(); if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); if(reflectclip && z>=0) popprojection(); if(reflecting) { glPopMatrix(); glFrontFace(GL_CW); } if(fogging) { popprojection(); glPopMatrix(); } glFogf(GL_FOG_START, oldfogstart); glFogf(GL_FOG_END, oldfogend); glFogfv(GL_FOG_COLOR, oldfogcolor); reflectz = 1e16f; refracting = 0; reflecting = fading = fogging = false; setenvmatrix(); } bool envmapping = false; void drawcubemap(int size, const vec &o, float yaw, float pitch, const cubemapside &side) { envmapping = true; physent *oldcamera = camera1; static physent cmcamera; cmcamera = *player; cmcamera.reset(); cmcamera.type = ENT_CAMERA; cmcamera.o = o; cmcamera.yaw = yaw; cmcamera.pitch = pitch; cmcamera.roll = 0; camera1 = &cmcamera; setviewcell(camera1->o); defaultshader->set(); int fogmat = lookupmaterial(o)&(MATF_VOLUME|MATF_INDEX); setfog(fogmat); glClear(GL_DEPTH_BUFFER_BIT); int farplane = worldsize*2; project(90.0f, 1.0f, farplane, !side.flipx, !side.flipy, side.swapxy); transplayer(); readmatrices(); findorientation(); setenvmatrix(); glEnable(GL_FOG); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); xtravertsva = xtraverts = glde = gbatches = 0; visiblecubes(); if(limitsky()) drawskybox(farplane, true); rendergeom(); if(!limitsky()) drawskybox(farplane, false); // queryreflections(); rendermapmodels(); renderalphageom(); // drawreflections(); // renderwater(); // rendermaterials(); glDisable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_FOG); camera1 = oldcamera; envmapping = false; } bool modelpreviewing = false; namespace modelpreview { physent *oldcamera; float oldfogstart, oldfogend, oldfogcolor[4]; physent camera; void start(bool background) { float fovy = 90.f, aspect = 1.f; envmapping = modelpreviewing = true; oldcamera = camera1; camera = *camera1; camera.reset(); camera.type = ENT_CAMERA; camera.o = vec(0, 0, 0); camera.yaw = 0; camera.pitch = 0; camera.roll = 0; camera1 = &camera; glGetFloatv(GL_FOG_START, &oldfogstart); glGetFloatv(GL_FOG_END, &oldfogend); glGetFloatv(GL_FOG_COLOR, oldfogcolor); GLfloat fogc[4] = { 0, 0, 0, 1 }; glFogf(GL_FOG_START, 0); glFogf(GL_FOG_END, 1000000); glFogfv(GL_FOG_COLOR, fogc); glClearColor(fogc[0], fogc[1], fogc[2], fogc[3]); glClear((background ? GL_COLOR_BUFFER_BIT : 0) | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); project(fovy, aspect, 1024); transplayer(); readmatrices(); setenvmatrix(); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); } void end() { glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); defaultshader->set(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glFogf(GL_FOG_START, oldfogstart); glFogf(GL_FOG_END, oldfogend); glFogfv(GL_FOG_COLOR, oldfogcolor); glClearColor(oldfogcolor[0], oldfogcolor[1], oldfogcolor[2], oldfogcolor[3]); camera1 = oldcamera; envmapping = modelpreviewing = false; } } bool minimapping = false; GLuint minimaptex = 0; vec minimapcenter(0, 0, 0), minimapradius(0, 0, 0), minimapscale(0, 0, 0); void clearminimap() { if(minimaptex) { glDeleteTextures(1, &minimaptex); minimaptex = 0; } } VARR(minimapheight, 0, 0, 2<<16); bvec minimapcolor(0, 0, 0); HVARFR(minimapcolour, 0, 0, 0xFFFFFF, { minimapcolor = bvec((minimapcolour>>16)&0xFF, (minimapcolour>>8)&0xFF, minimapcolour&0xFF); }); VARR(minimapclip, 0, 0, 1); VARFP(minimapsize, 7, 8, 10, { if(minimaptex) drawminimap(); }); void bindminimap() { glBindTexture(GL_TEXTURE_2D, minimaptex); } void clipminimap(ivec &bbmin, ivec &bbmax, cube *c = worldroot, int x = 0, int y = 0, int z = 0, int size = worldsize>>1) { loopi(8) { ivec o(i, x, y, z, size); if(c[i].children) clipminimap(bbmin, bbmax, c[i].children, o.x, o.y, o.z, size>>1); else if(!isentirelysolid(c[i]) && (c[i].material&MATF_CLIP)!=MAT_CLIP) { loopk(3) bbmin[k] = min(bbmin[k], o[k]); loopk(3) bbmax[k] = max(bbmax[k], o[k] + size); } } } void drawminimap() { if(!game::needminimap()) { clearminimap(); return; } renderprogress(0, "generating mini-map...", 0, !renderedframe); int size = 1<w, screen->h)); while(size > sizelimit) size /= 2; if(!minimaptex) glGenTextures(1, &minimaptex); extern vector valist; ivec bbmin(worldsize, worldsize, worldsize), bbmax(0, 0, 0); loopv(valist) { vtxarray *va = valist[i]; loopk(3) { if(va->geommin[k]>va->geommax[k]) continue; bbmin[k] = min(bbmin[k], va->geommin[k]); bbmax[k] = max(bbmax[k], va->geommax[k]); } } if(minimapclip) { ivec clipmin(worldsize, worldsize, worldsize), clipmax(0, 0, 0); clipminimap(clipmin, clipmax); loopk(2) bbmin[k] = max(bbmin[k], clipmin[k]); loopk(2) bbmax[k] = min(bbmax[k], clipmax[k]); } minimapradius = bbmax.tovec().sub(bbmin.tovec()).mul(0.5f); minimapcenter = bbmin.tovec().add(minimapradius); minimapradius.x = minimapradius.y = max(minimapradius.x, minimapradius.y); minimapscale = vec((0.5f - 1.0f/size)/minimapradius.x, (0.5f - 1.0f/size)/minimapradius.y, 1.0f); envmapping = minimapping = true; physent *oldcamera = camera1; static physent cmcamera; cmcamera = *player; cmcamera.reset(); cmcamera.type = ENT_CAMERA; cmcamera.o = vec(minimapcenter.x, minimapcenter.y, max(minimapcenter.z + minimapradius.z + 1, float(minimapheight))); cmcamera.yaw = 0; cmcamera.pitch = -90; cmcamera.roll = 0; camera1 = &cmcamera; setviewcell(vec(-1, -1, -1)); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-minimapradius.x, minimapradius.x, -minimapradius.y, minimapradius.y, 0, camera1->o.z + 1); glScalef(-1, 1, 1); glMatrixMode(GL_MODELVIEW); transplayer(); defaultshader->set(); GLfloat fogc[4] = { minimapcolor.x/255.0f, minimapcolor.y/255.0f, minimapcolor.z/255.0f, 1.0f }; glFogf(GL_FOG_START, 0); glFogf(GL_FOG_END, 1000000); glFogfv(GL_FOG_COLOR, fogc); glClearColor(fogc[0], fogc[1], fogc[2], fogc[3]); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glViewport(0, 0, size, size); glDisable(GL_FOG); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glFrontFace(GL_CCW); xtravertsva = xtraverts = glde = gbatches = 0; visiblecubes(false); queryreflections(); drawreflections(); loopi(minimapheight > 0 && minimapheight < minimapcenter.z + minimapradius.z ? 2 : 1) { if(i) { glClear(GL_DEPTH_BUFFER_BIT); camera1->o.z = minimapheight; transplayer(); } rendergeom(); rendermapmodels(); renderwater(); rendermaterials(); renderalphageom(); } glFrontFace(GL_CW); glDisable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_FOG); glViewport(0, 0, screen->w, screen->h); camera1 = oldcamera; envmapping = minimapping = false; glBindTexture(GL_TEXTURE_2D, minimaptex); glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB5, 0, 0, size, size, 0); setuptexparameters(minimaptex, NULL, 3, 1, GL_RGB5, GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); GLfloat border[4] = { minimapcolor.x/255.0f, minimapcolor.y/255.0f, minimapcolor.z/255.0f, 1.0f }; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border); glBindTexture(GL_TEXTURE_2D, 0); } bool deferdrawtextures = false; void drawtextures() { if(minimized) { deferdrawtextures = true; return; } deferdrawtextures = false; genenvmaps(); drawminimap(); } GLuint motiontex = 0; int motionw = 0, motionh = 0, lastmotion = 0; void cleanupmotionblur() { if(motiontex) { glDeleteTextures(1, &motiontex); motiontex = 0; } motionw = motionh = 0; lastmotion = 0; } VARFP(motionblur, 0, 0, 1, { if(!motionblur) cleanupmotionblur(); }); VARP(motionblurmillis, 1, 5, 1000); FVARP(motionblurscale, 0, 0.5f, 1); void addmotionblur() { if(!motionblur || !hasTR || max(screen->w, screen->h) > hwtexsize) return; if(game::ispaused()) { lastmotion = 0; return; } if(!motiontex || motionw != screen->w || motionh != screen->h) { if(!motiontex) glGenTextures(1, &motiontex); motionw = screen->w; motionh = screen->h; lastmotion = 0; createtexture(motiontex, motionw, motionh, NULL, 3, 0, GL_RGB, GL_TEXTURE_RECTANGLE_ARB); } glBindTexture(GL_TEXTURE_RECTANGLE_ARB, motiontex); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_RECTANGLE_ARB); rectshader->set(); glColor4f(1, 1, 1, lastmotion ? pow(motionblurscale, max(float(lastmillis - lastmotion)/motionblurmillis, 1.0f)) : 0); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f( 0, 0); glVertex2f(-1, -1); glTexCoord2f(motionw, 0); glVertex2f( 1, -1); glTexCoord2f( 0, motionh); glVertex2f(-1, 1); glTexCoord2f(motionw, motionh); glVertex2f( 1, 1); glEnd(); glDisable(GL_TEXTURE_RECTANGLE_ARB); glEnable(GL_TEXTURE_2D); glDisable(GL_BLEND); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); if(lastmillis - lastmotion >= motionblurmillis) { lastmotion = lastmillis - lastmillis%motionblurmillis; glCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, screen->w, screen->h); } } bool dopostfx = false; void invalidatepostfx() { dopostfx = false; } void gl_drawhud(int w, int h); int xtraverts, xtravertsva; void gl_drawframe(int w, int h) { if(deferdrawtextures) drawtextures(); defaultshader->set(); updatedynlights(); aspect = forceaspect ? forceaspect : w/float(h); fovy = 2*atan2(tan(curfov/2*RAD), aspect)/RAD; int fogmat = lookupmaterial(camera1->o)&(MATF_VOLUME|MATF_INDEX), abovemat = MAT_AIR; float fogblend = 1.0f, causticspass = 0.0f; if(isliquid(fogmat&MATF_VOLUME)) { float z = findsurface(fogmat, camera1->o, abovemat) - WATER_OFFSET; if(camera1->o.z < z + 1) fogblend = min(z + 1 - camera1->o.z, 1.0f); else fogmat = abovemat; if(caustics && (fogmat&MATF_VOLUME)==MAT_WATER && camera1->o.z < z) causticspass = renderpath==R_FIXEDFUNCTION ? 1.0f : min(z - camera1->o.z, 1.0f); } else fogmat = MAT_AIR; setfog(fogmat, fogblend, abovemat); if(fogmat!=MAT_AIR) { float blend = abovemat==MAT_AIR ? fogblend : 1.0f; fovy += blend*sinf(lastmillis/1000.0)*2.0f; aspect += blend*sinf(lastmillis/1000.0+PI)*0.1f; } farplane = worldsize*2; project(fovy, aspect, farplane); transplayer(); readmatrices(); findorientation(); setenvmatrix(); glEnable(GL_FOG); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); xtravertsva = xtraverts = glde = gbatches = 0; if(!hasFBO) { if(dopostfx) { drawglaretex(); drawdepthfxtex(); drawreflections(); } else dopostfx = true; } visiblecubes(); if(shadowmap && !hasFBO) rendershadowmap(); glClear(GL_DEPTH_BUFFER_BIT|(wireframe && editmode ? GL_COLOR_BUFFER_BIT : 0)|(hasstencil ? GL_STENCIL_BUFFER_BIT : 0)); if(wireframe && editmode) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); if(limitsky()) drawskybox(farplane, true); rendergeom(causticspass); extern int outline; if(!wireframe && editmode && outline) renderoutline(); queryreflections(); generategrass(); if(!limitsky()) drawskybox(farplane, false); renderdecals(true); rendermapmodels(); rendergame(true); if(!isthirdperson()) { project(curavatarfov, aspect, farplane, false, false, false, avatardepth); game::renderavatar(); project(fovy, aspect, farplane); } if(wireframe && editmode) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if(hasFBO) { drawglaretex(); drawdepthfxtex(); drawreflections(); } if(wireframe && editmode) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); renderwater(); rendergrass(); rendermaterials(); renderalphageom(); if(wireframe && editmode) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); renderparticles(true); glDisable(GL_FOG); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); addmotionblur(); addglare(); if(isliquid(fogmat&MATF_VOLUME)) drawfogoverlay(fogmat, fogblend, abovemat); renderpostfx(); defaultshader->set(); g3d_render(); glDisable(GL_TEXTURE_2D); notextureshader->set(); gl_drawhud(w, h); renderedgame = false; } void gl_drawmainmenu(int w, int h) { xtravertsva = xtraverts = glde = gbatches = 0; renderbackground(NULL, NULL, NULL, NULL, true, true); renderpostfx(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); defaultshader->set(); glEnable(GL_TEXTURE_2D); g3d_render(); notextureshader->set(); glDisable(GL_TEXTURE_2D); gl_drawhud(w, h); } VARNP(damagecompass, usedamagecompass, 0, 1, 1); VARP(damagecompassfade, 1, 1000, 10000); VARP(damagecompasssize, 1, 30, 100); VARP(damagecompassalpha, 1, 25, 100); VARP(damagecompassmin, 1, 25, 1000); VARP(damagecompassmax, 1, 200, 1000); float dcompass[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; void damagecompass(int n, const vec &loc) { if(!usedamagecompass || minimized) return; vec delta(loc); delta.sub(camera1->o); float yaw, pitch; if(delta.magnitude()<4) yaw = camera1->yaw; else vectoyawpitch(delta, yaw, pitch); yaw -= camera1->yaw; if(yaw >= 360) yaw = fmod(yaw, 360); else if(yaw < 0) yaw = 360 - fmod(-yaw, 360); int dir = (int(yaw+22.5f)%360)/45; dcompass[dir] += max(n, damagecompassmin)/float(damagecompassmax); if(dcompass[dir]>1) dcompass[dir] = 1; } void drawdamagecompass(int w, int h) { int dirs = 0; float size = damagecompasssize/100.0f*min(h, w)/2.0f; loopi(8) if(dcompass[i]>0) { if(!dirs) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1, 0, 0, damagecompassalpha/100.0f); } dirs++; glPushMatrix(); glTranslatef(w/2, h/2, 0); glRotatef(i*45, 0, 0, 1); glTranslatef(0, -size/2.0f-min(h, w)/4.0f, 0); float logscale = 32, scale = log(1 + (logscale - 1)*dcompass[i]) / log(logscale); glScalef(size*scale, size*scale, 0); glBegin(GL_TRIANGLES); glVertex3f(1, 1, 0); glVertex3f(-1, 1, 0); glVertex3f(0, 0, 0); glEnd(); glPopMatrix(); // fade in log space so short blips don't disappear too quickly scale -= float(curtime)/damagecompassfade; dcompass[i] = scale > 0 ? (pow(logscale, scale) - 1) / (logscale - 1) : 0; } } int damageblendmillis = 0; VARFP(damagescreen, 0, 1, 1, { if(!damagescreen) damageblendmillis = 0; }); VARP(damagescreenfactor, 1, 7, 100); VARP(damagescreenalpha, 1, 45, 100); VARP(damagescreenfade, 0, 125, 1000); VARP(damagescreenmin, 1, 10, 1000); VARP(damagescreenmax, 1, 100, 1000); void damageblend(int n) { if(!damagescreen || minimized) return; if(lastmillis > damageblendmillis) damageblendmillis = lastmillis; damageblendmillis += clamp(n, damagescreenmin, damagescreenmax)*damagescreenfactor; } void drawdamagescreen(int w, int h) { if(lastmillis >= damageblendmillis) return; defaultshader->set(); glEnable(GL_TEXTURE_2D); static Texture *damagetex = NULL; if(!damagetex) damagetex = textureload("packages/hud/damage.png", 3); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glBindTexture(GL_TEXTURE_2D, damagetex->id); float fade = damagescreenalpha/100.0f; if(damageblendmillis - lastmillis < damagescreenfade) fade *= float(damageblendmillis - lastmillis)/damagescreenfade; glColor4f(fade, fade, fade, fade); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(1, 0); glVertex2f(w, 0); glTexCoord2f(0, 1); glVertex2f(0, h); glTexCoord2f(1, 1); glVertex2f(w, h); glEnd(); glDisable(GL_TEXTURE_2D); notextureshader->set(); } VAR(hidestats, 0, 0, 1); VAR(hidehud, 0, 0, 1); VARP(crosshairsize, 0, 15, 50); VARP(cursorsize, 0, 30, 50); VARP(crosshairfx, 0, 1, 1); VARP(crosshaircolors, 0, 1, 1); #define MAXCROSSHAIRS 4 static Texture *crosshairs[MAXCROSSHAIRS] = { NULL, NULL, NULL, NULL }; void loadcrosshair(const char *name, int i) { if(i < 0 || i >= MAXCROSSHAIRS) return; crosshairs[i] = name ? textureload(name, 3, true) : notexture; if(crosshairs[i] == notexture) { name = game::defaultcrosshair(i); if(!name) name = "data/crosshair.png"; crosshairs[i] = textureload(name, 3, true); } } void loadcrosshair_(const char *name, int *i) { loadcrosshair(name, *i); } COMMANDN(loadcrosshair, loadcrosshair_, "si"); ICOMMAND(getcrosshair, "i", (int *i), { const char *name = ""; if(*i >= 0 && *i < MAXCROSSHAIRS) { name = crosshairs[*i] ? crosshairs[*i]->name : game::defaultcrosshair(*i); if(!name) name = "data/crosshair.png"; } result(name); }); void writecrosshairs(stream *f) { loopi(MAXCROSSHAIRS) if(crosshairs[i] && crosshairs[i]!=notexture) f->printf("loadcrosshair %s %d\n", escapestring(crosshairs[i]->name), i); f->printf("\n"); } void drawcrosshair(int w, int h) { bool windowhit = g3d_windowhit(true, false); if(!windowhit && (hidehud || mainmenu)) return; //(hidehud || player->state==CS_SPECTATOR || player->state==CS_DEAD)) return; float r = 1, g = 1, b = 1, cx = 0.5f, cy = 0.5f, chsize; Texture *crosshair; if(windowhit) { static Texture *cursor = NULL; if(!cursor) cursor = textureload("data/guicursor.png", 3, true); crosshair = cursor; chsize = cursorsize*w/900.0f; g3d_cursorpos(cx, cy); } else { int index = game::selectcrosshair(r, g, b); if(index < 0) return; if(!crosshairfx) index = 0; if(!crosshairfx || !crosshaircolors) r = g = b = 1; crosshair = crosshairs[index]; if(!crosshair) { loadcrosshair(NULL, index); crosshair = crosshairs[index]; } chsize = crosshairsize*w/900.0f; } if(crosshair->type&Texture::ALPHA) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); else glBlendFunc(GL_ONE, GL_ONE); glColor3f(r, g, b); float x = cx*w - (windowhit ? 0 : chsize/2.0f); float y = cy*h - (windowhit ? 0 : chsize/2.0f); glBindTexture(GL_TEXTURE_2D, crosshair->id); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x + chsize, y); glTexCoord2f(0, 1); glVertex2f(x, y + chsize); glTexCoord2f(1, 1); glVertex2f(x + chsize, y + chsize); glEnd(); } VARP(wallclock, 0, 0, 1); VARP(wallclock24, 0, 0, 1); VARP(wallclocksecs, 0, 0, 1); static time_t walltime = 0; VARP(showfps, 0, 1, 1); VARP(showfpsrange, 0, 0, 1); VAR(showeditstats, 0, 0, 1); VAR(statrate, 1, 200, 1000); FVARP(conscale, 1e-3f, 0.33f, 1e3f); void gl_drawhud(int w, int h) { if(forceaspect) w = int(ceil(h*forceaspect)); if(editmode && !hidehud && !mainmenu) { glEnable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); renderblendbrush(); rendereditcursor(); glDepthMask(GL_TRUE); glDisable(GL_DEPTH_TEST); } gettextres(w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor3f(1, 1, 1); extern int debugsm; if(debugsm) { extern void viewshadowmap(); viewshadowmap(); } extern int debugglare; if(debugglare) { extern void viewglaretex(); viewglaretex(); } extern int debugdepthfx; if(debugdepthfx) { extern void viewdepthfxtex(); viewdepthfxtex(); } glEnable(GL_BLEND); if(!mainmenu) { drawdamagescreen(w, h); drawdamagecompass(w, h); } glEnable(GL_TEXTURE_2D); defaultshader->set(); int conw = int(w/conscale), conh = int(h/conscale), abovehud = conh - FONTH, limitgui = abovehud; if(!hidehud && !mainmenu) { if(!hidestats) { glPushMatrix(); glScalef(conscale, conscale, 1); int roffset = 0; if(showfps) { static int lastfps = 0, prevfps[3] = { 0, 0, 0 }, curfps[3] = { 0, 0, 0 }; if(totalmillis - lastfps >= statrate) { memcpy(prevfps, curfps, sizeof(prevfps)); lastfps = totalmillis - (totalmillis%statrate); } int nextfps[3]; getfps(nextfps[0], nextfps[1], nextfps[2]); loopi(3) if(prevfps[i]==curfps[i]) curfps[i] = nextfps[i]; if(showfpsrange) draw_textf("fps %d+%d-%d", conw-7*FONTH, conh-FONTH*3/2, curfps[0], curfps[1], curfps[2]); else draw_textf("fps %d", conw-5*FONTH, conh-FONTH*3/2, curfps[0]); roffset += FONTH; } if(wallclock) { if(!walltime) { walltime = time(NULL); walltime -= totalmillis/1000; if(!walltime) walltime++; } time_t walloffset = walltime + totalmillis/1000; struct tm *localvals = localtime(&walloffset); static string buf; if(localvals && strftime(buf, sizeof(buf), wallclocksecs ? (wallclock24 ? "%H:%M:%S" : "%I:%M:%S%p") : (wallclock24 ? "%H:%M" : "%I:%M%p"), localvals)) { // hack because not all platforms (windows) support %P lowercase option // also strip leading 0 from 12 hour time char *dst = buf; const char *src = &buf[!wallclock24 && buf[0]=='0' ? 1 : 0]; while(*src) *dst++ = tolower(*src++); *dst++ = '\0'; draw_text(buf, conw-5*FONTH, conh-FONTH*3/2-roffset); roffset += FONTH; } } if(editmode || showeditstats) { static int laststats = 0, prevstats[8] = { 0, 0, 0, 0, 0, 0, 0 }, curstats[8] = { 0, 0, 0, 0, 0, 0, 0 }; if(totalmillis - laststats >= statrate) { memcpy(prevstats, curstats, sizeof(prevstats)); laststats = totalmillis - (totalmillis%statrate); } int nextstats[8] = { vtris*100/max(wtris, 1), vverts*100/max(wverts, 1), xtraverts/1024, xtravertsva/1024, glde, gbatches, getnumqueries(), rplanes }; loopi(8) if(prevstats[i]==curstats[i]) curstats[i] = nextstats[i]; abovehud -= 2*FONTH; draw_textf("wtr:%dk(%d%%) wvt:%dk(%d%%) evt:%dk eva:%dk", FONTH/2, abovehud, wtris/1024, curstats[0], wverts/1024, curstats[1], curstats[2], curstats[3]); draw_textf("ond:%d va:%d gl:%d(%d) oq:%d lm:%d rp:%d pvs:%d", FONTH/2, abovehud+FONTH, allocnodes*8, allocva, curstats[4], curstats[5], curstats[6], lightmaps.length(), curstats[7], getnumviewcells()); limitgui = abovehud; } if(editmode) { abovehud -= FONTH; draw_textf("cube %s%d%s", FONTH/2, abovehud, selchildcount<0 ? "1/" : "", abs(selchildcount), showmat && selchildmat > 0 ? getmaterialdesc(selchildmat, ": ") : ""); char *editinfo = executestr("edithud"); if(editinfo) { if(editinfo[0]) { int tw, th; text_bounds(editinfo, tw, th); th += FONTH-1; th -= th%FONTH; abovehud -= max(th, FONTH); draw_text(editinfo, FONTH/2, abovehud); } DELETEA(editinfo); } } else if(identexists("gamehud")) { char *gameinfo = executestr("gamehud"); if(gameinfo) { if(gameinfo[0]) { int tw, th; text_bounds(gameinfo, tw, th); th += FONTH-1; th -= th%FONTH; roffset += max(th, FONTH); draw_text(gameinfo, conw-max(5*FONTH, 2*FONTH+tw), conh-FONTH/2-roffset); } DELETEA(gameinfo); } } glPopMatrix(); } if(hidestats || (!editmode && !showeditstats)) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); game::gameplayhud(w, h); limitgui = abovehud = min(abovehud, int(conh*game::abovegameplayhud(w, h))); } rendertexturepanel(w, h); } g3d_limitscale((2*limitgui - conh) / float(conh)); glPushMatrix(); glScalef(conscale, conscale, 1); abovehud -= rendercommand(FONTH/2, abovehud - FONTH/2, conw-FONTH); extern int fullconsole; if(!hidehud || fullconsole) renderconsole(conw, conh, abovehud - FONTH/2); glPopMatrix(); drawcrosshair(w, h); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); } sauerbraten-0.0.20130203.dfsg/engine/rendersky.cpp0000644000175000017500000004614712063144364021373 0ustar vincentvincent#include "engine.h" Texture *sky[6] = { 0, 0, 0, 0, 0, 0 }, *clouds[6] = { 0, 0, 0, 0, 0, 0 }; void loadsky(const char *basename, Texture *texs[6]) { const char *wildcard = strchr(basename, '*'); loopi(6) { const char *side = cubemapsides[i].name; string name; copystring(name, makerelpath("packages", basename)); if(wildcard) { char *chop = strchr(name, '*'); if(chop) { *chop = '\0'; concatstring(name, side); concatstring(name, wildcard+1); } texs[i] = textureload(name, 3, true, false); } else { defformatstring(ext)("_%s.jpg", side); concatstring(name, ext); if((texs[i] = textureload(name, 3, true, false))==notexture) { strcpy(name+strlen(name)-3, "png"); texs[i] = textureload(name, 3, true, false); } } if(texs[i]==notexture) conoutf(CON_ERROR, "could not load side %s of sky texture %s", side, basename); } } Texture *cloudoverlay = NULL; Texture *loadskyoverlay(const char *basename) { const char *ext = strrchr(basename, '.'); string name; copystring(name, makerelpath("packages", basename)); Texture *t = notexture; if(ext) t = textureload(name, 0, true, false); else { concatstring(name, ".jpg"); if((t = textureload(name, 0, true, false)) == notexture) { strcpy(name+strlen(name)-3, "png"); t = textureload(name, 0, true, false); } } if(t==notexture) conoutf(CON_ERROR, "could not load sky overlay texture %s", basename); return t; } SVARFR(skybox, "", { if(skybox[0]) loadsky(skybox, sky); }); HVARR(skyboxcolour, 0, 0xFFFFFF, 0xFFFFFF); FVARR(spinsky, -720, 0, 720); VARR(yawsky, 0, 0, 360); SVARFR(cloudbox, "", { if(cloudbox[0]) loadsky(cloudbox, clouds); }); HVARR(cloudboxcolour, 0, 0xFFFFFF, 0xFFFFFF); FVARR(cloudboxalpha, 0, 1, 1); FVARR(spinclouds, -720, 0, 720); VARR(yawclouds, 0, 0, 360); FVARR(cloudclip, 0, 0.5f, 1); SVARFR(cloudlayer, "", { if(cloudlayer[0]) cloudoverlay = loadskyoverlay(cloudlayer); }); FVARR(cloudoffsetx, 0, 0, 1); FVARR(cloudoffsety, 0, 0, 1); FVARR(cloudscrollx, -16, 0, 16); FVARR(cloudscrolly, -16, 0, 16); FVARR(cloudscale, 0.001, 1, 64); FVARR(spincloudlayer, -720, 0, 720); VARR(yawcloudlayer, 0, 0, 360); FVARR(cloudheight, -1, 0.2f, 1); FVARR(cloudfade, 0, 0.2f, 1); FVARR(cloudalpha, 0, 1, 1); VARR(cloudsubdiv, 4, 16, 64); HVARR(cloudcolour, 0, 0xFFFFFF, 0xFFFFFF); void draw_envbox_face(float s0, float t0, int x0, int y0, int z0, float s1, float t1, int x1, int y1, int z1, float s2, float t2, int x2, int y2, int z2, float s3, float t3, int x3, int y3, int z3, GLuint texture) { glBindTexture(GL_TEXTURE_2D, texture); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(s3, t3); glVertex3f(x3, y3, z3); glTexCoord2f(s2, t2); glVertex3f(x2, y2, z2); glTexCoord2f(s0, t0); glVertex3f(x0, y0, z0); glTexCoord2f(s1, t1); glVertex3f(x1, y1, z1); glEnd(); xtraverts += 4; } void draw_envbox(int w, float z1clip = 0.0f, float z2clip = 1.0f, int faces = 0x3F, Texture **sky = NULL) { if(z1clip >= z2clip) return; float v1 = 1-z1clip, v2 = 1-z2clip; int z1 = int(ceil(2*w*(z1clip-0.5f))), z2 = int(ceil(2*w*(z2clip-0.5f))); if(faces&0x01) draw_envbox_face(0.0f, v2, -w, -w, z2, 1.0f, v2, -w, w, z2, 1.0f, v1, -w, w, z1, 0.0f, v1, -w, -w, z1, sky[0] ? sky[0]->id : notexture->id); if(faces&0x02) draw_envbox_face(1.0f, v1, w, -w, z1, 0.0f, v1, w, w, z1, 0.0f, v2, w, w, z2, 1.0f, v2, w, -w, z2, sky[1] ? sky[1]->id : notexture->id); if(faces&0x04) draw_envbox_face(1.0f, v1, -w, -w, z1, 0.0f, v1, w, -w, z1, 0.0f, v2, w, -w, z2, 1.0f, v2, -w, -w, z2, sky[2] ? sky[2]->id : notexture->id); if(faces&0x08) draw_envbox_face(1.0f, v1, w, w, z1, 0.0f, v1, -w, w, z1, 0.0f, v2, -w, w, z2, 1.0f, v2, w, w, z2, sky[3] ? sky[3]->id : notexture->id); if(z1clip <= 0 && faces&0x10) draw_envbox_face(0.0f, 1.0f, -w, w, -w, 0.0f, 0.0f, w, w, -w, 1.0f, 0.0f, w, -w, -w, 1.0f, 1.0f, -w, -w, -w, sky[4] ? sky[4]->id : notexture->id); if(z2clip >= 1 && faces&0x20) draw_envbox_face(0.0f, 1.0f, w, w, w, 0.0f, 0.0f, -w, w, w, 1.0f, 0.0f, -w, -w, w, 1.0f, 1.0f, w, -w, w, sky[5] ? sky[5]->id : notexture->id); } void draw_env_overlay(int w, Texture *overlay = NULL, float tx = 0, float ty = 0) { float z = w*cloudheight, tsz = 0.5f*(1-cloudfade)/cloudscale, psz = w*(1-cloudfade); glBindTexture(GL_TEXTURE_2D, overlay ? overlay->id : notexture->id); float r = (cloudcolour>>16)/255.0f, g = ((cloudcolour>>8)&255)/255.0f, b = (cloudcolour&255)/255.0f; glColor4f(r, g, b, cloudalpha); glBegin(GL_TRIANGLE_FAN); loopi(cloudsubdiv+1) { vec p(1, 1, 0); p.rotate_around_z((-2.0f*M_PI*i)/cloudsubdiv); glTexCoord2f(tx + p.x*tsz, ty + p.y*tsz); glVertex3f(p.x*psz, p.y*psz, z); } glEnd(); float tsz2 = 0.5f/cloudscale; glBegin(GL_TRIANGLE_STRIP); loopi(cloudsubdiv+1) { vec p(1, 1, 0); p.rotate_around_z((-2.0f*M_PI*i)/cloudsubdiv); glColor4f(r, g, b, cloudalpha); glTexCoord2f(tx + p.x*tsz, ty + p.y*tsz); glVertex3f(p.x*psz, p.y*psz, z); glColor4f(r, g, b, 0); glTexCoord2f(tx + p.x*tsz2, ty + p.y*tsz2); glVertex3f(p.x*w, p.y*w, z); } glEnd(); } static struct domevert { vec pos; uchar color[4]; domevert() {} domevert(const vec &pos, const bvec &fcolor, float alpha) : pos(pos) { memcpy(color, fcolor.v, 3); color[3] = uchar(alpha*255); } domevert(const domevert &v0, const domevert &v1) : pos(vec(v0.pos).add(v1.pos).normalize()) { memcpy(color, v0.color, 4); if(v0.pos.z != v1.pos.z) color[3] += uchar((v1.color[3] - v0.color[3]) * (pos.z - v0.pos.z) / (v1.pos.z - v0.pos.z)); } } *domeverts = NULL; static GLushort *domeindices = NULL; static int domenumverts = 0, domenumindices = 0, domecapindices = 0; static GLuint domevbuf = 0, domeebuf = 0; static bvec domecolor(0, 0, 0); static float domeminalpha = 0, domemaxalpha = 0, domecapsize = -1, domeclipz = 1; static void subdivide(int depth, int face); static void genface(int depth, int i1, int i2, int i3) { int face = domenumindices; domenumindices += 3; domeindices[face] = i3; domeindices[face+1] = i2; domeindices[face+2] = i1; subdivide(depth, face); } static void subdivide(int depth, int face) { if(depth-- <= 0) return; int idx[6]; loopi(3) idx[i] = domeindices[face+2-i]; loopi(3) { int vert = domenumverts++; domeverts[vert] = domevert(domeverts[idx[i]], domeverts[idx[(i+1)%3]]); //push on to unit sphere idx[3+i] = vert; domeindices[face+2-i] = vert; } subdivide(depth, face); loopi(3) genface(depth, idx[i], idx[3+i], idx[3+(i+2)%3]); } static int sortdomecap(GLushort x, GLushort y) { const vec &xv = domeverts[x].pos, &yv = domeverts[y].pos; return xv.y < 0 ? yv.y >= 0 || xv.x < yv.x : yv.y >= 0 && xv.x > yv.x; } static void initdome(const bvec &color, float minalpha = 0.0f, float maxalpha = 1.0f, float capsize = -1, float clipz = 1, int hres = 16, int depth = 2) { const int tris = hres << (2*depth); domenumverts = domenumindices = domecapindices = 0; DELETEA(domeverts); DELETEA(domeindices); domeverts = new domevert[tris+1 + (capsize >= 0 ? 1 : 0)]; domeindices = new GLushort[(tris + (capsize >= 0 ? hres<= 1) { domeverts[domenumverts++] = domevert(vec(0.0f, 0.0f, 1.0f), color, minalpha); //build initial 'hres' sided pyramid loopi(hres) domeverts[domenumverts++] = domevert(vec(sincos360[(360*i)/hres], 0.0f), color, maxalpha); loopi(hres) genface(depth, 0, i+1, 1+(i+1)%hres); } else if(clipz <= 0) { loopi(hres<= 0) { GLushort *domecap = &domeindices[domenumindices]; int domecapverts = 0; loopi(domenumverts) if(!domeverts[i].pos.z) domecap[domecapverts++] = i; domeverts[domenumverts++] = domevert(vec(0.0f, 0.0f, -capsize), color, maxalpha); quicksort(domecap, domecapverts, sortdomecap); loopi(domecapverts) { int n = domecapverts-1-i; domecap[n*3] = domecap[n]; domecap[n*3+1] = domecap[(n+1)%domecapverts]; domecap[n*3+2] = domenumverts-1; domecapindices += 3; } } if(hasVBO) { if(!domevbuf) glGenBuffers_(1, &domevbuf); glBindBuffer_(GL_ARRAY_BUFFER_ARB, domevbuf); glBufferData_(GL_ARRAY_BUFFER_ARB, domenumverts*sizeof(domevert), domeverts, GL_STATIC_DRAW_ARB); DELETEA(domeverts); if(!domeebuf) glGenBuffers_(1, &domeebuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, domeebuf); glBufferData_(GL_ELEMENT_ARRAY_BUFFER_ARB, (domenumindices + domecapindices)*sizeof(GLushort), domeindices, GL_STATIC_DRAW_ARB); DELETEA(domeindices); } } static void deletedome() { domenumverts = domenumindices = 0; if(domevbuf) { glDeleteBuffers_(1, &domevbuf); domevbuf = 0; } if(domeebuf) { glDeleteBuffers_(1, &domeebuf); domeebuf = 0; } DELETEA(domeverts); DELETEA(domeindices); } FVARR(fogdomeheight, -1, -0.5f, 1); FVARR(fogdomemin, 0, 0, 1); FVARR(fogdomemax, 0, 0, 1); VARR(fogdomecap, 0, 1, 1); FVARR(fogdomeclip, 0, 1, 1); bvec fogdomecolor(0, 0, 0); HVARFR(fogdomecolour, 0, 0, 0xFFFFFF, { fogdomecolor = bvec((fogdomecolour>>16)&0xFF, (fogdomecolour>>8)&0xFF, fogdomecolour&0xFF); }); static void drawdome() { float capsize = fogdomecap && fogdomeheight < 1 ? (1 + fogdomeheight) / (1 - fogdomeheight) : -1; bvec color = fogdomecolour ? fogdomecolor : fogcolor; if(!domenumverts || domecolor != color || domeminalpha != fogdomemin || domemaxalpha != fogdomemax || domecapsize != capsize || domeclipz != fogdomeclip) { initdome(color, min(fogdomemin, fogdomemax), fogdomemax, capsize, fogdomeclip); domecolor = color; domeminalpha = fogdomemin; domemaxalpha = fogdomemax; domecapsize = capsize; domeclipz = fogdomeclip; } if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, domevbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, domeebuf); } glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(domevert), &domeverts->pos); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(domevert), &domeverts->color); if(hasDRE) glDrawRangeElements_(GL_TRIANGLES, 0, domenumverts-1, domenumindices + fogdomecap*domecapindices, GL_UNSIGNED_SHORT, domeindices); else glDrawElements(GL_TRIANGLES, domenumindices + fogdomecap*domecapindices, GL_UNSIGNED_SHORT, domeindices); xtraverts += domenumverts; glde++; glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } } void cleanupsky() { deletedome(); } VARP(sparklyfix, 0, 0, 1); VAR(showsky, 0, 1, 1); VAR(clipsky, 0, 1, 1); bool drawskylimits(bool explicitonly) { nocolorshader->set(); glDisable(GL_TEXTURE_2D); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); bool rendered = rendersky(explicitonly); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glEnable(GL_TEXTURE_2D); return rendered; } void drawskyoutline() { lineshader->set(); glDisable(GL_TEXTURE_2D); glDepthMask(GL_FALSE); extern int wireframe; if(!wireframe) { enablepolygonoffset(GL_POLYGON_OFFSET_LINE); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } glColor3f(0.5f, 0.0f, 0.5f); rendersky(true); if(!wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); disablepolygonoffset(GL_POLYGON_OFFSET_LINE); } glDepthMask(GL_TRUE); glEnable(GL_TEXTURE_2D); if(!glaring) defaultshader->set(); } VAR(clampsky, 0, 1, 1); VARR(fogdomeclouds, 0, 1, 1); static void drawfogdome(int farplane) { notextureshader->set(); glDisable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); glLoadMatrixf(viewmatrix.v); glRotatef(camera1->roll, 0, 1, 0); glRotatef(camera1->pitch, -1, 0, 0); glRotatef(camera1->yaw, 0, 0, -1); if(reflecting) glScalef(1, 1, -1); glTranslatef(0, 0, farplane*fogdomeheight*0.5f); glScalef(farplane/2, farplane/2, farplane*(0.5f - fogdomeheight*0.5f)); drawdome(); glPopMatrix(); glDisable(GL_BLEND); glEnable(GL_TEXTURE_2D); } static int yawskyfaces(int faces, int yaw, float spin = 0) { if(spin || yaw%90) return faces&0x0F ? faces | 0x0F : faces; static const int faceidxs[3][4] = { { 3, 2, 0, 1 }, { 1, 0, 3, 2 }, { 2, 3, 1, 0 } }; yaw /= 90; if(yaw < 1 || yaw > 3) return faces; const int *idxs = faceidxs[yaw - 1]; return (faces & ~0x0F) | (((faces>>idxs[0])&1)<<0) | (((faces>>idxs[1])&1)<<1) | (((faces>>idxs[2])&1)<<2) | (((faces>>idxs[3])&1)<<3); } void drawskybox(int farplane, bool limited) { extern int renderedskyfaces, renderedskyclip; // , renderedsky, renderedexplicitsky; bool alwaysrender = editmode || !insideworld(camera1->o) || reflecting, explicitonly = false; if(limited) { explicitonly = alwaysrender || !sparklyfix || refracting; if(!drawskylimits(explicitonly) && !alwaysrender) return; extern int ati_skybox_bug; if(!alwaysrender && !renderedskyfaces && !ati_skybox_bug) explicitonly = false; } else if(!alwaysrender) { extern vtxarray *visibleva; renderedskyfaces = 0; renderedskyclip = INT_MAX; for(vtxarray *va = visibleva; va; va = va->next) { if(va->occluded >= OCCLUDE_BB && va->skyfaces&0x80) continue; renderedskyfaces |= va->skyfaces&0x3F; if(!(va->skyfaces&0x1F) || camera1->o.z < va->skyclip) renderedskyclip = min(renderedskyclip, va->skyclip); else renderedskyclip = 0; } if(!renderedskyfaces) return; } if(alwaysrender) { renderedskyfaces = 0x3F; renderedskyclip = 0; } float skyclip = clipsky ? max(renderedskyclip-1, 0) : 0, topclip = 1; if(reflectzo.z)/float(worldsize); else if(reflectz>skyclip) skyclip = reflectz; } if(skyclip) skyclip = 0.5f + 0.5f*(skyclip-camera1->o.z)/float(worldsize); if(glaring) SETSHADER(skyboxglare); else defaultshader->set(); glDisable(GL_FOG); if(limited) { if(explicitonly) glDisable(GL_DEPTH_TEST); else glDepthFunc(GL_GEQUAL); } else glDepthFunc(GL_LEQUAL); glDepthMask(GL_FALSE); if(clampsky) glDepthRange(1, 1); glColor3f((skyboxcolour>>16)/255.0f, ((skyboxcolour>>8)&255)/255.0f, (skyboxcolour&255)/255.0f); glPushMatrix(); glLoadMatrixf(viewmatrix.v); glRotatef(camera1->roll, 0, 1, 0); glRotatef(camera1->pitch, -1, 0, 0); glRotatef(camera1->yaw+spinsky*lastmillis/1000.0f+yawsky, 0, 0, -1); if(reflecting) glScalef(1, 1, -1); draw_envbox(farplane/2, skyclip, topclip, yawskyfaces(renderedskyfaces, yawsky, spinsky), sky); glPopMatrix(); if(!glaring && fogdomemax && !fogdomeclouds) { if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); drawfogdome(farplane); defaultshader->set(); } if(!glaring && cloudbox[0]) { if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f((cloudboxcolour>>16)/255.0f, ((cloudboxcolour>>8)&255)/255.0f, (cloudboxcolour&255)/255.0f, cloudboxalpha); glPushMatrix(); glLoadMatrixf(viewmatrix.v); glRotatef(camera1->roll, 0, 1, 0); glRotatef(camera1->pitch, -1, 0, 0); glRotatef(camera1->yaw+spinclouds*lastmillis/1000.0f+yawclouds, 0, 0, -1); if(reflecting) glScalef(1, 1, -1); draw_envbox(farplane/2, skyclip ? skyclip : cloudclip, topclip, yawskyfaces(renderedskyfaces, yawclouds, spinclouds), clouds); glPopMatrix(); glDisable(GL_BLEND); } if(!glaring && cloudlayer[0] && cloudheight && renderedskyfaces&(cloudheight < 0 ? 0x1F : 0x2F)) { if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); glLoadMatrixf(viewmatrix.v); glRotatef(camera1->roll, 0, 1, 0); glRotatef(camera1->pitch, -1, 0, 0); glRotatef(camera1->yaw+spincloudlayer*lastmillis/1000.0f+yawcloudlayer, 0, 0, -1); if(reflecting) glScalef(1, 1, -1); draw_env_overlay(farplane/2, cloudoverlay, cloudoffsetx + cloudscrollx * lastmillis/1000.0f, cloudoffsety + cloudscrolly * lastmillis/1000.0f); glPopMatrix(); glDisable(GL_BLEND); glEnable(GL_CULL_FACE); } if(!glaring && fogdomemax && fogdomeclouds) { if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); drawfogdome(farplane); } if(clampsky) glDepthRange(0, 1); glDepthMask(GL_TRUE); if(limited) { if(explicitonly) glEnable(GL_DEPTH_TEST); else glDepthFunc(GL_LESS); if(!reflecting && !refracting && !envmapping && editmode && showsky) drawskyoutline(); } else glDepthFunc(GL_LESS); glEnable(GL_FOG); } VARNR(skytexture, useskytexture, 0, 1, 1); int explicitsky = 0; double skyarea = 0; bool limitsky() { return (explicitsky && (useskytexture || editmode)) || (sparklyfix && skyarea / (double(worldsize)*double(worldsize)*6) < 0.9); } sauerbraten-0.0.20130203.dfsg/engine/main.cpp0000644000175000017500000011607312072672414020307 0ustar vincentvincent// main.cpp: initialisation & main loop #include "engine.h" extern void cleargamma(); void cleanup() { recorder::stop(); cleanupserver(); SDL_ShowCursor(1); SDL_WM_GrabInput(SDL_GRAB_OFF); cleargamma(); freeocta(worldroot); extern void clear_command(); clear_command(); extern void clear_console(); clear_console(); extern void clear_mdls(); clear_mdls(); extern void clear_sound(); clear_sound(); closelogfile(); SDL_Quit(); } void quit() // normal exit { extern void writeinitcfg(); writeinitcfg(); writeservercfg(); abortconnect(); disconnect(); localdisconnect(); writecfg(); cleanup(); exit(EXIT_SUCCESS); } void fatal(const char *s, ...) // failure exit { static int errors = 0; errors++; if(errors <= 2) // print up to one extra recursive error { defvformatstring(msg,s,s); logoutf("%s", msg); if(errors <= 1) // avoid recursion { if(SDL_WasInit(SDL_INIT_VIDEO)) { SDL_ShowCursor(1); SDL_WM_GrabInput(SDL_GRAB_OFF); cleargamma(); } #ifdef WIN32 MessageBox(NULL, msg, "Cube 2: Sauerbraten fatal error", MB_OK|MB_SYSTEMMODAL); #endif SDL_Quit(); } } exit(EXIT_FAILURE); } SDL_Surface *screen = NULL; int curtime = 0, totalmillis = 1, lastmillis = 1; dynent *player = NULL; int initing = NOT_INITING; bool initwarning(const char *desc, int level, int type) { if(initing < level) { addchange(desc, type); return true; } return false; } #define SCR_MINW 320 #define SCR_MINH 200 #define SCR_MAXW 10000 #define SCR_MAXH 10000 #define SCR_DEFAULTW 1024 #define SCR_DEFAULTH 768 VARF(scr_w, SCR_MINW, -1, SCR_MAXW, initwarning("screen resolution")); VARF(scr_h, SCR_MINH, -1, SCR_MAXH, initwarning("screen resolution")); VARF(colorbits, 0, 0, 32, initwarning("color depth")); VARF(depthbits, 0, 0, 32, initwarning("depth-buffer precision")); VARF(stencilbits, 0, 0, 32, initwarning("stencil-buffer precision")); VARF(fsaa, -1, -1, 16, initwarning("anti-aliasing")); VARF(vsync, -1, -1, 1, initwarning("vertical sync")); void writeinitcfg() { stream *f = openutf8file("init.cfg", "w"); if(!f) return; f->printf("// automatically written on exit, DO NOT MODIFY\n// modify settings in game\n"); extern int fullscreen; f->printf("fullscreen %d\n", fullscreen); f->printf("scr_w %d\n", scr_w); f->printf("scr_h %d\n", scr_h); f->printf("colorbits %d\n", colorbits); f->printf("depthbits %d\n", depthbits); f->printf("stencilbits %d\n", stencilbits); f->printf("fsaa %d\n", fsaa); f->printf("vsync %d\n", vsync); extern int useshaders, shaderprecision, forceglsl; f->printf("shaders %d\n", useshaders); f->printf("shaderprecision %d\n", shaderprecision); f->printf("forceglsl %d\n", forceglsl); extern int soundchans, soundfreq, soundbufferlen; f->printf("soundchans %d\n", soundchans); f->printf("soundfreq %d\n", soundfreq); f->printf("soundbufferlen %d\n", soundbufferlen); delete f; } COMMAND(quit, ""); static void getbackgroundres(int &w, int &h) { float wk = 1, hk = 1; if(w < 1024) wk = 1024.0f/w; if(h < 768) hk = 768.0f/h; wk = hk = max(wk, hk); w = int(ceil(w*wk)); h = int(ceil(h*hk)); } string backgroundcaption = ""; Texture *backgroundmapshot = NULL; string backgroundmapname = ""; char *backgroundmapinfo = NULL; void restorebackground() { if(renderedframe) return; renderbackground(backgroundcaption[0] ? backgroundcaption : NULL, backgroundmapshot, backgroundmapname[0] ? backgroundmapname : NULL, backgroundmapinfo, true); } void renderbackground(const char *caption, Texture *mapshot, const char *mapname, const char *mapinfo, bool restore, bool force) { if(!inbetweenframes && !force) return; stopsounds(); // stop sounds while loading int w = screen->w, h = screen->h; if(forceaspect) w = int(ceil(h*forceaspect)); getbackgroundres(w, h); gettextres(w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); defaultshader->set(); glEnable(GL_TEXTURE_2D); static int lastupdate = -1, lastw = -1, lasth = -1; static float backgroundu = 0, backgroundv = 0, detailu = 0, detailv = 0; static int numdecals = 0; static struct decal { float x, y, size; int side; } decals[12]; if((renderedframe && !mainmenu && lastupdate != lastmillis) || lastw != w || lasth != h) { lastupdate = lastmillis; lastw = w; lasth = h; backgroundu = rndscale(1); backgroundv = rndscale(1); detailu = rndscale(1); detailv = rndscale(1); numdecals = sizeof(decals)/sizeof(decals[0]); numdecals = numdecals/3 + rnd((numdecals*2)/3 + 1); float maxsize = min(w, h)/16.0f; loopi(numdecals) { decal d = { rndscale(w), rndscale(h), maxsize/2 + rndscale(maxsize/2), rnd(2) }; decals[i] = d; } } else if(lastupdate != lastmillis) lastupdate = lastmillis; loopi(restore ? 1 : 3) { glColor3f(1, 1, 1); settexture("data/background.png", 0); float bu = w*0.67f/256.0f + backgroundu, bv = h*0.67f/256.0f + backgroundv; glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(bu, 0); glVertex2f(w, 0); glTexCoord2f(0, bv); glVertex2f(0, h); glTexCoord2f(bu, bv); glVertex2f(w, h); glEnd(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); settexture("data/background_detail.png", 0); float du = w*0.8f/512.0f + detailu, dv = h*0.8f/512.0f + detailv; glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(du, 0); glVertex2f(w, 0); glTexCoord2f(0, dv); glVertex2f(0, h); glTexCoord2f(du, dv); glVertex2f(w, h); glEnd(); settexture("data/background_decal.png", 3); glBegin(GL_QUADS); loopj(numdecals) { float hsz = decals[j].size, hx = clamp(decals[j].x, hsz, w-hsz), hy = clamp(decals[j].y, hsz, h-hsz), side = decals[j].side; glTexCoord2f(side, 0); glVertex2f(hx-hsz, hy-hsz); glTexCoord2f(1-side, 0); glVertex2f(hx+hsz, hy-hsz); glTexCoord2f(1-side, 1); glVertex2f(hx+hsz, hy+hsz); glTexCoord2f(side, 1); glVertex2f(hx-hsz, hy+hsz); } glEnd(); float lh = 0.5f*min(w, h), lw = lh*2, lx = 0.5f*(w - lw), ly = 0.5f*(h*0.5f - lh); settexture((maxtexsize ? min(maxtexsize, hwtexsize) : hwtexsize) >= 1024 && (screen->w > 1280 || screen->h > 800) ? "data/logo_1024.png" : "data/logo.png", 3); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(lx, ly); glTexCoord2f(1, 0); glVertex2f(lx+lw, ly); glTexCoord2f(0, 1); glVertex2f(lx, ly+lh); glTexCoord2f(1, 1); glVertex2f(lx+lw, ly+lh); glEnd(); if(caption) { int tw = text_width(caption); float tsz = 0.04f*min(w, h)/FONTH, tx = 0.5f*(w - tw*tsz), ty = h - 0.075f*1.5f*min(w, h) - 1.25f*FONTH*tsz; glPushMatrix(); glTranslatef(tx, ty, 0); glScalef(tsz, tsz, 1); draw_text(caption, 0, 0); glPopMatrix(); } if(mapshot || mapname) { int infowidth = 12*FONTH; float sz = 0.35f*min(w, h), msz = (0.75f*min(w, h) - sz)/(infowidth + FONTH), x = 0.5f*(w-sz), y = ly+lh - sz/15; if(mapinfo) { int mw, mh; text_bounds(mapinfo, mw, mh, infowidth); x -= 0.5f*(mw*msz + FONTH*msz); } if(mapshot && mapshot!=notexture) { glBindTexture(GL_TEXTURE_2D, mapshot->id); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x+sz, y); glTexCoord2f(0, 1); glVertex2f(x, y+sz); glTexCoord2f(1, 1); glVertex2f(x+sz, y+sz); glEnd(); } else { int qw, qh; text_bounds("?", qw, qh); float qsz = sz*0.5f/max(qw, qh); glPushMatrix(); glTranslatef(x + 0.5f*(sz - qw*qsz), y + 0.5f*(sz - qh*qsz), 0); glScalef(qsz, qsz, 1); draw_text("?", 0, 0); glPopMatrix(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } settexture("data/mapshot_frame.png", 3); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x+sz, y); glTexCoord2f(0, 1); glVertex2f(x, y+sz); glTexCoord2f(1, 1); glVertex2f(x+sz, y+sz); glEnd(); if(mapname) { int tw = text_width(mapname); float tsz = sz/(8*FONTH), tx = 0.9f*sz - tw*tsz, ty = 0.9f*sz - FONTH*tsz; if(tx < 0.1f*sz) { tsz = 0.1f*sz/tw; tx = 0.1f; } glPushMatrix(); glTranslatef(x+tx, y+ty, 0); glScalef(tsz, tsz, 1); draw_text(mapname, 0, 0); glPopMatrix(); } if(mapinfo) { glPushMatrix(); glTranslatef(x+sz+FONTH*msz, y, 0); glScalef(msz, msz, 1); draw_text(mapinfo, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, -1, infowidth); glPopMatrix(); } } glDisable(GL_BLEND); if(!restore) swapbuffers(); } glDisable(GL_TEXTURE_2D); if(!restore) { renderedframe = false; copystring(backgroundcaption, caption ? caption : ""); backgroundmapshot = mapshot; copystring(backgroundmapname, mapname ? mapname : ""); if(mapinfo != backgroundmapinfo) { DELETEA(backgroundmapinfo); if(mapinfo) backgroundmapinfo = newstring(mapinfo); } } } float loadprogress = 0; void renderprogress(float bar, const char *text, GLuint tex, bool background) // also used during loading { if(!inbetweenframes || envmapping) return; clientkeepalive(); // make sure our connection doesn't time out while loading maps etc. #ifdef __APPLE__ interceptkey(SDLK_UNKNOWN); // keep the event queue awake to avoid 'beachball' cursor #endif extern int sdl_backingstore_bug; if(background || sdl_backingstore_bug > 0) restorebackground(); int w = screen->w, h = screen->h; if(forceaspect) w = int(ceil(h*forceaspect)); getbackgroundres(w, h); gettextres(w, h); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glEnable(GL_TEXTURE_2D); defaultshader->set(); glColor3f(1, 1, 1); float fh = 0.075f*min(w, h), fw = fh*10, fx = renderedframe ? w - fw - fh/4 : 0.5f*(w - fw), fy = renderedframe ? fh/4 : h - fh*1.5f, fu1 = 0/512.0f, fu2 = 511/512.0f, fv1 = 0/64.0f, fv2 = 52/64.0f; settexture("data/loading_frame.png", 3); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(fu1, fv1); glVertex2f(fx, fy); glTexCoord2f(fu2, fv1); glVertex2f(fx+fw, fy); glTexCoord2f(fu1, fv2); glVertex2f(fx, fy+fh); glTexCoord2f(fu2, fv2); glVertex2f(fx+fw, fy+fh); glEnd(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); float bw = fw*(511 - 2*17)/511.0f, bh = fh*20/52.0f, bx = fx + fw*17/511.0f, by = fy + fh*16/52.0f, bv1 = 0/32.0f, bv2 = 20/32.0f, su1 = 0/32.0f, su2 = 7/32.0f, sw = fw*7/511.0f, eu1 = 23/32.0f, eu2 = 30/32.0f, ew = fw*7/511.0f, mw = bw - sw - ew, ex = bx+sw + max(mw*bar, fw*7/511.0f); if(bar > 0) { settexture("data/loading_bar.png", 3); glBegin(GL_QUADS); glTexCoord2f(su1, bv1); glVertex2f(bx, by); glTexCoord2f(su2, bv1); glVertex2f(bx+sw, by); glTexCoord2f(su2, bv2); glVertex2f(bx+sw, by+bh); glTexCoord2f(su1, bv2); glVertex2f(bx, by+bh); glTexCoord2f(su2, bv1); glVertex2f(bx+sw, by); glTexCoord2f(eu1, bv1); glVertex2f(ex, by); glTexCoord2f(eu1, bv2); glVertex2f(ex, by+bh); glTexCoord2f(su2, bv2); glVertex2f(bx+sw, by+bh); glTexCoord2f(eu1, bv1); glVertex2f(ex, by); glTexCoord2f(eu2, bv1); glVertex2f(ex+ew, by); glTexCoord2f(eu2, bv2); glVertex2f(ex+ew, by+bh); glTexCoord2f(eu1, bv2); glVertex2f(ex, by+bh); glEnd(); } if(text) { int tw = text_width(text); float tsz = bh*0.8f/FONTH; if(tw*tsz > mw) tsz = mw/tw; glPushMatrix(); glTranslatef(bx+sw, by + (bh - FONTH*tsz)/2, 0); glScalef(tsz, tsz, 1); draw_text(text, 0, 0); glPopMatrix(); } glDisable(GL_BLEND); if(tex) { glBindTexture(GL_TEXTURE_2D, tex); float sz = 0.35f*min(w, h), x = 0.5f*(w-sz), y = 0.5f*min(w, h) - sz/15; glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x+sz, y); glTexCoord2f(0, 1); glVertex2f(x, y+sz); glTexCoord2f(1, 1); glVertex2f(x+sz, y+sz); glEnd(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); settexture("data/mapshot_frame.png", 3); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x+sz, y); glTexCoord2f(0, 1); glVertex2f(x, y+sz); glTexCoord2f(1, 1); glVertex2f(x+sz, y+sz); glEnd(); glDisable(GL_BLEND); } glDisable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); swapbuffers(); } void keyrepeat(bool on) { SDL_EnableKeyRepeat(on ? SDL_DEFAULT_REPEAT_DELAY : 0, SDL_DEFAULT_REPEAT_INTERVAL); } bool grabinput = false, minimized = false; void inputgrab(bool on) { #ifndef WIN32 if(!(screen->flags & SDL_FULLSCREEN)) SDL_WM_GrabInput(SDL_GRAB_OFF); else #endif SDL_WM_GrabInput(on ? SDL_GRAB_ON : SDL_GRAB_OFF); SDL_ShowCursor(on ? SDL_DISABLE : SDL_ENABLE); } void setfullscreen(bool enable) { if(!screen) return; #if defined(WIN32) || defined(__APPLE__) initwarning(enable ? "fullscreen" : "windowed"); #else if(enable == !(screen->flags&SDL_FULLSCREEN)) { SDL_WM_ToggleFullScreen(screen); inputgrab(grabinput); } #endif } #ifdef _DEBUG VARF(fullscreen, 0, 0, 1, setfullscreen(fullscreen!=0)); #else VARF(fullscreen, 0, 1, 1, setfullscreen(fullscreen!=0)); #endif void screenres(int *w, int *h) { #if !defined(WIN32) && !defined(__APPLE__) if(initing >= INIT_RESET) { #endif scr_w = clamp(*w, SCR_MINW, SCR_MAXW); scr_h = clamp(*h, SCR_MINH, SCR_MAXH); #if defined(WIN32) || defined(__APPLE__) initwarning("screen resolution"); #else return; } SDL_Surface *surf = SDL_SetVideoMode(clamp(*w, SCR_MINW, SCR_MAXW), clamp(*h, SCR_MINH, SCR_MAXH), 0, SDL_OPENGL|(screen->flags&SDL_FULLSCREEN ? SDL_FULLSCREEN : SDL_RESIZABLE)); if(!surf) return; screen = surf; scr_w = screen->w; scr_h = screen->h; glViewport(0, 0, scr_w, scr_h); #endif } COMMAND(screenres, "ii"); static int curgamma = 100; VARFP(gamma, 30, 100, 300, { if(gamma == curgamma) return; curgamma = gamma; float f = gamma/100.0f; if(SDL_SetGamma(f,f,f)==-1) conoutf(CON_ERROR, "Could not set gamma: %s", SDL_GetError()); }); void restoregamma() { if(curgamma == 100) return; float f = curgamma/100.0f; SDL_SetGamma(1, 1, 1); SDL_SetGamma(f, f, f); } void cleargamma() { if(curgamma != 100) SDL_SetGamma(1, 1, 1); } VAR(dbgmodes, 0, 0, 1); int desktopw = 0, desktoph = 0; void setupscreen(int &usedcolorbits, int &useddepthbits, int &usedfsaa) { int flags = SDL_RESIZABLE; #if defined(WIN32) || defined(__APPLE__) flags = 0; #endif if(fullscreen) flags = SDL_FULLSCREEN; SDL_Rect **modes = SDL_ListModes(NULL, SDL_OPENGL|flags); if(modes && modes!=(SDL_Rect **)-1) { int widest = -1, best = -1; for(int i = 0; modes[i]; i++) { if(dbgmodes) conoutf(CON_DEBUG, "mode[%d]: %d x %d", i, modes[i]->w, modes[i]->h); if(widest < 0 || modes[i]->w > modes[widest]->w || (modes[i]->w == modes[widest]->w && modes[i]->h > modes[widest]->h)) widest = i; } if(scr_w < 0 || scr_h < 0) { int w = scr_w, h = scr_h, ratiow = desktopw, ratioh = desktoph; if(w < 0 && h < 0) { w = SCR_DEFAULTW; h = SCR_DEFAULTH; } if(ratiow <= 0 || ratioh <= 0) { ratiow = modes[widest]->w; ratioh = modes[widest]->h; } for(int i = 0; modes[i]; i++) if(modes[i]->w*ratioh == modes[i]->h*ratiow) { if(w <= modes[i]->w && h <= modes[i]->h && (best < 0 || modes[i]->w < modes[best]->w)) best = i; } } if(best < 0) { int w = scr_w, h = scr_h; if(w < 0 && h < 0) { w = SCR_DEFAULTW; h = SCR_DEFAULTH; } else if(w < 0) w = (h*SCR_DEFAULTW)/SCR_DEFAULTH; else if(h < 0) h = (w*SCR_DEFAULTH)/SCR_DEFAULTW; for(int i = 0; modes[i]; i++) { if(w <= modes[i]->w && h <= modes[i]->h && (best < 0 || modes[i]->w < modes[best]->w || (modes[i]->w == modes[best]->w && modes[i]->h < modes[best]->h))) best = i; } } if(flags&SDL_FULLSCREEN) { if(best >= 0) { scr_w = modes[best]->w; scr_h = modes[best]->h; } else if(desktopw > 0 && desktoph > 0) { scr_w = desktopw; scr_h = desktoph; } else if(widest >= 0) { scr_w = modes[widest]->w; scr_h = modes[widest]->h; } } else if(best < 0) { scr_w = min(scr_w >= 0 ? scr_w : (scr_h >= 0 ? (scr_h*SCR_DEFAULTW)/SCR_DEFAULTH : SCR_DEFAULTW), (int)modes[widest]->w); scr_h = min(scr_h >= 0 ? scr_h : (scr_w >= 0 ? (scr_w*SCR_DEFAULTH)/SCR_DEFAULTW : SCR_DEFAULTH), (int)modes[widest]->h); } if(dbgmodes) conoutf(CON_DEBUG, "selected %d x %d", scr_w, scr_h); } if(scr_w < 0 && scr_h < 0) { scr_w = SCR_DEFAULTW; scr_h = SCR_DEFAULTH; } else if(scr_w < 0) scr_w = (scr_h*SCR_DEFAULTW)/SCR_DEFAULTH; else if(scr_h < 0) scr_h = (scr_w*SCR_DEFAULTH)/SCR_DEFAULTW; bool hasbpp = true; if(colorbits) hasbpp = SDL_VideoModeOK(scr_w, scr_h, colorbits, SDL_OPENGL|flags)==colorbits; SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); #if SDL_VERSION_ATLEAST(1, 2, 11) if(vsync>=0) SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, vsync); #endif static int configs[] = { 0x7, /* try everything */ 0x6, 0x5, 0x3, /* try disabling one at a time */ 0x4, 0x2, 0x1, /* try disabling two at a time */ 0 /* try disabling everything */ }; int config = 0; SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0); if(!depthbits) SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); if(!fsaa) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); } loopi(sizeof(configs)/sizeof(configs[0])) { config = configs[i]; if(!depthbits && config&1) continue; if(!stencilbits && config&2) continue; if(fsaa<=0 && config&4) continue; if(depthbits) SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, config&1 ? depthbits : 16); if(stencilbits) { hasstencil = config&2 ? stencilbits : 0; SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, hasstencil); } else hasstencil = 0; if(fsaa>0) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, config&4 ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, config&4 ? fsaa : 0); } screen = SDL_SetVideoMode(scr_w, scr_h, hasbpp ? colorbits : 0, SDL_OPENGL|flags); if(screen) break; } if(!screen) fatal("Unable to create OpenGL screen: %s", SDL_GetError()); else { if(!hasbpp) conoutf(CON_WARN, "%d bit color buffer not supported - disabling", colorbits); if(depthbits && (config&1)==0) conoutf(CON_WARN, "%d bit z-buffer not supported - disabling", depthbits); if(stencilbits && (config&2)==0) conoutf(CON_WARN, "Stencil buffer not supported - disabling"); if(fsaa>0 && (config&4)==0) conoutf(CON_WARN, "%dx anti-aliasing not supported - disabling", fsaa); } scr_w = screen->w; scr_h = screen->h; usedcolorbits = hasbpp ? colorbits : 0; useddepthbits = config&1 ? depthbits : 0; usedfsaa = config&4 ? fsaa : 0; } void resetgl() { clearchanges(CHANGE_GFX); renderbackground("resetting OpenGL"); extern void cleanupva(); extern void cleanupparticles(); extern void cleanupsky(); extern void cleanupmodels(); extern void cleanuptextures(); extern void cleanuplightmaps(); extern void cleanupblendmap(); extern void cleanshadowmap(); extern void cleanreflections(); extern void cleanupglare(); extern void cleanupdepthfx(); extern void cleanupshaders(); extern void cleanupgl(); recorder::cleanup(); cleanupva(); cleanupparticles(); cleanupsky(); cleanupmodels(); cleanuptextures(); cleanuplightmaps(); cleanupblendmap(); cleanshadowmap(); cleanreflections(); cleanupglare(); cleanupdepthfx(); cleanupshaders(); cleanupgl(); SDL_SetVideoMode(0, 0, 0, 0); int usedcolorbits = 0, useddepthbits = 0, usedfsaa = 0; setupscreen(usedcolorbits, useddepthbits, usedfsaa); gl_init(scr_w, scr_h, usedcolorbits, useddepthbits, usedfsaa); extern void reloadfonts(); extern void reloadtextures(); extern void reloadshaders(); inbetweenframes = false; if(!reloadtexture(*notexture) || !reloadtexture("data/logo.png") || !reloadtexture("data/logo_1024.png") || !reloadtexture("data/background.png") || !reloadtexture("data/background_detail.png") || !reloadtexture("data/background_decal.png") || !reloadtexture("data/mapshot_frame.png") || !reloadtexture("data/loading_frame.png") || !reloadtexture("data/loading_bar.png")) fatal("failed to reload core texture"); reloadfonts(); inbetweenframes = true; renderbackground("initializing..."); restoregamma(); reloadshaders(); reloadtextures(); initlights(); allchanged(true); } COMMAND(resetgl, ""); vector events; void pushevent(const SDL_Event &e) { events.add(e); } static bool filterevent(const SDL_Event &event) { switch(event.type) { case SDL_MOUSEMOTION: #ifndef WIN32 if(grabinput && !(screen->flags&SDL_FULLSCREEN)) { if(event.motion.x == screen->w / 2 && event.motion.y == screen->h / 2) return false; // ignore any motion events generated by SDL_WarpMouse #ifdef __APPLE__ if(event.motion.y == 0) return false; // let mac users drag windows via the title bar #endif } #endif break; } return true; } static inline bool pollevent(SDL_Event &event) { while(SDL_PollEvent(&event)) { if(filterevent(event)) return true; } return false; } bool interceptkey(int sym) { static int lastintercept = SDLK_UNKNOWN; int len = lastintercept == sym ? events.length() : 0; SDL_Event event; while(pollevent(event)) { switch(event.type) { case SDL_MOUSEMOTION: break; default: pushevent(event); break; } } lastintercept = sym; if(sym != SDLK_UNKNOWN) for(int i = len; i < events.length(); i++) { if(events[i].type == SDL_KEYDOWN && events[i].key.keysym.sym == sym) { events.remove(i); return true; } } return false; } static void ignoremousemotion() { SDL_Event e; SDL_PumpEvents(); while(SDL_PeepEvents(&e, 1, SDL_GETEVENT, SDL_EVENTMASK(SDL_MOUSEMOTION))); } static void resetmousemotion() { #ifndef WIN32 if(grabinput && !(screen->flags&SDL_FULLSCREEN)) { SDL_WarpMouse(screen->w / 2, screen->h / 2); } #endif } static void checkmousemotion(int &dx, int &dy) { loopv(events) { SDL_Event &event = events[i]; if(event.type != SDL_MOUSEMOTION) { if(i > 0) events.remove(0, i); return; } dx += event.motion.xrel; dy += event.motion.yrel; } events.setsize(0); SDL_Event event; while(pollevent(event)) { if(event.type != SDL_MOUSEMOTION) { events.add(event); return; } dx += event.motion.xrel; dy += event.motion.yrel; } } void checkinput() { SDL_Event event; int lasttype = 0, lastbut = 0; bool mousemoved = false; while(events.length() || pollevent(event)) { if(events.length()) event = events.remove(0); switch(event.type) { case SDL_QUIT: quit(); return; #if !defined(WIN32) && !defined(__APPLE__) case SDL_VIDEORESIZE: screenres(&event.resize.w, &event.resize.h); break; #endif case SDL_KEYDOWN: case SDL_KEYUP: keypress(event.key.keysym.sym, event.key.state==SDL_PRESSED, uni2cube(event.key.keysym.unicode)); break; case SDL_ACTIVEEVENT: if(event.active.state & SDL_APPINPUTFOCUS) inputgrab(grabinput = event.active.gain!=0); if(event.active.state & SDL_APPACTIVE) minimized = !event.active.gain; break; case SDL_MOUSEMOTION: if(grabinput) { int dx = event.motion.xrel, dy = event.motion.yrel; checkmousemotion(dx, dy); if(!g3d_movecursor(dx, dy)) mousemove(dx, dy); mousemoved = true; } break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: if(lasttype==event.type && lastbut==event.button.button) break; // why?? get event twice without it keypress(-event.button.button, event.button.state!=0, 0); lasttype = event.type; lastbut = event.button.button; break; } } if(mousemoved) resetmousemotion(); } void swapbuffers() { recorder::capture(); SDL_GL_SwapBuffers(); } VAR(menufps, 0, 60, 1000); VARP(maxfps, 0, 200, 1000); void limitfps(int &millis, int curmillis) { int limit = (mainmenu || minimized) && menufps ? (maxfps ? min(maxfps, menufps) : menufps) : maxfps; if(!limit) return; static int fpserror = 0; int delay = 1000/limit - (millis-curmillis); if(delay < 0) fpserror = 0; else { fpserror += 1000%limit; if(fpserror >= limit) { ++delay; fpserror -= limit; } if(delay > 0) { SDL_Delay(delay); millis += delay; } } } #if defined(WIN32) && !defined(_DEBUG) && !defined(__GNUC__) void stackdumper(unsigned int type, EXCEPTION_POINTERS *ep) { if(!ep) fatal("unknown type"); EXCEPTION_RECORD *er = ep->ExceptionRecord; CONTEXT *context = ep->ContextRecord; string out, t; formatstring(out)("Cube 2: Sauerbraten Win32 Exception: 0x%x [0x%x]\n\n", er->ExceptionCode, er->ExceptionCode==EXCEPTION_ACCESS_VIOLATION ? er->ExceptionInformation[1] : -1); SymInitialize(GetCurrentProcess(), NULL, TRUE); #ifdef _AMD64_ STACKFRAME64 sf = {{context->Rip, 0, AddrModeFlat}, {}, {context->Rbp, 0, AddrModeFlat}, {context->Rsp, 0, AddrModeFlat}, 0}; while(::StackWalk64(IMAGE_FILE_MACHINE_AMD64, GetCurrentProcess(), GetCurrentThread(), &sf, context, NULL, ::SymFunctionTableAccess, ::SymGetModuleBase, NULL)) { union { IMAGEHLP_SYMBOL64 sym; char symext[sizeof(IMAGEHLP_SYMBOL64) + sizeof(string)]; }; sym.SizeOfStruct = sizeof(sym); sym.MaxNameLength = sizeof(symext) - sizeof(sym); IMAGEHLP_LINE64 line; line.SizeOfStruct = sizeof(line); DWORD64 symoff; DWORD lineoff; if(SymGetSymFromAddr64(GetCurrentProcess(), sf.AddrPC.Offset, &symoff, &sym) && SymGetLineFromAddr64(GetCurrentProcess(), sf.AddrPC.Offset, &lineoff, &line)) #else STACKFRAME sf = {{context->Eip, 0, AddrModeFlat}, {}, {context->Ebp, 0, AddrModeFlat}, {context->Esp, 0, AddrModeFlat}, 0}; while(::StackWalk(IMAGE_FILE_MACHINE_I386, GetCurrentProcess(), GetCurrentThread(), &sf, context, NULL, ::SymFunctionTableAccess, ::SymGetModuleBase, NULL)) { union { IMAGEHLP_SYMBOL sym; char symext[sizeof(IMAGEHLP_SYMBOL) + sizeof(string)]; }; sym.SizeOfStruct = sizeof(sym); sym.MaxNameLength = sizeof(symext) - sizeof(sym); IMAGEHLP_LINE line; line.SizeOfStruct = sizeof(line); DWORD symoff, lineoff; if(SymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset, &symoff, &sym) && SymGetLineFromAddr(GetCurrentProcess(), sf.AddrPC.Offset, &lineoff, &line)) #endif { char *del = strrchr(line.FileName, '\\'); formatstring(t)("%s - %s [%d]\n", sym.Name, del ? del + 1 : line.FileName, line.LineNumber); concatstring(out, t); } } fatal(out); } #endif #define MAXFPSHISTORY 60 int fpspos = 0, fpshistory[MAXFPSHISTORY]; void resetfpshistory() { loopi(MAXFPSHISTORY) fpshistory[i] = 1; fpspos = 0; } void updatefpshistory(int millis) { fpshistory[fpspos++] = max(1, min(1000, millis)); if(fpspos>=MAXFPSHISTORY) fpspos = 0; } void getfps(int &fps, int &bestdiff, int &worstdiff) { int total = fpshistory[MAXFPSHISTORY-1], best = total, worst = total; loopi(MAXFPSHISTORY-1) { int millis = fpshistory[i]; total += millis; if(millis < best) best = millis; if(millis > worst) worst = millis; } fps = (1000*MAXFPSHISTORY)/total; bestdiff = 1000/best-fps; worstdiff = fps-1000/worst; } void getfps_(int *raw) { int fps, bestdiff, worstdiff; if(*raw) fps = 1000/fpshistory[(fpspos+MAXFPSHISTORY-1)%MAXFPSHISTORY]; else getfps(fps, bestdiff, worstdiff); intret(fps); } COMMANDN(getfps, getfps_, "i"); bool inbetweenframes = false, renderedframe = true; static bool findarg(int argc, char **argv, const char *str) { for(int i = 1; i 0 ? 1 : 0; shaderprecision = prec; break; } case 'l': { char pkgdir[] = "packages/"; load = strstr(path(&argv[i][2]), path(pkgdir)); if(load) load += sizeof(pkgdir)-1; else load = &argv[i][2]; break; } case 'x': initscript = &argv[i][2]; break; default: if(!serveroption(argv[i])) gameargs.add(argv[i]); break; } else gameargs.add(argv[i]); } initing = NOT_INITING; numcpus = clamp(guessnumcpus(), 1, 16); if(dedicated <= 1) { logoutf("init: sdl"); int par = 0; #ifdef _DEBUG par = SDL_INIT_NOPARACHUTE; #ifdef WIN32 SetEnvironmentVariable("SDL_DEBUG", "1"); #endif #endif if(SDL_Init(SDL_INIT_TIMER|SDL_INIT_VIDEO|SDL_INIT_AUDIO|par)<0) fatal("Unable to initialize SDL: %s", SDL_GetError()); const SDL_version *v = SDL_Linked_Version(); conoutf(CON_INIT, "Library: SDL %u.%u.%u", v->major, v->minor, v->patch); } logoutf("init: net"); if(enet_initialize()<0) fatal("Unable to initialise network module"); atexit(enet_deinitialize); enet_time_set(0); logoutf("init: game"); game::parseoptions(gameargs); initserver(dedicated>0, dedicated>1); // never returns if dedicated ASSERT(dedicated <= 1); game::initclient(); logoutf("init: video: mode"); const SDL_VideoInfo *video = SDL_GetVideoInfo(); if(video) { desktopw = video->current_w; desktoph = video->current_h; } int usedcolorbits = 0, useddepthbits = 0, usedfsaa = 0; setupscreen(usedcolorbits, useddepthbits, usedfsaa); logoutf("init: video: misc"); SDL_WM_SetCaption("Cube 2: Sauerbraten", NULL); keyrepeat(false); SDL_ShowCursor(0); logoutf("init: gl"); gl_checkextensions(); gl_init(scr_w, scr_h, usedcolorbits, useddepthbits, usedfsaa); notexture = textureload("packages/textures/notexture.png"); if(!notexture) fatal("could not find core textures"); logoutf("init: console"); if(!execfile("data/stdlib.cfg", false)) fatal("cannot find data files (you are running from the wrong folder, try .bat file in the main folder)"); // this is the first file we load. if(!execfile("data/font.cfg", false)) fatal("cannot find font definitions"); if(!setfont("default")) fatal("no default font specified"); inbetweenframes = true; renderbackground("initializing..."); logoutf("init: gl: effects"); loadshaders(); particleinit(); initdecals(); logoutf("init: world"); camera1 = player = game::iterdynents(0); emptymap(0, true, NULL, false); logoutf("init: sound"); initsound(); logoutf("init: cfg"); execfile("data/keymap.cfg"); execfile("data/stdedit.cfg"); execfile("data/menus.cfg"); execfile("data/sounds.cfg"); execfile("data/brush.cfg"); execfile("mybrushes.cfg", false); if(game::savedservers()) execfile(game::savedservers(), false); identflags |= IDF_PERSIST; initing = INIT_LOAD; if(!execfile(game::savedconfig(), false)) { execfile(game::defaultconfig()); writecfg(game::restoreconfig()); } execfile(game::autoexec(), false); initing = NOT_INITING; identflags &= ~IDF_PERSIST; string gamecfgname; copystring(gamecfgname, "data/game_"); concatstring(gamecfgname, game::gameident()); concatstring(gamecfgname, ".cfg"); execfile(gamecfgname); game::loadconfigs(); identflags |= IDF_PERSIST; if(execfile("once.cfg", false)) remove(findfile("once.cfg", "rb")); if(load) { logoutf("init: localconnect"); //localconnect(); game::changemap(load); } if(initscript) execute(initscript); logoutf("init: mainloop"); initmumble(); resetfpshistory(); inputgrab(grabinput = true); ignoremousemotion(); for(;;) { static int frames = 0; int millis = getclockmillis(); limitfps(millis, totalmillis); int elapsed = millis-totalmillis; static int timeerr = 0; int scaledtime = game::scaletime(elapsed) + timeerr; curtime = scaledtime/100; timeerr = scaledtime%100; if(!multiplayer(false) && curtime>200) curtime = 200; if(game::ispaused()) curtime = 0; lastmillis += curtime; totalmillis = millis; updatetime(); checkinput(); menuprocess(); tryedit(); if(lastmillis) game::updateworld(); checksleep(lastmillis); serverslice(false, 0); if(frames) updatefpshistory(elapsed); frames++; // miscellaneous general game effects recomputecamera(); updateparticles(); updatesounds(); if(minimized) continue; inbetweenframes = false; if(mainmenu) gl_drawmainmenu(screen->w, screen->h); else gl_drawframe(screen->w, screen->h); swapbuffers(); renderedframe = inbetweenframes = true; } ASSERT(0); return EXIT_FAILURE; #if defined(WIN32) && !defined(_DEBUG) && !defined(__GNUC__) } __except(stackdumper(0, GetExceptionInformation()), EXCEPTION_CONTINUE_SEARCH) { return 0; } #endif } sauerbraten-0.0.20130203.dfsg/engine/glare.cpp0000644000175000017500000000236411367763167020466 0ustar vincentvincent#include "engine.h" #include "rendertarget.h" static struct glaretexture : rendertarget { bool dorender() { extern void drawglare(); drawglare(); return true; } } glaretex; void cleanupglare() { glaretex.cleanup(true); } VARFP(glaresize, 6, 8, 10, cleanupglare()); VARP(glare, 0, 0, 1); VARP(blurglare, 0, 4, 7); VARP(blurglaresigma, 1, 50, 200); VAR(debugglare, 0, 0, 1); void viewglaretex() { if(!glare) return; glaretex.debug(); } bool glaring = false; void drawglaretex() { if(!glare || renderpath==R_FIXEDFUNCTION) return; glaretex.render(1<start(menustart, 0.03f, showtab ? &menutab : NULL); if(showtab) cgui->tab(header ? header : name, GUI_TITLE_COLOR); execute(contents); cgui->end(); cgui = NULL; } virtual void clear() { if(onclear) { freecode(onclear); onclear = NULL; } } }; struct delayedupdate { enum { INT, FLOAT, STRING, ACTION } type; ident *id; union { int i; float f; char *s; } val; delayedupdate() : type(ACTION), id(NULL) { val.s = NULL; } ~delayedupdate() { if(type == STRING || type == ACTION) DELETEA(val.s); } void schedule(const char *s) { type = ACTION; val.s = newstring(s); } void schedule(ident *var, int i) { type = INT; id = var; val.i = i; } void schedule(ident *var, float f) { type = FLOAT; id = var; val.f = f; } void schedule(ident *var, char *s) { type = STRING; id = var; val.s = newstring(s); } int getint() const { switch(type) { case INT: return val.i; case FLOAT: return int(val.f); case STRING: return int(strtol(val.s, NULL, 0)); default: return 0; } } float getfloat() const { switch(type) { case INT: return float(val.i); case FLOAT: return val.f; case STRING: return float(parsefloat(val.s)); default: return 0; } } const char *getstring() const { switch(type) { case INT: return intstr(val.i); case FLOAT: return intstr(int(floor(val.f))); case STRING: return val.s; default: return ""; } } void run() { if(type == ACTION) { if(val.s) execute(val.s); } else if(id) switch(id->type) { case ID_VAR: setvarchecked(id, getint()); break; case ID_FVAR: setfvarchecked(id, getfloat()); break; case ID_SVAR: setsvarchecked(id, getstring()); break; case ID_ALIAS: alias(id->name, getstring()); break; } } }; static hashtable guis; static vector guistack; static vector updatelater; static bool shouldclearmenu = true, clearlater = false; VARP(menudistance, 16, 40, 256); VARP(menuautoclose, 32, 120, 4096); vec menuinfrontofplayer() { vec dir; vecfromyawpitch(camera1->yaw, 0, 1, 0, dir); dir.mul(menudistance).add(camera1->o); dir.z -= player->eyeheight-1; return dir; } void popgui() { menu *m = guistack.pop(); m->clear(); } void removegui(menu *m) { loopv(guistack) if(guistack[i]==m) { guistack.remove(i); m->clear(); return; } } void pushgui(menu *m, int pos = -1) { if(guistack.empty()) { menupos = menuinfrontofplayer(); g3d_resetcursor(); } if(pos < 0) guistack.add(m); else guistack.insert(pos, m); if(pos < 0 || pos==guistack.length()-1) { menutab = 1; menustart = totalmillis; } if(m->init) execute(m->init); } void restoregui(int pos) { int clear = guistack.length()-pos-1; loopi(clear) popgui(); menutab = 1; menustart = totalmillis; } void showgui(const char *name) { menu *m = guis.access(name); if(!m) return; int pos = guistack.find(m); if(pos<0) pushgui(m); else restoregui(pos); } void hidegui(const char *name) { menu *m = guis.access(name); if(m) removegui(m); } int cleargui(int n) { int clear = guistack.length(); if(mainmenu && !isconnected(true) && clear > 0 && guistack[0]->name && !strcmp(guistack[0]->name, "main")) { clear--; if(!clear) return 1; } if(n>0) clear = min(clear, n); loopi(clear) popgui(); if(!guistack.empty()) restoregui(guistack.length()-1); return clear; } void clearguis(int level = -1) { if(level < 0) level = guistack.length(); loopvrev(guistack) { menu *m = guistack[i]; if(m->onclear) { uint *action = m->onclear; m->onclear = NULL; execute(action); freecode(action); } } cleargui(level); } void guionclear(char *action) { if(guistack.empty()) return; menu *m = guistack.last(); if(m->onclear) { freecode(m->onclear); m->onclear = NULL; } if(action[0]) m->onclear = compilecode(action); } void guistayopen(uint *contents) { bool oldclearmenu = shouldclearmenu; shouldclearmenu = false; execute(contents); shouldclearmenu = oldclearmenu; } void guinoautotab(uint *contents) { if(!cgui) return; cgui->allowautotab(false); execute(contents); cgui->allowautotab(true); } //@DOC name and icon are optional void guibutton(char *name, char *action, char *icon) { if(!cgui) return; bool hideicon = !strcmp(icon, "0"); int ret = cgui->button(name, GUI_BUTTON_COLOR, hideicon ? NULL : (icon[0] ? icon : (strstr(action, "showgui") ? "menu" : "action"))); if(ret&G3D_UP) { updatelater.add().schedule(action[0] ? action : name); if(shouldclearmenu) clearlater = true; } else if(ret&G3D_ROLLOVER) { alias("guirollovername", name); alias("guirolloveraction", action); } } void guiimage(char *path, char *action, float *scale, int *overlaid, char *alt) { if(!cgui) return; Texture *t = textureload(path, 0, true, false); if(t==notexture) { if(alt[0]) t = textureload(alt, 0, true, false); if(t==notexture) return; } int ret = cgui->image(t, *scale, *overlaid!=0); if(ret&G3D_UP) { if(*action) { updatelater.add().schedule(action); if(shouldclearmenu) clearlater = true; } } else if(ret&G3D_ROLLOVER) { alias("guirolloverimgpath", path); alias("guirolloverimgaction", action); } } void guicolor(int *color) { if(cgui) { defformatstring(desc)("0x%06X", *color); cgui->text(desc, *color, NULL); } } void guitextbox(char *text, int *width, int *height, int *color) { if(cgui && text[0]) cgui->textbox(text, *width ? *width : 12, *height ? *height : 1, *color ? *color : 0xFFFFFF); } void guitext(char *name, char *icon) { bool hideicon = !strcmp(icon, "0"); if(cgui) cgui->text(name, !hideicon && icon[0] ? GUI_BUTTON_COLOR : GUI_TEXT_COLOR, hideicon ? NULL : (icon[0] ? icon : "info")); } void guititle(char *name) { if(cgui) cgui->title(name, GUI_TITLE_COLOR); } void guitab(char *name) { if(cgui) cgui->tab(name, GUI_TITLE_COLOR); } void guibar() { if(cgui) cgui->separator(); } void guistrut(float *strut, int *alt) { if(cgui) { if(*alt) cgui->strut(*strut); else cgui->space(*strut); } } void guispring(int *weight) { if(cgui) cgui->spring(max(*weight, 1)); } void guicolumn(int *col) { if(cgui) cgui->column(*col); } template static void updateval(char *var, T val, char *onchange) { ident *id = writeident(var); updatelater.add().schedule(id, val); if(onchange[0]) updatelater.add().schedule(onchange); } static int getval(char *var) { ident *id = readident(var); if(!id) return 0; switch(id->type) { case ID_VAR: return *id->storage.i; case ID_FVAR: return int(*id->storage.f); case ID_SVAR: return parseint(*id->storage.s); case ID_ALIAS: return id->getint(); default: return 0; } } static float getfval(char *var) { ident *id = readident(var); if(!id) return 0; switch(id->type) { case ID_VAR: return *id->storage.i; case ID_FVAR: return *id->storage.f; case ID_SVAR: return parsefloat(*id->storage.s); case ID_ALIAS: return id->getfloat(); default: return 0; } } static const char *getsval(char *var) { ident *id = readident(var); if(!id) return ""; switch(id->type) { case ID_VAR: return intstr(*id->storage.i); case ID_FVAR: return floatstr(*id->storage.f); case ID_SVAR: return *id->storage.s; case ID_ALIAS: return id->getstr(); default: return ""; } } void guislider(char *var, int *min, int *max, char *onchange) { if(!cgui) return; int oldval = getval(var), val = oldval, vmin = *max > INT_MIN ? *min : getvarmin(var), vmax = *max > INT_MIN ? *max : getvarmax(var); cgui->slider(val, vmin, vmax, GUI_TITLE_COLOR); if(val != oldval) updateval(var, val, onchange); } void guilistslider(char *var, char *list, char *onchange) { if(!cgui) return; vector vals; list += strspn(list, "\n\t "); while(*list) { vals.add(parseint(list)); list += strcspn(list, "\n\t \0"); list += strspn(list, "\n\t "); } if(vals.empty()) return; int val = getval(var), oldoffset = vals.length()-1, offset = oldoffset; loopv(vals) if(val <= vals[i]) { oldoffset = offset = i; break; } cgui->slider(offset, 0, vals.length()-1, GUI_TITLE_COLOR, intstr(val)); if(offset != oldoffset) updateval(var, vals[offset], onchange); } void guinameslider(char *var, char *names, char *list, char *onchange) { if(!cgui) return; vector vals; list += strspn(list, "\n\t "); while(*list) { vals.add(parseint(list)); list += strcspn(list, "\n\t \0"); list += strspn(list, "\n\t "); } if(vals.empty()) return; int val = getval(var), oldoffset = vals.length()-1, offset = oldoffset; loopv(vals) if(val <= vals[i]) { oldoffset = offset = i; break; } char *label = indexlist(names, offset); cgui->slider(offset, 0, vals.length()-1, GUI_TITLE_COLOR, label); if(offset != oldoffset) updateval(var, vals[offset], onchange); delete[] label; } void guicheckbox(char *name, char *var, float *on, float *off, char *onchange) { bool enabled = getfval(var)!=*off; if(cgui && cgui->button(name, GUI_BUTTON_COLOR, enabled ? "checkbox_on" : "checkbox_off")&G3D_UP) { updateval(var, enabled ? *off : (*on || *off ? *on : 1.0f), onchange); } } void guiradio(char *name, char *var, float *n, char *onchange) { bool enabled = getfval(var)==*n; if(cgui && cgui->button(name, GUI_BUTTON_COLOR, enabled ? "radio_on" : "radio_off")&G3D_UP) { if(!enabled) updateval(var, *n, onchange); } } void guibitfield(char *name, char *var, int *mask, char *onchange) { int val = getval(var); bool enabled = (val & *mask) != 0; if(cgui && cgui->button(name, GUI_BUTTON_COLOR, enabled ? "checkbox_on" : "checkbox_off")&G3D_UP) { updateval(var, enabled ? val & ~*mask : val | *mask, onchange); } } //-ve length indicates a wrapped text field of any (approx 260 chars) length, |length| is the field width void guifield(char *var, int *maxlength, char *onchange) { if(!cgui) return; const char *initval = getsval(var); char *result = cgui->field(var, GUI_BUTTON_COLOR, *maxlength ? *maxlength : 12, 0, initval); if(result) updateval(var, result, onchange); } //-ve maxlength indicates a wrapped text field of any (approx 260 chars) length, |maxlength| is the field width void guieditor(char *name, int *maxlength, int *height, int *mode) { if(!cgui) return; cgui->field(name, GUI_BUTTON_COLOR, *maxlength ? *maxlength : 12, *height, NULL, *mode<=0 ? EDITORFOREVER : *mode); //returns a non-NULL pointer (the currentline) when the user commits, could then manipulate via text* commands } //-ve length indicates a wrapped text field of any (approx 260 chars) length, |length| is the field width void guikeyfield(char *var, int *maxlength, char *onchange) { if(!cgui) return; const char *initval = getsval(var); char *result = cgui->keyfield(var, GUI_BUTTON_COLOR, *maxlength ? *maxlength : -8, 0, initval); if(result) updateval(var, result, onchange); } //use text to do more... void guilist(uint *contents) { if(!cgui) return; cgui->pushlist(); execute(contents); cgui->poplist(); } void guialign(int *align, uint *contents) { if(!cgui) return; cgui->pushlist(); if(*align >= 0) cgui->spring(); execute(contents); if(*align == 0) cgui->spring(); cgui->poplist(); } void newgui(char *name, char *contents, char *header, char *init) { menu *m = guis.access(name); if(!m) { name = newstring(name); m = &guis[name]; m->name = name; } else { DELETEA(m->header); freecode(m->contents); freecode(m->init); } if(header && header[0]) { char *end = NULL; int val = strtol(header, &end, 0); if(end && !*end) { m->header = NULL; m->showtab = val != 0; } else { m->header = newstring(header); m->showtab = true; } } else { m->header = NULL; m->showtab = true; } m->contents = compilecode(contents); m->init = init && init[0] ? compilecode(init) : NULL; } menu *guiserversmenu = NULL; void guiservers(uint *header, int *pagemin, int *pagemax) { extern const char *showservers(g3d_gui *cgui, uint *header, int pagemin, int pagemax); if(cgui) { const char *command = showservers(cgui, header, *pagemin, *pagemax > 0 ? *pagemax : INT_MAX); if(command) { updatelater.add().schedule(command); if(shouldclearmenu) clearlater = true; guiserversmenu = clearlater || guistack.empty() ? NULL : guistack.last(); } } } void notifywelcome() { if(guiserversmenu) { if(guistack.length() && guistack.last() == guiserversmenu) clearguis(); guiserversmenu = NULL; } } COMMAND(newgui, "ssss"); COMMAND(guibutton, "sss"); COMMAND(guitext, "ss"); COMMAND(guiservers, "eii"); ICOMMAND(cleargui, "i", (int *n), intret(cleargui(*n))); COMMAND(showgui, "s"); COMMAND(hidegui, "s"); COMMAND(guionclear, "s"); COMMAND(guistayopen, "e"); COMMAND(guinoautotab, "e"); COMMAND(guilist, "e"); COMMAND(guialign, "ie"); COMMAND(guititle, "s"); COMMAND(guibar,""); COMMAND(guistrut,"fi"); COMMAND(guispring, "i"); COMMAND(guicolumn, "i"); COMMAND(guiimage,"ssfis"); COMMAND(guislider,"sbbs"); COMMAND(guilistslider, "sss"); COMMAND(guinameslider, "ssss"); COMMAND(guiradio,"ssfs"); COMMAND(guibitfield, "ssis"); COMMAND(guicheckbox, "ssffs"); COMMAND(guitab, "s"); COMMAND(guifield, "sis"); COMMAND(guikeyfield, "sis"); COMMAND(guieditor, "siii"); COMMAND(guicolor, "i"); COMMAND(guitextbox, "siii"); void guiplayerpreview(int *model, int *team, int *weap, char *action, float *scale, int *overlaid) { if(!cgui) return; int ret = cgui->playerpreview(*model, *team, *weap, *scale, *overlaid!=0); if(ret&G3D_UP) { if(*action) { updatelater.add().schedule(action); if(shouldclearmenu) clearlater = true; } } } COMMAND(guiplayerpreview, "iiisfi"); void guimodelpreview(char *model, char *animspec, char *action, float *scale, int *overlaid) { if(!cgui) return; int anim = ANIM_ALL; if(animspec[0]) { if(isdigit(animspec[0])) { anim = parseint(animspec); if(anim >= 0) anim %= ANIM_INDEX; else anim = ANIM_ALL; } else { vector anims; findanims(animspec, anims); if(anims.length()) anim = anims[0]; } } int ret = cgui->modelpreview(model, anim|ANIM_LOOP, *scale, *overlaid!=0); if(ret&G3D_UP) { if(*action) { updatelater.add().schedule(action); if(shouldclearmenu) clearlater = true; } } } COMMAND(guimodelpreview, "sssfi"); struct change { int type; const char *desc; change() {} change(int type, const char *desc) : type(type), desc(desc) {} }; static vector needsapply; static struct applymenu : menu { void gui(g3d_gui &g, bool firstpass) { if(guistack.empty()) return; g.start(menustart, 0.03f); g.text("the following settings have changed:", GUI_TEXT_COLOR, "info"); loopv(needsapply) g.text(needsapply[i].desc, GUI_TEXT_COLOR, "info"); g.separator(); g.text("apply changes now?", GUI_TEXT_COLOR, "info"); if(g.button("yes", GUI_BUTTON_COLOR, "action")&G3D_UP) { int changetypes = 0; loopv(needsapply) changetypes |= needsapply[i].type; if(changetypes&CHANGE_GFX) updatelater.add().schedule("resetgl"); if(changetypes&CHANGE_SOUND) updatelater.add().schedule("resetsound"); clearlater = true; } if(g.button("no", GUI_BUTTON_COLOR, "action")&G3D_UP) clearlater = true; g.end(); } void clear() { menu::clear(); needsapply.shrink(0); } } applymenu; VARP(applydialog, 0, 1, 1); static bool processingmenu = false; void addchange(const char *desc, int type) { if(!applydialog) return; loopv(needsapply) if(!strcmp(needsapply[i].desc, desc)) return; needsapply.add(change(type, desc)); if(needsapply.length() && guistack.find(&applymenu) < 0) pushgui(&applymenu, processingmenu ? max(guistack.length()-1, 0) : -1); } void clearchanges(int type) { loopv(needsapply) { if(needsapply[i].type&type) { needsapply[i].type &= ~type; if(!needsapply[i].type) needsapply.remove(i--); } } if(needsapply.empty()) removegui(&applymenu); } void menuprocess() { processingmenu = true; int wasmain = mainmenu, level = guistack.length(); loopv(updatelater) updatelater[i].run(); updatelater.shrink(0); if(wasmain > mainmenu || clearlater) { if(wasmain > mainmenu || level==guistack.length()) clearguis(level); clearlater = false; } if(mainmenu && !isconnected(true) && guistack.empty()) showgui("main"); processingmenu = false; } VAR(mainmenu, 1, 1, 0); void clearmainmenu() { if(mainmenu && isconnected()) { mainmenu = 0; if(!processingmenu) cleargui(); } } void g3d_mainmenu() { if(!guistack.empty()) { extern int usegui2d; if(!mainmenu && !usegui2d && camera1->o.dist(menupos) > menuautoclose) cleargui(); else g3d_addgui(guistack.last(), menupos, GUI_2D | GUI_FOLLOW); } } sauerbraten-0.0.20130203.dfsg/engine/master.cpp0000644000175000017500000004713112072027322020644 0ustar vincentvincent#include "cube.h" #include #include #define INPUT_LIMIT 4096 #define OUTPUT_LIMIT (64*1024) #define CLIENT_TIME (3*60*1000) #define AUTH_TIME (30*1000) #define AUTH_LIMIT 100 #define AUTH_THROTTLE 1000 #define CLIENT_LIMIT 8192 #define DUP_LIMIT 16 #define PING_TIME 3000 #define PING_RETRY 5 #define KEEPALIVE_TIME (65*60*1000) #define SERVER_LIMIT (10*1024) FILE *logfile = NULL; struct userinfo { char *name; void *pubkey; }; hashtable users; void adduser(char *name, char *pubkey) { name = newstring(name); userinfo &u = users[name]; u.name = name; u.pubkey = parsepubkey(pubkey); } COMMAND(adduser, "ss"); void clearusers() { enumerate(users, userinfo, u, { delete[] u.name; freepubkey(u.pubkey); }); users.clear(); } COMMAND(clearusers, ""); struct baninfo { enet_uint32 ip, mask; }; vector bans, servbans, gbans; void clearbans() { bans.shrink(0); servbans.shrink(0); gbans.shrink(0); } COMMAND(clearbans, ""); void addban(vector &bans, const char *name) { union { uchar b[sizeof(enet_uint32)]; enet_uint32 i; } ip, mask; ip.i = 0; mask.i = 0; loopi(4) { char *end = NULL; int n = strtol(name, &end, 10); if(!end) break; if(end > name) { ip.b[i] = n; mask.b[i] = 0xFF; } name = end; while(*name && *name++ != '.'); } baninfo &ban = bans.add(); ban.ip = ip.i; ban.mask = mask.i; } ICOMMAND(ban, "s", (char *name), addban(bans, name)); ICOMMAND(servban, "s", (char *name), addban(servbans, name)); ICOMMAND(gban, "s", (char *name), addban(gbans, name)); char *printban(const baninfo &ban, char *buf) { union { uchar b[sizeof(enet_uint32)]; enet_uint32 i; } ip, mask; ip.i = ban.ip; mask.i = ban.mask; int lastdigit = -1; loopi(4) if(mask.b[i]) { if(lastdigit >= 0) *buf++ = '.'; loopj(i - lastdigit - 1) { *buf++ = '*'; *buf++ = '.'; } buf += sprintf(buf, "%d", ip.b[i]); lastdigit = i; } return buf; } bool checkban(vector &bans, enet_uint32 host) { loopv(bans) if((host & bans[i].mask) == bans[i].ip) return true; return false; } struct authreq { enet_uint32 reqtime; uint id; void *answer; }; struct gameserver { ENetAddress address; string ip; int port, numpings; enet_uint32 lastping, lastpong; }; vector gameservers; struct messagebuf { vector &owner; vector buf; int refs; messagebuf(vector &owner) : owner(owner), refs(0) {} const char *getbuf() { return buf.getbuf(); } int length() { return buf.length(); } void purge(); bool equals(const messagebuf &m) const { return buf.length() == m.buf.length() && !memcmp(buf.getbuf(), m.buf.getbuf(), buf.length()); } bool endswith(const messagebuf &m) const { return buf.length() >= m.buf.length() && !memcmp(&buf[buf.length() - m.buf.length()], m.buf.getbuf(), m.buf.length()); } void concat(const messagebuf &m) { if(buf.length() && buf.last() == '\0') buf.pop(); buf.put(m.buf.getbuf(), m.buf.length()); } }; vector gameserverlists, gbanlists; bool updateserverlist = true; struct client { ENetAddress address; ENetSocket socket; char input[INPUT_LIMIT]; messagebuf *message; vector output; int inputpos, outputpos; enet_uint32 connecttime, lastinput; int servport; enet_uint32 lastauth; vector authreqs; bool shouldpurge; bool registeredserver; client() : message(NULL), inputpos(0), outputpos(0), servport(-1), lastauth(0), shouldpurge(false), registeredserver(false) {} }; vector clients; ENetSocket serversocket = ENET_SOCKET_NULL; time_t starttime; enet_uint32 servtime = 0; void fatal(const char *fmt, ...) { va_list args; va_start(args, fmt); vfprintf(logfile, fmt, args); fputc('\n', logfile); va_end(args); exit(EXIT_FAILURE); } void conoutfv(int type, const char *fmt, va_list args) { vfprintf(logfile, fmt, args); fputc('\n', logfile); } void conoutf(const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(CON_INFO, fmt, args); va_end(args); } void conoutf(int type, const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(type, fmt, args); va_end(args); } void purgeclient(int n) { client &c = *clients[n]; if(c.message) c.message->purge(); enet_socket_destroy(c.socket); delete clients[n]; clients.remove(n); } void output(client &c, const char *msg, int len = 0) { if(!len) len = strlen(msg); c.output.put(msg, len); } void outputf(client &c, const char *fmt, ...) { string msg; va_list args; va_start(args, fmt); vformatstring(msg, fmt, args); va_end(args); output(c, msg); } ENetSocket pingsocket = ENET_SOCKET_NULL; bool setuppingsocket(ENetAddress *address) { if(pingsocket != ENET_SOCKET_NULL) return true; pingsocket = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM); if(pingsocket == ENET_SOCKET_NULL) return false; if(address && enet_socket_bind(pingsocket, address) < 0) return false; enet_socket_set_option(pingsocket, ENET_SOCKOPT_NONBLOCK, 1); return true; } void setupserver(int port, const char *ip = NULL) { ENetAddress address; address.host = ENET_HOST_ANY; address.port = port; if(ip) { if(enet_address_set_host(&address, ip)<0) fatal("failed to resolve server address: %s", ip); } serversocket = enet_socket_create(ENET_SOCKET_TYPE_STREAM); if(serversocket==ENET_SOCKET_NULL || enet_socket_set_option(serversocket, ENET_SOCKOPT_REUSEADDR, 1) < 0 || enet_socket_bind(serversocket, &address) < 0 || enet_socket_listen(serversocket, -1) < 0) fatal("failed to create server socket"); if(enet_socket_set_option(serversocket, ENET_SOCKOPT_NONBLOCK, 1)<0) fatal("failed to make server socket non-blocking"); if(!setuppingsocket(&address)) fatal("failed to create ping socket"); enet_time_set(0); starttime = time(NULL); char *ct = ctime(&starttime); if(strchr(ct, '\n')) *strchr(ct, '\n') = '\0'; conoutf("*** Starting master server on %s %d at %s ***", ip ? ip : "localhost", port, ct); } void genserverlist() { if(!updateserverlist) return; while(gameserverlists.length() && gameserverlists.last()->refs<=0) delete gameserverlists.pop(); messagebuf *l = new messagebuf(gameserverlists); loopv(gameservers) { gameserver &s = *gameservers[i]; if(!s.lastpong) continue; defformatstring(cmd)("addserver %s %d\n", s.ip, s.port); l->buf.put(cmd, strlen(cmd)); } l->buf.add('\0'); gameserverlists.add(l); updateserverlist = false; } void gengbanlist() { messagebuf *l = new messagebuf(gbanlists); const char *header = "cleargbans\n"; l->buf.put(header, strlen(header)); string cmd = "addgban "; int cmdlen = strlen(cmd); loopv(gbans) { baninfo &b = gbans[i]; l->buf.put(cmd, printban(b, &cmd[cmdlen]) - cmd); l->buf.add('\n'); } if(gbanlists.length() && gbanlists.last()->equals(*l)) { delete l; return; } while(gbanlists.length() && gbanlists.last()->refs<=0) delete gbanlists.pop(); loopv(gbanlists) { messagebuf *m = gbanlists[i]; if(m->refs > 0 && !m->endswith(*l)) m->concat(*l); } gbanlists.add(l); loopv(clients) { client &c = *clients[i]; if(c.servport >= 0 && !c.message) { c.message = l; c.message->refs++; } } } void addgameserver(client &c) { if(gameservers.length() >= SERVER_LIMIT) return; loopv(gameservers) { gameserver &s = *gameservers[i]; if(s.address.host == c.address.host && s.port == c.servport) { s.lastping = 0; s.numpings = 0; return; } } string hostname; if(enet_address_get_host_ip(&c.address, hostname, sizeof(hostname)) < 0) { outputf(c, "failreg failed resolving ip\n"); return; } gameserver &s = *gameservers.add(new gameserver); s.address.host = c.address.host; s.address.port = c.servport+1; copystring(s.ip, hostname); s.port = c.servport; s.numpings = 0; s.lastping = s.lastpong = 0; } client *findclient(gameserver &s) { loopv(clients) { client &c = *clients[i]; if(s.address.host == c.address.host && s.port == c.servport) return &c; } return NULL; } void servermessage(gameserver &s, const char *msg) { client *c = findclient(s); if(c) outputf(*c, msg); } void checkserverpongs() { ENetBuffer buf; ENetAddress addr; static uchar pong[MAXTRANS]; for(;;) { buf.data = pong; buf.dataLength = sizeof(pong); int len = enet_socket_receive(pingsocket, &addr, &buf, 1); if(len <= 0) break; loopv(gameservers) { gameserver &s = *gameservers[i]; if(s.address.host == addr.host && s.address.port == addr.port) { if(s.lastping && (!s.lastpong || ENET_TIME_GREATER(s.lastping, s.lastpong))) { client *c = findclient(s); if(c) { c->registeredserver = true; outputf(*c, "succreg\n"); if(!c->message && gbanlists.length()) { c->message = gbanlists.last(); c->message->refs++; } } } if(!s.lastpong) updateserverlist = true; s.lastpong = servtime ? servtime : 1; break; } } } } void bangameservers() { loopvrev(gameservers) if(checkban(servbans, gameservers[i]->address.host)) { delete gameservers.remove(i); updateserverlist = true; } } void checkgameservers() { ENetBuffer buf; loopv(gameservers) { gameserver &s = *gameservers[i]; if(s.lastping && s.lastpong && ENET_TIME_LESS_EQUAL(s.lastping, s.lastpong)) { if(ENET_TIME_DIFFERENCE(servtime, s.lastpong) > KEEPALIVE_TIME) { delete gameservers.remove(i--); updateserverlist = true; } } else if(!s.lastping || ENET_TIME_DIFFERENCE(servtime, s.lastping) > PING_TIME) { if(s.numpings >= PING_RETRY) { servermessage(s, "failreg failed pinging server\n"); delete gameservers.remove(i--); updateserverlist = true; } else { static const uchar ping[] = { 1 }; buf.data = (void *)ping; buf.dataLength = sizeof(ping); s.numpings++; s.lastping = servtime ? servtime : 1; enet_socket_send(pingsocket, &s.address, &buf, 1); } } } } void messagebuf::purge() { refs = max(refs - 1, 0); if(refs<=0 && owner.last()!=this) { owner.removeobj(this); delete this; } } void purgeauths(client &c) { int expired = 0; loopv(c.authreqs) { if(ENET_TIME_DIFFERENCE(servtime, c.authreqs[i].reqtime) >= AUTH_TIME) { outputf(c, "failauth %u\n", c.authreqs[i].id); freechallenge(c.authreqs[i].answer); expired = i + 1; } else break; } if(expired > 0) c.authreqs.remove(0, expired); } void reqauth(client &c, uint id, char *name) { if(ENET_TIME_DIFFERENCE(servtime, c.lastauth) < AUTH_THROTTLE) return; c.lastauth = servtime; purgeauths(c); time_t t = time(NULL); char *ct = ctime(&t); if(ct) { char *newline = strchr(ct, '\n'); if(newline) *newline = '\0'; } string ip; if(enet_address_get_host_ip(&c.address, ip, sizeof(ip)) < 0) copystring(ip, "-"); conoutf("%s: attempting \"%s\" as %u from %s", ct ? ct : "-", name, id, ip); userinfo *u = users.access(name); if(!u) { outputf(c, "failauth %u\n", id); return; } if(c.authreqs.length() >= AUTH_LIMIT) { outputf(c, "failauth %u\n", c.authreqs[0].id); freechallenge(c.authreqs[0].answer); c.authreqs.remove(0); } authreq &a = c.authreqs.add(); a.reqtime = servtime; a.id = id; uint seed[3] = { uint(starttime), servtime, randomMT() }; static vector buf; buf.setsize(0); a.answer = genchallenge(u->pubkey, seed, sizeof(seed), buf); outputf(c, "chalauth %u %s\n", id, buf.getbuf()); } void confauth(client &c, uint id, const char *val) { purgeauths(c); loopv(c.authreqs) if(c.authreqs[i].id == id) { string ip; if(enet_address_get_host_ip(&c.address, ip, sizeof(ip)) < 0) copystring(ip, "-"); if(checkchallenge(val, c.authreqs[i].answer)) { outputf(c, "succauth %u\n", id); conoutf("succeeded %u from %s", id, ip); } else { outputf(c, "failauth %u\n", id); conoutf("failed %u from %s", id, ip); } freechallenge(c.authreqs[i].answer); c.authreqs.remove(i--); return; } outputf(c, "failauth %u\n", id); } bool checkclientinput(client &c) { if(c.inputpos<0) return true; char *end = (char *)memchr(c.input, '\n', c.inputpos); while(end) { *end++ = '\0'; c.lastinput = servtime; int port; uint id; string user, val; if(!strncmp(c.input, "list", 4) && (!c.input[4] || c.input[4] == '\n' || c.input[4] == '\r')) { genserverlist(); if(gameserverlists.empty() || c.message) return false; c.message = gameserverlists.last(); c.message->refs++; c.output.setsize(0); c.outputpos = 0; c.shouldpurge = true; return true; } else if(sscanf(c.input, "regserv %d", &port) == 1) { if(checkban(servbans, c.address.host)) return false; if(port < 0 || port + 1 < 0 || (c.servport >= 0 && port != c.servport)) outputf(c, "failreg invalid port\n"); else { c.servport = port; addgameserver(c); } } else if(sscanf(c.input, "reqauth %u %100s", &id, user) == 2) { reqauth(c, id, user); } else if(sscanf(c.input, "confauth %u %100s", &id, val) == 2) { confauth(c, id, val); } c.inputpos = &c.input[c.inputpos] - end; memmove(c.input, end, c.inputpos); end = (char *)memchr(c.input, '\n', c.inputpos); } return c.inputpos<(int)sizeof(c.input); } ENetSocketSet readset, writeset; void checkclients() { ENetSocketSet readset, writeset; ENetSocket maxsock = max(serversocket, pingsocket); ENET_SOCKETSET_EMPTY(readset); ENET_SOCKETSET_EMPTY(writeset); ENET_SOCKETSET_ADD(readset, serversocket); ENET_SOCKETSET_ADD(readset, pingsocket); loopv(clients) { client &c = *clients[i]; if(c.authreqs.length()) purgeauths(c); if(c.message || c.output.length()) ENET_SOCKETSET_ADD(writeset, c.socket); else ENET_SOCKETSET_ADD(readset, c.socket); maxsock = max(maxsock, c.socket); } if(enet_socketset_select(maxsock, &readset, &writeset, 1000)<=0) return; if(ENET_SOCKETSET_CHECK(readset, pingsocket)) checkserverpongs(); if(ENET_SOCKETSET_CHECK(readset, serversocket)) { ENetAddress address; ENetSocket clientsocket = enet_socket_accept(serversocket, &address); if(clients.length()>=CLIENT_LIMIT || checkban(bans, address.host)) enet_socket_destroy(clientsocket); else if(clientsocket!=ENET_SOCKET_NULL) { int dups = 0, oldest = -1; loopv(clients) if(clients[i]->address.host == address.host) { dups++; if(oldest<0 || clients[i]->connecttime < clients[oldest]->connecttime) oldest = i; } if(dups >= DUP_LIMIT) purgeclient(oldest); client *c = new client; c->address = address; c->socket = clientsocket; c->connecttime = servtime; c->lastinput = servtime; clients.add(c); } } loopv(clients) { client &c = *clients[i]; if((c.message || c.output.length()) && ENET_SOCKETSET_CHECK(writeset, c.socket)) { const char *data = c.output.length() ? c.output.getbuf() : c.message->getbuf(); int len = c.output.length() ? c.output.length() : c.message->length(); ENetBuffer buf; buf.data = (void *)&data[c.outputpos]; buf.dataLength = len-c.outputpos; int res = enet_socket_send(c.socket, NULL, &buf, 1); if(res>=0) { c.outputpos += res; if(c.outputpos>=len) { if(c.output.length()) c.output.setsize(0); else { c.message->purge(); c.message = NULL; } c.outputpos = 0; if(!c.message && c.output.empty() && c.shouldpurge) { purgeclient(i--); continue; } } } else { purgeclient(i--); continue; } } if(ENET_SOCKETSET_CHECK(readset, c.socket)) { ENetBuffer buf; buf.data = &c.input[c.inputpos]; buf.dataLength = sizeof(c.input) - c.inputpos; int res = enet_socket_receive(c.socket, NULL, &buf, 1); if(res>0) { c.inputpos += res; c.input[min(c.inputpos, (int)sizeof(c.input)-1)] = '\0'; if(!checkclientinput(c)) { purgeclient(i--); continue; } } else { purgeclient(i--); continue; } } if(c.output.length() > OUTPUT_LIMIT) { purgeclient(i--); continue; } if(ENET_TIME_DIFFERENCE(servtime, c.lastinput) >= (c.registeredserver ? KEEPALIVE_TIME : CLIENT_TIME)) { purgeclient(i--); continue; } } } void banclients() { loopvrev(clients) if(checkban(bans, clients[i]->address.host)) purgeclient(i); } volatile bool reloadcfg = true; void reloadsignal(int signum) { reloadcfg = true; } int main(int argc, char **argv) { if(enet_initialize()<0) fatal("Unable to initialise network module"); atexit(enet_deinitialize); const char *dir = "", *ip = NULL; int port = 28787; if(argc>=2) dir = argv[1]; if(argc>=3) port = atoi(argv[2]); if(argc>=4) ip = argv[3]; defformatstring(logname)("%smaster.log", dir); defformatstring(cfgname)("%smaster.cfg", dir); path(logname); path(cfgname); logfile = fopen(logname, "a"); if(!logfile) logfile = stdout; setvbuf(logfile, NULL, _IOLBF, BUFSIZ); #ifndef WIN32 signal(SIGUSR1, reloadsignal); #endif setupserver(port, ip); for(;;) { if(reloadcfg) { conoutf("reloading master.cfg"); execfile(cfgname); bangameservers(); banclients(); gengbanlist(); reloadcfg = false; } servtime = enet_time_get(); checkclients(); checkgameservers(); } return EXIT_SUCCESS; } sauerbraten-0.0.20130203.dfsg/engine/renderva.cpp0000644000175000017500000026341712066663645021207 0ustar vincentvincent// renderva.cpp: handles the occlusion and rendering of vertex arrays #include "engine.h" static inline void drawtris(GLsizei numindices, const GLvoid *indices, ushort minvert, ushort maxvert) { if(hasDRE) glDrawRangeElements_(GL_TRIANGLES, minvert, maxvert, numindices, GL_UNSIGNED_SHORT, indices); else glDrawElements(GL_TRIANGLES, numindices, GL_UNSIGNED_SHORT, indices); glde++; } static inline void drawvatris(vtxarray *va, GLsizei numindices, const GLvoid *indices) { drawtris(numindices, indices, va->minvert, va->maxvert); } ///////// view frustrum culling /////////////////////// plane vfcP[5]; // perpindictular vectors to view frustrum bounding planes float vfcDfog; // far plane culling distance (fog limit). float vfcDnear[5], vfcDfar[5]; vtxarray *visibleva; bool isfoggedsphere(float rad, const vec &cv) { loopi(4) if(vfcP[i].dist(cv) < -rad) return true; float dist = vfcP[4].dist(cv); return dist < -rad || dist > vfcDfog + rad; } int isvisiblesphere(float rad, const vec &cv) { int v = VFC_FULL_VISIBLE; float dist; loopi(5) { dist = vfcP[i].dist(cv); if(dist < -rad) return VFC_NOT_VISIBLE; if(dist < rad) v = VFC_PART_VISIBLE; } dist -= vfcDfog; if(dist > rad) return VFC_FOGGED; //VFC_NOT_VISIBLE; // culling when fog is closer than size of world results in HOM if(dist > -rad) v = VFC_PART_VISIBLE; return v; } static inline int ishiddencube(const ivec &o, int size) { loopi(5) if(o.dist(vfcP[i]) < -vfcDfar[i]*size) return true; return false; } static inline int isfoggedcube(const ivec &o, int size) { loopi(4) if(o.dist(vfcP[i]) < -vfcDfar[i]*size) return true; float dist = o.dist(vfcP[4]); return dist < -vfcDfar[4]*size || dist > vfcDfog - vfcDnear[4]*size; } int isvisiblecube(const ivec &o, int size) { int v = VFC_FULL_VISIBLE; float dist; loopi(5) { dist = o.dist(vfcP[i]); if(dist < -vfcDfar[i]*size) return VFC_NOT_VISIBLE; if(dist < -vfcDnear[i]*size) v = VFC_PART_VISIBLE; } dist -= vfcDfog; if(dist > -vfcDnear[4]*size) return VFC_FOGGED; if(dist > -vfcDfar[4]*size) v = VFC_PART_VISIBLE; return v; } float vadist(vtxarray *va, const vec &p) { return p.dist_to_bb(va->bbmin, va->bbmax); } #define VASORTSIZE 64 static vtxarray *vasort[VASORTSIZE]; void addvisibleva(vtxarray *va) { float dist = vadist(va, camera1->o); va->distance = int(dist); /*cv.dist(camera1->o) - va->size*SQRT3/2*/ int hash = min(int(dist*VASORTSIZE/worldsize), VASORTSIZE-1); vtxarray **prev = &vasort[hash], *cur = vasort[hash]; while(cur && va->distance >= cur->distance) { prev = &cur->next; cur = cur->next; } va->next = *prev; *prev = va; } void sortvisiblevas() { visibleva = NULL; vtxarray **last = &visibleva; loopi(VASORTSIZE) if(vasort[i]) { vtxarray *va = vasort[i]; *last = va; while(va->next) va = va->next; last = &va->next; } } void findvisiblevas(vector &vas, bool resetocclude = false) { loopv(vas) { vtxarray &v = *vas[i]; int prevvfc = resetocclude ? VFC_NOT_VISIBLE : v.curvfc; v.curvfc = isvisiblecube(v.o, v.size); if(v.curvfc!=VFC_NOT_VISIBLE) { if(pvsoccluded(v.o, v.size)) { v.curvfc += PVS_FULL_VISIBLE - VFC_FULL_VISIBLE; continue; } addvisibleva(&v); if(v.children.length()) findvisiblevas(v.children, prevvfc>=VFC_NOT_VISIBLE); if(prevvfc>=VFC_NOT_VISIBLE) { v.occluded = !v.texs ? OCCLUDE_GEOM : OCCLUDE_NOTHING; v.query = NULL; } } } } void calcvfcD() { loopi(5) { plane &p = vfcP[i]; vfcDnear[i] = vfcDfar[i] = 0; loopk(3) if(p[k] > 0) vfcDfar[i] += p[k]; else vfcDnear[i] += p[k]; } } void setvfcP(float z, const vec &bbmin, const vec &bbmax) { vec4 px = mvpmatrix.getrow(0), py = mvpmatrix.getrow(1), pz = mvpmatrix.getrow(2), pw = mvpmatrix.getrow(3); vfcP[0] = plane(vec4(pw).mul(-bbmin.x).add(px)).normalize(); // left plane vfcP[1] = plane(vec4(pw).mul(bbmax.x).sub(px)).normalize(); // right plane vfcP[2] = plane(vec4(pw).mul(-bbmin.y).add(py)).normalize(); // bottom plane vfcP[3] = plane(vec4(pw).mul(bbmax.y).sub(py)).normalize(); // top plane vfcP[4] = plane(vec4(pw).add(pz)).normalize(); // near/far planes if(z >= 0) loopi(5) vfcP[i].reflectz(z); extern int fog; vfcDfog = fog; calcvfcD(); } plane oldvfcP[5]; void savevfcP() { memcpy(oldvfcP, vfcP, sizeof(vfcP)); } void restorevfcP() { memcpy(vfcP, oldvfcP, sizeof(vfcP)); calcvfcD(); } extern vector varoot, valist; void visiblecubes(bool cull) { memset(vasort, 0, sizeof(vasort)); if(cull) { setvfcP(); findvisiblevas(varoot); sortvisiblevas(); } else { memset(vfcP, 0, sizeof(vfcP)); vfcDfog = 1000000; memset(vfcDnear, 0, sizeof(vfcDnear)); memset(vfcDfar, 0, sizeof(vfcDfar)); visibleva = NULL; loopv(valist) { vtxarray *va = valist[i]; va->distance = 0; va->curvfc = VFC_FULL_VISIBLE; va->occluded = !va->texs ? OCCLUDE_GEOM : OCCLUDE_NOTHING; va->query = NULL; va->next = visibleva; visibleva = va; } } } static inline bool insideva(const vtxarray *va, const vec &v, int margin = 2) { int size = va->size + margin; return v.x>=va->o.x-margin && v.y>=va->o.y-margin && v.z>=va->o.z-margin && v.x<=va->o.x+size && v.y<=va->o.y+size && v.z<=va->o.z+size; } ///////// occlusion queries ///////////// #define MAXQUERY 2048 struct queryframe { int cur, max; occludequery queries[MAXQUERY]; }; static queryframe queryframes[2] = {{0, 0}, {0, 0}}; static uint flipquery = 0; int getnumqueries() { return queryframes[flipquery].cur; } void flipqueries() { flipquery = (flipquery + 1) % 2; queryframe &qf = queryframes[flipquery]; loopi(qf.cur) qf.queries[i].owner = NULL; qf.cur = 0; } occludequery *newquery(void *owner) { queryframe &qf = queryframes[flipquery]; if(qf.cur >= qf.max) { if(qf.max >= MAXQUERY) return NULL; glGenQueries_(1, &qf.queries[qf.max++].id); } occludequery *query = &qf.queries[qf.cur++]; query->owner = owner; query->fragments = -1; return query; } void resetqueries() { loopi(2) loopj(queryframes[i].max) queryframes[i].queries[j].owner = NULL; } void clearqueries() { loopi(2) { queryframe &qf = queryframes[i]; loopj(qf.max) { glDeleteQueries_(1, &qf.queries[j].id); qf.queries[j].owner = NULL; } qf.cur = qf.max = 0; } } VAR(oqfrags, 0, 8, 64); VAR(oqwait, 0, 1, 1); bool checkquery(occludequery *query, bool nowait) { GLuint fragments; if(query->fragments >= 0) fragments = query->fragments; else { if(nowait || !oqwait) { GLint avail; glGetQueryObjectiv_(query->id, GL_QUERY_RESULT_AVAILABLE, &avail); if(!avail) return false; } glGetQueryObjectuiv_(query->id, GL_QUERY_RESULT_ARB, &fragments); query->fragments = fragments; } return fragments < uint(oqfrags); } void drawbb(const ivec &bo, const ivec &br, const vec &camera) { glBegin(GL_QUADS); #define GENFACEORIENT(orient, v0, v1, v2, v3) do { \ int dim = dimension(orient); \ if(dimcoord(orient)) \ { \ if(camera[dim] < bo[dim] + br[dim]) continue; \ } \ else if(camera[dim] > bo[dim]) continue; \ v0 v1 v2 v3 \ xtraverts += 4; \ } while(0); #define GENFACEVERT(orient, vert, ox,oy,oz, rx,ry,rz) \ glVertex3f(ox rx, oy ry, oz rz); GENFACEVERTS(bo.x, bo.x + br.x, bo.y, bo.y + br.y, bo.z, bo.z + br.z, , , , , , ) #undef GENFACEORIENT #undef GENFACEVERTS glEnd(); } extern int octaentsize; static octaentities *visiblemms, **lastvisiblemms; static inline bool insideoe(const octaentities *oe, const vec &v, int margin = 1) { return v.x>=oe->bbmin.x-margin && v.y>=oe->bbmin.y-margin && v.z>=oe->bbmin.z-margin && v.x<=oe->bbmax.x+margin && v.y<=oe->bbmax.y+margin && v.z<=oe->bbmax.z+margin; } void findvisiblemms(const vector &ents) { for(vtxarray *va = visibleva; va; va = va->next) { if(va->mapmodels.empty() || va->curvfc >= VFC_FOGGED || va->occluded >= OCCLUDE_BB) continue; loopv(va->mapmodels) { octaentities *oe = va->mapmodels[i]; if(isfoggedcube(oe->o, oe->size) || pvsoccluded(oe->bbmin, ivec(oe->bbmax).sub(oe->bbmin))) continue; bool occluded = oe->query && oe->query->owner == oe && checkquery(oe->query); if(occluded) { oe->distance = -1; oe->next = NULL; *lastvisiblemms = oe; lastvisiblemms = &oe->next; } else { int visible = 0; loopv(oe->mapmodels) { extentity &e = *ents[oe->mapmodels[i]]; if(e.flags&extentity::F_NOVIS) continue; e.visible = true; ++visible; } if(!visible) continue; oe->distance = int(camera1->o.dist_to_bb(oe->o, oe->size)); octaentities **prev = &visiblemms, *cur = visiblemms; while(cur && cur->distance >= 0 && oe->distance > cur->distance) { prev = &cur->next; cur = cur->next; } if(*prev == NULL) lastvisiblemms = &oe->next; oe->next = *prev; *prev = oe; } } } } VAR(oqmm, 0, 4, 8); extern bool getentboundingbox(extentity &e, ivec &o, ivec &r); void rendermapmodel(extentity &e) { int anim = ANIM_MAPMODEL|ANIM_LOOP, basetime = 0; if(e.flags&extentity::F_ANIM) entities::animatemapmodel(e, anim, basetime); mapmodelinfo *mmi = getmminfo(e.attr2); if(mmi) rendermodel(&e.light, mmi->name, anim, e.o, e.attr1, 0, MDL_CULL_VFC | MDL_CULL_DIST | MDL_DYNLIGHT, NULL, NULL, basetime); } extern int reflectdist; vtxarray *reflectedva; void renderreflectedmapmodels() { const vector &ents = entities::getents(); octaentities *mms = visiblemms; if(reflecting) { octaentities **lastmms = &mms; for(vtxarray *va = reflectedva; va; va = va->rnext) { if(va->mapmodels.empty() || va->distance > reflectdist) continue; loopv(va->mapmodels) { octaentities *oe = va->mapmodels[i]; *lastmms = oe; lastmms = &oe->rnext; } } *lastmms = NULL; } for(octaentities *oe = mms; oe; oe = reflecting ? oe->rnext : oe->next) if(reflecting || oe->distance >= 0) { if(reflecting || refracting>0 ? oe->bbmax.z <= reflectz : oe->bbmin.z >= reflectz) continue; if(isfoggedcube(oe->o, oe->size)) continue; loopv(oe->mapmodels) { extentity &e = *ents[oe->mapmodels[i]]; if(e.visible || e.flags&extentity::F_NOVIS) continue; e.visible = true; } } if(mms) { startmodelbatches(); for(octaentities *oe = mms; oe; oe = reflecting ? oe->rnext : oe->next) { loopv(oe->mapmodels) { extentity &e = *ents[oe->mapmodels[i]]; if(!e.visible) continue; rendermapmodel(e); e.visible = false; } } endmodelbatches(); } } void rendermapmodels() { const vector &ents = entities::getents(); visiblemms = NULL; lastvisiblemms = &visiblemms; findvisiblemms(ents); static int skipoq = 0; bool doquery = hasOQ && oqfrags && oqmm; startmodelbatches(); for(octaentities *oe = visiblemms; oe; oe = oe->next) if(oe->distance>=0) { bool rendered = false; loopv(oe->mapmodels) { extentity &e = *ents[oe->mapmodels[i]]; if(!e.visible) continue; if(!rendered) { rendered = true; oe->query = doquery && oe->distance>0 && !(++skipoq%oqmm) ? newquery(oe) : NULL; if(oe->query) startmodelquery(oe->query); } rendermapmodel(e); e.visible = false; } if(rendered && oe->query) endmodelquery(); } endmodelbatches(); bool colormask = true; for(octaentities *oe = visiblemms; oe; oe = oe->next) if(oe->distance<0) { oe->query = doquery && !insideoe(oe, camera1->o) ? newquery(oe) : NULL; if(!oe->query) continue; if(colormask) { glDepthMask(GL_FALSE); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); nocolorshader->set(); colormask = false; } startquery(oe->query); drawbb(oe->bbmin, ivec(oe->bbmax).sub(oe->bbmin)); endquery(oe->query); } if(!colormask) { glDepthMask(GL_TRUE); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, fading ? GL_FALSE : GL_TRUE); } } static inline bool bbinsideva(const ivec &bo, const ivec &br, vtxarray *va) { return bo.x >= va->bbmin.x && bo.y >= va->bbmin.y && va->o.z >= va->bbmin.z && bo.x + br.x <= va->bbmax.x && bo.y + br.y <= va->bbmax.y && bo.z + br.z <= va->bbmax.z; } static inline bool bboccluded(const ivec &bo, const ivec &br, cube *c, const ivec &o, int size) { loopoctabox(o, size, bo, br) { ivec co(i, o.x, o.y, o.z, size); if(c[i].ext && c[i].ext->va) { vtxarray *va = c[i].ext->va; if(va->curvfc >= VFC_FOGGED || (va->occluded >= OCCLUDE_BB && bbinsideva(bo, br, va))) continue; } if(c[i].children && bboccluded(bo, br, c[i].children, co, size>>1)) continue; return false; } return true; } bool bboccluded(const ivec &bo, const ivec &br) { int diff = (bo.x^(bo.x+br.x)) | (bo.y^(bo.y+br.y)) | (bo.z^(bo.z+br.z)); if(diff&~((1<ext && c->ext->va) { vtxarray *va = c->ext->va; if(va->curvfc >= VFC_FOGGED || (va->occluded >= OCCLUDE_BB && bbinsideva(bo, br, va))) return true; } scale--; while(c->children && !(diff&(1<children[octastep(bo.x, bo.y, bo.z, scale)]; if(c->ext && c->ext->va) { vtxarray *va = c->ext->va; if(va->curvfc >= VFC_FOGGED || (va->occluded >= OCCLUDE_BB && bbinsideva(bo, br, va))) return true; } scale--; } if(c->children) return bboccluded(bo, br, c->children, ivec(bo).mask(~((2<=2) { glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glEnable(GL_TEXTURE_GEN_T); } } static void disabletexgen(int dims = 2) { glDisable(GL_TEXTURE_GEN_S); if(dims>=2) glDisable(GL_TEXTURE_GEN_T); } VAR(outline, 0, 0, 1); HVARP(outlinecolour, 0, 0, 0xFFFFFF); VAR(dtoutline, 0, 1, 1); void renderoutline() { lineshader->set(); glDisable(GL_TEXTURE_2D); glEnableClientState(GL_VERTEX_ARRAY); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor3ub((outlinecolour>>16)&0xFF, (outlinecolour>>8)&0xFF, outlinecolour&0xFF); enablepolygonoffset(GL_POLYGON_OFFSET_LINE); if(!dtoutline) glDisable(GL_DEPTH_TEST); vtxarray *prev = NULL; for(vtxarray *va = visibleva; va; va = va->next) { if(va->occluded >= OCCLUDE_BB) continue; if(!va->alphaback && !va->alphafront && (!va->texs || va->occluded >= OCCLUDE_GEOM)) continue; if(!prev || va->vbuf != prev->vbuf) { if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->ebuf); } glVertexPointer(3, GL_FLOAT, VTXSIZE, va->vdata[0].pos.v); } if(va->texs && va->occluded < OCCLUDE_GEOM) { drawvatris(va, 3*va->tris, va->edata); xtravertsva += va->verts; } if(va->alphaback || va->alphafront) { drawvatris(va, 3*(va->alphabacktris + va->alphafronttris), &va->edata[3*(va->tris + va->blendtris)]); xtravertsva += 3*(va->alphabacktris + va->alphafronttris); } prev = va; } if(!dtoutline) glEnable(GL_DEPTH_TEST); disablepolygonoffset(GL_POLYGON_OFFSET_LINE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); glEnable(GL_TEXTURE_2D); defaultshader->set(); } HVAR(blendbrushcolor, 0, 0x0000C0, 0xFFFFFF); void renderblendbrush(GLuint tex, float x, float y, float w, float h) { SETSHADER(blendbrush); glEnableClientState(GL_VERTEX_ARRAY); glDepthFunc(GL_LEQUAL); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, tex); glColor4ub((blendbrushcolor>>16)&0xFF, (blendbrushcolor>>8)&0xFF, blendbrushcolor&0xFF, 0x40); GLfloat s[4] = { 1.0f/w, 0, 0, -x/w }, t[4] = { 0, 1.0f/h, 0, -y/h }; if(renderpath==R_FIXEDFUNCTION) { setuptexgen(); glTexGenfv(GL_S, GL_OBJECT_PLANE, s); glTexGenfv(GL_T, GL_OBJECT_PLANE, t); } else { setlocalparamfv("texgenS", SHPARAM_VERTEX, 0, s); setlocalparamfv("texgenT", SHPARAM_VERTEX, 1, t); } vtxarray *prev = NULL; for(vtxarray *va = visibleva; va; va = va->next) { if(!va->texs || va->occluded >= OCCLUDE_GEOM) continue; if(va->o.x + va->size <= x || va->o.y + va->size <= y || va->o.x >= x + w || va->o.y >= y + h) continue; if(!prev || va->vbuf != prev->vbuf) { if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->ebuf); } glVertexPointer(3, GL_FLOAT, VTXSIZE, va->vdata[0].pos.v); } drawvatris(va, 3*va->tris, va->edata); xtravertsva += va->verts; prev = va; } if(renderpath==R_FIXEDFUNCTION) disabletexgen(); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); glDepthFunc(GL_LESS); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); notextureshader->set(); } void rendershadowmapreceivers() { if(!hasBE) return; SETSHADER(shadowmapreceiver); glDisable(GL_TEXTURE_2D); glEnableClientState(GL_VERTEX_ARRAY); glCullFace(GL_FRONT); glDepthMask(GL_FALSE); glDepthFunc(GL_GREATER); extern int ati_minmax_bug; if(!ati_minmax_bug) glColorMask(GL_FALSE, GL_FALSE, GL_TRUE, GL_FALSE); glEnable(GL_BLEND); glBlendEquation_(GL_MAX_EXT); glBlendFunc(GL_ONE, GL_ONE); vtxarray *prev = NULL; for(vtxarray *va = visibleva; va; va = va->next) { if(!va->texs || va->curvfc >= VFC_FOGGED || !isshadowmapreceiver(va)) continue; if(!prev || va->vbuf != prev->vbuf) { if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->ebuf); } glVertexPointer(3, GL_FLOAT, VTXSIZE, va->vdata[0].pos.v); } drawvatris(va, 3*va->tris, va->edata); xtravertsva += va->verts; prev = va; } glDisable(GL_BLEND); glBlendEquation_(GL_FUNC_ADD_EXT); glCullFace(GL_BACK); glDepthMask(GL_TRUE); glDepthFunc(GL_LESS); if(!ati_minmax_bug) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); glEnable(GL_TEXTURE_2D); } void renderdepthobstacles(const vec &bbmin, const vec &bbmax, float scale, float *ranges, int numranges) { float scales[4] = { 0, 0, 0, 0 }, offsets[4] = { 0, 0, 0, 0 }; if(numranges < 0) { SETSHADER(depthfxsplitworld); loopi(-numranges) { if(!i) scales[i] = 1.0f/scale; else scales[i] = scales[i-1]*256; } } else { SETSHADER(depthfxworld); if(!numranges) loopi(4) scales[i] = 1.0f/scale; else loopi(numranges) { scales[i] = 1.0f/scale; offsets[i] = -ranges[i]/scale; } } setlocalparamfv("depthscale", SHPARAM_VERTEX, 0, scales); setlocalparamfv("depthoffsets", SHPARAM_VERTEX, 1, offsets); glDisable(GL_TEXTURE_2D); glEnableClientState(GL_VERTEX_ARRAY); vtxarray *prev = NULL; for(vtxarray *va = visibleva; va; va = va->next) { if(!va->texs || va->occluded >= OCCLUDE_GEOM || va->o.x > bbmax.x || va->o.y > bbmax.y || va->o.z > bbmax.z || va->o.x + va->size < bbmin.x || va->o.y + va->size < bbmin.y || va->o.z + va->size < bbmin.z) continue; if(!prev || va->vbuf != prev->vbuf) { if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->ebuf); } glVertexPointer(3, GL_FLOAT, VTXSIZE, va->vdata[0].pos.v); } drawvatris(va, 3*va->tris, va->edata); xtravertsva += va->verts; if(va->alphabacktris + va->alphafronttris > 0) { drawvatris(va, 3*(va->alphabacktris + va->alphafronttris), va->edata + 3*(va->tris + va->blendtris)); xtravertsva += 3*(va->alphabacktris + va->alphafronttris); } prev = va; } if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); glEnable(GL_TEXTURE_2D); defaultshader->set(); } VAR(oqdist, 0, 256, 1024); VAR(zpass, 0, 1, 1); VAR(glowpass, 0, 1, 1); VAR(envpass, 0, 1, 1); struct renderstate { bool colormask, depthmask, blending, mtglow; int skipped, alphaing; GLuint vbuf; int diffusetmu, lightmaptmu, glowtmu, causticstmu; GLfloat color[4], fogcolor[4]; vec colorscale, glowcolor, envscale, lightcolor; float alphascale; GLuint textures[8]; Slot *slot, *texgenslot; VSlot *vslot, *texgenvslot; float texgenscrollS, texgenscrollT; int texgendim; bool mttexgen, specmask; int visibledynlights; uint dynlightmask; vec dynlightpos; float dynlightradius; renderstate() : colormask(true), depthmask(true), blending(false), mtglow(false), skipped(0), alphaing(0), vbuf(0), diffusetmu(0), lightmaptmu(1), glowtmu(-1), causticstmu(-1), colorscale(1, 1, 1), glowcolor(1, 1, 1), envscale(0, 0, 0), alphascale(0), slot(NULL), texgenslot(NULL), vslot(NULL), texgenvslot(NULL), texgenscrollS(0), texgenscrollT(0), texgendim(-1), mttexgen(false), specmask(false), visibledynlights(0), dynlightmask(0) { loopk(4) color[k] = 1; loopk(8) textures[k] = 0; } }; void renderquery(renderstate &cur, occludequery *query, vtxarray *va, bool full = true) { nocolorshader->set(); if(cur.colormask) { cur.colormask = false; glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); } if(cur.depthmask) { cur.depthmask = false; glDepthMask(GL_FALSE); } vec camera(camera1->o); if(reflecting) camera.z = reflectz; startquery(query); if(full) drawbb(ivec(va->bbmin).sub(1), ivec(va->bbmax).sub(va->bbmin).add(2), camera); else drawbb(va->geommin, ivec(va->geommax).sub(va->geommin), camera); endquery(query); extern int intel_immediate_bug; if(intel_immediate_bug && cur.vbuf) cur.vbuf = 0; } enum { RENDERPASS_LIGHTMAP = 0, RENDERPASS_COLOR, RENDERPASS_Z, RENDERPASS_GLOW, RENDERPASS_ENVMAP, RENDERPASS_CAUSTICS, RENDERPASS_FOG, RENDERPASS_SHADOWMAP, RENDERPASS_DYNLIGHT, RENDERPASS_LIGHTMAP_BLEND }; struct geombatch { const elementset &es; VSlot &vslot; ushort *edata; vtxarray *va; int next, batch; geombatch(const elementset &es, ushort *edata, vtxarray *va) : es(es), vslot(lookupvslot(es.texture)), edata(edata), va(va), next(-1), batch(-1) {} int compare(const geombatch &b) const { if(va->vbuf < b.va->vbuf) return -1; if(va->vbuf > b.va->vbuf) return 1; if(renderpath!=R_FIXEDFUNCTION) { if(va->dynlightmask < b.va->dynlightmask) return -1; if(va->dynlightmask > b.va->dynlightmask) return 1; if(vslot.slot->shader < b.vslot.slot->shader) return -1; if(vslot.slot->shader > b.vslot.slot->shader) return 1; if(vslot.slot->params.length() < b.vslot.slot->params.length()) return -1; if(vslot.slot->params.length() > b.vslot.slot->params.length()) return 1; } if(es.texture < b.es.texture) return -1; if(es.texture > b.es.texture) return 1; if(es.lmid < b.es.lmid) return -1; if(es.lmid > b.es.lmid) return 1; if(es.envmap < b.es.envmap) return -1; if(es.envmap > b.es.envmap) return 1; if(es.dim < b.es.dim) return -1; if(es.dim > b.es.dim) return 1; return 0; } }; static vector geombatches; static int firstbatch = -1, numbatches = 0; static void mergetexs(renderstate &cur, vtxarray *va, elementset *texs = NULL, int numtexs = 0, ushort *edata = NULL) { if(!texs) { texs = va->eslist; numtexs = va->texs; edata = va->edata; if(cur.alphaing) { texs += va->texs + va->blends; edata += 3*(va->tris + va->blendtris); numtexs = va->alphaback; if(cur.alphaing > 1) numtexs += va->alphafront; } } if(firstbatch < 0) { firstbatch = geombatches.length(); numbatches = numtexs; loopi(numtexs-1) { geombatches.add(geombatch(texs[i], edata, va)).next = i+1; edata += texs[i].length[1]; } geombatches.add(geombatch(texs[numtexs-1], edata, va)); return; } int prevbatch = -1, curbatch = firstbatch, curtex = 0; do { geombatch &b = geombatches.add(geombatch(texs[curtex], edata, va)); edata += texs[curtex].length[1]; int dir = -1; while(curbatch >= 0) { dir = b.compare(geombatches[curbatch]); if(dir <= 0) break; prevbatch = curbatch; curbatch = geombatches[curbatch].next; } if(!dir) { int last = curbatch, next; for(;;) { next = geombatches[last].batch; if(next < 0) break; last = next; } if(last==curbatch) { b.batch = curbatch; b.next = geombatches[curbatch].next; if(prevbatch < 0) firstbatch = geombatches.length()-1; else geombatches[prevbatch].next = geombatches.length()-1; curbatch = geombatches.length()-1; } else { b.batch = next; geombatches[last].batch = geombatches.length()-1; } } else { numbatches++; b.next = curbatch; if(prevbatch < 0) firstbatch = geombatches.length()-1; else geombatches[prevbatch].next = geombatches.length()-1; prevbatch = geombatches.length()-1; } } while(++curtex < numtexs); } static void mergeglowtexs(renderstate &cur, vtxarray *va) { int start = -1; ushort *edata = va->edata, *startdata = NULL; int firsttex = 0, numtexs = va->texs; if(cur.alphaing) { firsttex += va->texs + va->blends; edata += 3*(va->tris + va->blendtris); numtexs = va->alphaback; if(cur.alphaing > 1) numtexs += va->alphafront; } for(int i = firsttex; i < firsttex + numtexs; i++) { elementset &es = va->eslist[i]; VSlot &vslot = lookupvslot(es.texture, false); if(vslot.slot->texmask&(1<=0) { mergetexs(cur, va, &va->eslist[start], i-start, startdata); start = -1; } edata += es.length[1]; } if(start>=0) mergetexs(cur, va, &va->eslist[start], firsttex+numtexs-start, startdata); } static void mergeenvmaptexs(renderstate &cur, vtxarray *va) { int start = -1; ushort *edata = va->edata, *startdata = NULL; int firsttex = 0, numtexs = va->texs; if(cur.alphaing) { firsttex += va->texs + va->blends; edata += 3*(va->tris + va->blendtris); numtexs = va->alphaback; if(cur.alphaing > 1) numtexs += va->alphafront; } for(int i = firsttex; i < firsttex + numtexs; i++) { elementset &es = va->eslist[i]; VSlot &vslot = lookupvslot(es.texture, false); if(vslot.slot->shader->type&SHADER_ENVMAP && vslot.skipped&(1<=0) { mergetexs(cur, va, &va->eslist[start], i-start, startdata); start = -1; } edata += es.length[1]; } if(start>=0) mergetexs(cur, va, &va->eslist[start], firsttex+numtexs-start, startdata); } static void changedynlightpos(renderstate &cur) { GLfloat tx[4] = { 0.5f/cur.dynlightradius, 0, 0, 0.5f - 0.5f*cur.dynlightpos.x/cur.dynlightradius }, ty[4] = { 0, 0.5f/cur.dynlightradius, 0, 0.5f - 0.5f*cur.dynlightpos.y/cur.dynlightradius }, tz[4] = { 0, 0, 0.5f/cur.dynlightradius, 0.5f - 0.5f*cur.dynlightpos.z/cur.dynlightradius }; glActiveTexture_(GL_TEXTURE0_ARB); glTexGenfv(GL_S, GL_OBJECT_PLANE, tx); glTexGenfv(GL_T, GL_OBJECT_PLANE, ty); glActiveTexture_(GL_TEXTURE1_ARB); glTexGenfv(GL_S, GL_OBJECT_PLANE, tz); glActiveTexture_(GL_TEXTURE2_ARB); } static void changevbuf(renderstate &cur, int pass, vtxarray *va) { if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->ebuf); } cur.vbuf = va->vbuf; glVertexPointer(3, GL_FLOAT, VTXSIZE, va->vdata[0].pos.v); if(pass==RENDERPASS_LIGHTMAP) { glTexCoordPointer(2, GL_FLOAT, VTXSIZE, &va->vdata[0].u); if(cur.glowtmu >= 0) { glClientActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glTexCoordPointer(2, GL_FLOAT, VTXSIZE, &va->vdata[0].u); } glClientActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); glTexCoordPointer(2, renderpath==R_FIXEDFUNCTION ? GL_FLOAT : GL_SHORT, VTXSIZE, &va->vdata[0].lmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); if(renderpath!=R_FIXEDFUNCTION) { glNormalPointer(GL_BYTE, VTXSIZE, va->vdata[0].norm.v); glColorPointer(4, GL_UNSIGNED_BYTE, VTXSIZE, va->vdata[0].tangent.v); } else if(cur.glowtmu >= 0 && hasCM && maxtmus >= 2) glNormalPointer(GL_BYTE, VTXSIZE, va->vdata[0].norm.v); } else if(pass == RENDERPASS_ENVMAP) { glTexCoordPointer(2, GL_FLOAT, VTXSIZE, &va->vdata[0].u); glNormalPointer(GL_BYTE, VTXSIZE, va->vdata[0].norm.v); } else if(pass==RENDERPASS_COLOR || pass==RENDERPASS_GLOW || pass==RENDERPASS_DYNLIGHT) glTexCoordPointer(2, GL_FLOAT, VTXSIZE, &va->vdata[0].u); } static void changebatchtmus(renderstate &cur, int pass, geombatch &b) { bool changed = false; extern bool brightengeom; extern int fullbright; int lmid = brightengeom && (b.es.lmid < LMID_RESERVED || (fullbright && editmode)) ? LMID_BRIGHT : b.es.lmid; if(cur.textures[cur.lightmaptmu]!=lightmaptexs[lmid].id) { glActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); glBindTexture(GL_TEXTURE_2D, cur.textures[cur.lightmaptmu] = lightmaptexs[lmid].id); changed = true; } if(renderpath==R_FIXEDFUNCTION) { if(b.vslot.slot->shader->type&SHADER_ENVMAP && b.es.envmap!=EMID_CUSTOM && cur.envscale.x) { GLuint emtex = lookupenvmap(b.es.envmap); if(cur.textures[cur.glowtmu]!=emtex) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, cur.textures[cur.glowtmu] = emtex); changed = true; } } } else { int tmu = cur.lightmaptmu+1; if(b.vslot.slot->shader->type&SHADER_NORMALSLMS) { if(cur.textures[tmu]!=lightmaptexs[lmid+1].id) { glActiveTexture_(GL_TEXTURE0_ARB+tmu); glBindTexture(GL_TEXTURE_2D, cur.textures[tmu] = lightmaptexs[lmid+1].id); changed = true; } tmu++; } if(b.vslot.slot->shader->type&SHADER_ENVMAP && b.es.envmap!=EMID_CUSTOM) { GLuint emtex = lookupenvmap(b.es.envmap); if(cur.textures[tmu]!=emtex) { glActiveTexture_(GL_TEXTURE0_ARB+tmu); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, cur.textures[tmu] = emtex); changed = true; } } } if(changed) glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); if(cur.dynlightmask != b.va->dynlightmask) { cur.visibledynlights = setdynlights(b.va); cur.dynlightmask = b.va->dynlightmask; } } static inline void disableenv(renderstate &cur) { glDisable(GL_TEXTURE_CUBE_MAP_ARB); glDisableClientState(GL_NORMAL_ARRAY); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_R); } static inline void enableenv(renderstate &cur) { setuptmu(cur.glowtmu, "T , P @ Pa", "= Pa"); glEnableClientState(GL_NORMAL_ARRAY); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glEnable(GL_TEXTURE_GEN_R); glMatrixMode(GL_TEXTURE); glLoadMatrixf(envmatrix.v); glMatrixMode(GL_MODELVIEW); glEnable(GL_TEXTURE_CUBE_MAP_ARB); } static inline void disableglow(renderstate &cur) { glDisable(GL_TEXTURE_2D); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } static inline void enableglow(renderstate &cur, bool shouldsetuptmu = true) { if(shouldsetuptmu) setuptmu(cur.glowtmu, "P + T", "= Pa"); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glEnable(GL_TEXTURE_2D); } static void changeenv(renderstate &cur, int pass, Slot &slot, VSlot &vslot, geombatch *b = NULL) { if(pass==RENDERPASS_ENVMAP) { bool specmask = slot.sts.length() && slot.sts[0].t->bpp >= 4; if(cur.envscale != vslot.envscale) { if(vslot.envscale.x != vslot.envscale.y || vslot.envscale.y != vslot.envscale.z) { if(hasBC && !specmask) { if(cur.envscale.x == cur.envscale.y && cur.envscale.y == cur.envscale.z) glBlendFunc(GL_CONSTANT_COLOR_EXT, GL_ONE_MINUS_CONSTANT_COLOR_EXT); glBlendColor_(vslot.envscale.x, vslot.envscale.y, vslot.envscale.z, 1); cur.envscale = vslot.envscale; } else { if(cur.envscale.x != cur.envscale.y || cur.envscale.y != cur.envscale.z) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // fake it, take the average and do a constant blend float envscale = (min(vslot.envscale.x, min(vslot.envscale.y, vslot.envscale.z)) + max(vslot.envscale.x, max(vslot.envscale.y, vslot.envscale.z)))/2; glColor4f(1, 1, 1, envscale); cur.envscale = vec(envscale, envscale, envscale); } } else { if(cur.envscale.x != cur.envscale.y || cur.envscale.y != cur.envscale.z) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1, 1, 1, vslot.envscale.x); cur.envscale = vslot.envscale; } } if(cur.specmask != specmask) { if(!specmask) glDisable(GL_TEXTURE_2D); else if(specmask) glEnable(GL_TEXTURE_2D); cur.specmask = specmask; } GLuint tex = 0; if(b) { if(b->es.envmap==EMID_CUSTOM) return; tex = lookupenvmap(b->es.envmap); } else { if(!(slot.texmask&(1<id; break; } } } glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, cur.textures[cur.glowtmu] = tex); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); return; } if(slot.texmask&(1<= 0 || vslot.envscale.x != vslot.envscale.y || vslot.envscale.y != vslot.envscale.z || !vslot.envscale.x) { cur.skipped |= 1<id) glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, cur.textures[cur.glowtmu] = t.t->id); break; } } } static void changeglow(renderstate &cur, int pass, Slot &slot, VSlot &vslot) { vec color = vslot.glowcolor; if(vslot.pulseglowspeed) { float k = lastmillis*vslot.pulseglowspeed; k -= floor(k); k = fabs(k*2 - 1); color.lerp(color, vslot.pulseglowcolor, k); } if(pass==RENDERPASS_GLOW) { if(cur.glowcolor!=color) glColor3fv(color.v); } else { if(cur.glowcolor!=color || cur.envscale.x) { if(color==vec(1, 1, 1)) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); setuptmu(cur.glowtmu, "P + T", "= Pa"); } else if((hasTE3 || hasTE4) && cur.colorscale == vec(1, 1, 1)) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); if(cur.glowcolor==vec(1, 1, 1)) { if(hasTE3) setuptmu(cur.glowtmu, "TPC3", "= Pa"); else if(hasTE4) setuptmu(cur.glowtmu, "TCP14", "= Pa"); } memcpy(cur.color, color.v, sizeof(color)); glColor4fv(cur.color); } else { cur.skipped |= 1<id) glBindTexture(GL_TEXTURE_2D, cur.textures[cur.glowtmu] = t.t->id); break; } } cur.glowcolor = color; } static void changecolor(renderstate &cur, int pass, Slot &slot, VSlot &vslot) { if(vslot.colorscale == vec(1, 1, 1)) { if(cur.causticstmu >= 0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.causticstmu+1); setuptmu(cur.causticstmu+1, "= P"); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); } else if(pass==RENDERPASS_LIGHTMAP) setuptmu(cur.diffusetmu, "= T"); } else if(cur.colorscale == vec(1, 1, 1)) { if(cur.causticstmu >= 0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.causticstmu+1); setuptmu(cur.causticstmu+1, "C * P"); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); } else if(pass==RENDERPASS_LIGHTMAP) setuptmu(cur.diffusetmu, "C * T"); if(cur.glowcolor != vec(1, 1, 1)) { cur.glowcolor.x = -1; if(cur.mtglow && !cur.envscale.x) { cur.mtglow = false; glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glDisable(GL_TEXTURE_2D); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); } } } cur.colorscale = vslot.colorscale; memcpy(cur.color, vslot.colorscale.v, sizeof(vslot.colorscale)); } static void changeslottmus(renderstate &cur, int pass, Slot &slot, VSlot &vslot) { if(pass==RENDERPASS_LIGHTMAP || pass==RENDERPASS_COLOR || pass==RENDERPASS_ENVMAP || pass==RENDERPASS_DYNLIGHT) { GLuint diffusetex = slot.sts.empty() ? notexture->id : slot.sts[0].t->id; if(cur.textures[cur.diffusetmu]!=diffusetex) glBindTexture(GL_TEXTURE_2D, cur.textures[cur.diffusetmu] = diffusetex); } if(renderpath==R_FIXEDFUNCTION) { if(pass==RENDERPASS_LIGHTMAP || pass==RENDERPASS_COLOR) { if(cur.alphaing) { float alpha = cur.alphaing > 1 ? vslot.alphafront : vslot.alphaback; if(cur.colorscale != vslot.colorscale) { changecolor(cur, pass, slot, vslot); if(cur.alphascale != alpha) { cur.alphascale = alpha; cur.color[3] = alpha; } glColor4fv(cur.color); } else if(cur.alphascale != alpha) { cur.alphascale = alpha; cur.color[3] = alpha; glColor4fv(cur.color); } } else if(cur.colorscale != vslot.colorscale) { changecolor(cur, pass, slot, vslot); glColor4fv(cur.color); } vslot.skipped = 0; } else if(pass==RENDERPASS_DYNLIGHT) { if(cur.colorscale != vslot.colorscale) { cur.colorscale = vslot.colorscale; glColor3f(cur.lightcolor.x*vslot.colorscale.x, cur.lightcolor.y*vslot.colorscale.y, cur.lightcolor.z*vslot.colorscale.z); } } if((pass==RENDERPASS_LIGHTMAP || pass==RENDERPASS_ENVMAP) && slot.shader->type&SHADER_ENVMAP && slot.ffenv && hasCM && maxtmus >= 2 && envpass) { if(cur.glowtmu<0) { cur.skipped |= 1< 1 ? vslot.alphafront : vslot.alphaback; if(cur.colorscale != vslot.colorscale || cur.alphascale != alpha) { cur.colorscale = vslot.colorscale; cur.alphascale = alpha; setenvparamf("colorparams", SHPARAM_PIXEL, 6, 2*alpha*vslot.colorscale.x, 2*alpha*vslot.colorscale.y, 2*alpha*vslot.colorscale.z, alpha); GLfloat fogc[4] = { alpha*cur.fogcolor[0], alpha*cur.fogcolor[1], alpha*cur.fogcolor[2], cur.fogcolor[3] }; glFogfv(GL_FOG_COLOR, fogc); } } else if(cur.colorscale != vslot.colorscale) { cur.colorscale = vslot.colorscale; setenvparamf("colorparams", SHPARAM_PIXEL, 6, 2*vslot.colorscale.x, 2*vslot.colorscale.y, 2*vslot.colorscale.z, 1); } int tmu = cur.lightmaptmu+1, envmaptmu = -1; if(slot.shader->type&SHADER_NORMALSLMS) tmu++; if(slot.shader->type&SHADER_ENVMAP) envmaptmu = tmu++; loopvj(slot.sts) { Slot::Tex &t = slot.sts[j]; if(t.type==TEX_DIFFUSE || t.combined>=0) continue; if(t.type==TEX_ENVMAP) { if(envmaptmu>=0 && t.t && cur.textures[envmaptmu]!=t.t->id) { glActiveTexture_(GL_TEXTURE0_ARB+envmaptmu); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, cur.textures[envmaptmu] = t.t->id); } } else { if(cur.textures[tmu]!=t.t->id) { glActiveTexture_(GL_TEXTURE0_ARB+tmu); glBindTexture(GL_TEXTURE_2D, cur.textures[tmu] = t.t->id); } if(++tmu >= 8) break; } } glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); } cur.slot = &slot; cur.vslot = &vslot; } static void changeshader(renderstate &cur, Shader *s, Slot &slot, VSlot &vslot, bool shadowed) { if(glaring) { static Shader *noglareshader = NULL, *noglareblendshader = NULL, *noglarealphashader = NULL; Shader *fallback; if(cur.blending) { if(!noglareblendshader) noglareblendshader = lookupshaderbyname("noglareblendworld"); fallback = noglareblendshader; } else if(cur.alphaing) { if(!noglarealphashader) noglarealphashader = lookupshaderbyname("noglarealphaworld"); fallback = noglarealphashader; } else { if(!noglareshader) noglareshader = lookupshaderbyname("noglareworld"); fallback = noglareshader; } if(s->hasoption(4)) s->setvariant(cur.visibledynlights, 4, slot, vslot, fallback); else s->setvariant(cur.blending ? 1 : 0, 4, slot, vslot, fallback); } else if(fading && !cur.blending && !cur.alphaing) { if(shadowed) s->setvariant(cur.visibledynlights, 3, slot, vslot); else s->setvariant(cur.visibledynlights, 2, slot, vslot); } else if(shadowed) s->setvariant(cur.visibledynlights, 1, slot, vslot); else if(!cur.visibledynlights) s->set(slot, vslot); else s->setvariant(cur.visibledynlights-1, 0, slot, vslot); } static void changetexgen(renderstate &cur, int dim, Slot &slot, VSlot &vslot) { if(cur.texgenslot != &slot || cur.texgenvslot != &vslot) { Texture *curtex = !cur.texgenslot || cur.texgenslot->sts.empty() ? notexture : cur.texgenslot->sts[0].t, *tex = slot.sts.empty() ? notexture : slot.sts[0].t; if(!cur.texgenvslot || slot.sts.empty() || (curtex->xs != tex->xs || curtex->ys != tex->ys || cur.texgenvslot->rotation != vslot.rotation || cur.texgenvslot->scale != vslot.scale || cur.texgenvslot->xoffset != vslot.xoffset || cur.texgenvslot->yoffset != vslot.yoffset || cur.texgenvslot->scrollS != vslot.scrollS || cur.texgenvslot->scrollT != vslot.scrollT)) { float xs = vslot.rotation>=2 && vslot.rotation<=4 ? -tex->xs : tex->xs, ys = (vslot.rotation>=1 && vslot.rotation<=2) || vslot.rotation==5 ? -tex->ys : tex->ys, scrollS = vslot.scrollS, scrollT = vslot.scrollT; if((vslot.rotation&5)==1) swap(scrollS, scrollT); scrollS *= lastmillis*tex->xs/xs; scrollT *= lastmillis*tex->ys/ys; if(cur.texgenscrollS != scrollS || cur.texgenscrollT != scrollT) { cur.texgenscrollS = scrollS; cur.texgenscrollT = scrollT; cur.texgendim = -1; } } cur.texgenslot = &slot; cur.texgenvslot = &vslot; } if(renderpath==R_FIXEDFUNCTION) { bool mtglow = cur.mtglow && !cur.envscale.x; if(cur.texgendim == dim && (cur.mttexgen || !mtglow)) return; glMatrixMode(GL_TEXTURE); if(cur.texgendim!=dim) { glLoadIdentity(); if(dim <= 2) glTranslatef(cur.texgenscrollS, cur.texgenscrollT, 0.0f); } if(mtglow) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glLoadIdentity(); if(dim <= 2) glTranslatef(cur.texgenscrollS, cur.texgenscrollT, 0.0f); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); } cur.mttexgen = mtglow; glMatrixMode(GL_MODELVIEW); } else { if(cur.texgendim == dim) return; setenvparamf("texgenscroll", SHPARAM_VERTEX, 0, cur.texgenscrollS, cur.texgenscrollT); } cur.texgendim = dim; } static void renderbatch(renderstate &cur, int pass, geombatch &b) { geombatch *shadowed = NULL; int rendered = -1; for(geombatch *curbatch = &b;; curbatch = &geombatches[curbatch->batch]) { ushort len = curbatch->es.length[curbatch->va->shadowed ? 0 : 1]; if(len) { if(rendered < 0) { if(renderpath!=R_FIXEDFUNCTION) changeshader(cur, b.vslot.slot->shader, *b.vslot.slot, b.vslot, false); rendered = 0; gbatches++; } ushort minvert = curbatch->es.minvert[0], maxvert = curbatch->es.maxvert[0]; if(!curbatch->va->shadowed) { minvert = min(minvert, curbatch->es.minvert[1]); maxvert = max(maxvert, curbatch->es.maxvert[1]); } drawtris(len, curbatch->edata, minvert, maxvert); vtris += len/3; } if(curbatch->es.length[1] > len && !shadowed) shadowed = curbatch; if(curbatch->batch < 0) break; } if(shadowed) for(geombatch *curbatch = shadowed;; curbatch = &geombatches[curbatch->batch]) { if(curbatch->va->shadowed && curbatch->es.length[1] > curbatch->es.length[0]) { if(rendered < 1) { if(renderpath!=R_FIXEDFUNCTION) changeshader(cur, b.vslot.slot->shader, *b.vslot.slot, b.vslot, true); rendered = 1; gbatches++; } ushort len = curbatch->es.length[1] - curbatch->es.length[0]; drawtris(len, curbatch->edata + curbatch->es.length[0], curbatch->es.minvert[1], curbatch->es.maxvert[1]); vtris += len/3; } if(curbatch->batch < 0) break; } } static void resetbatches() { geombatches.setsize(0); firstbatch = -1; numbatches = 0; } static void renderbatches(renderstate &cur, int pass) { cur.slot = NULL; cur.vslot = NULL; int curbatch = firstbatch; if(curbatch >= 0) { if(cur.alphaing) { if(cur.depthmask) { cur.depthmask = false; glDepthMask(GL_FALSE); } } else if(!cur.depthmask) { cur.depthmask = true; glDepthMask(GL_TRUE); } if(!cur.colormask) { cur.colormask = true; glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, cur.alphaing ? GL_FALSE : GL_TRUE); } } while(curbatch >= 0) { geombatch &b = geombatches[curbatch]; curbatch = b.next; if(cur.vbuf != b.va->vbuf) changevbuf(cur, pass, b.va); if(cur.vslot != &b.vslot) { changeslottmus(cur, pass, *b.vslot.slot, b.vslot); if(cur.texgendim != b.es.dim || (cur.texgendim <= 2 && cur.texgenvslot != &b.vslot) || (!cur.mttexgen && cur.mtglow && !cur.envscale.x)) changetexgen(cur, b.es.dim, *b.vslot.slot, b.vslot); } else if(cur.texgendim != b.es.dim) changetexgen(cur, b.es.dim, *b.vslot.slot, b.vslot); if(pass == RENDERPASS_LIGHTMAP) changebatchtmus(cur, pass, b); else if(pass == RENDERPASS_ENVMAP) changeenv(cur, pass, *b.vslot.slot, b.vslot, &b); renderbatch(cur, pass, b); } if(pass == RENDERPASS_LIGHTMAP && cur.mtglow) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glDisable(cur.envscale.x ? GL_TEXTURE_CUBE_MAP_ARB : GL_TEXTURE_2D); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); cur.mtglow = false; } resetbatches(); } void renderzpass(renderstate &cur, vtxarray *va) { if(cur.vbuf!=va->vbuf) changevbuf(cur, RENDERPASS_Z, va); if(!cur.depthmask) { cur.depthmask = true; glDepthMask(GL_TRUE); } if(cur.colormask) { cur.colormask = false; glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); } extern int apple_glsldepth_bug; int firsttex = 0, numtexs = va->texs, numtris = va->tris; ushort *edata = va->edata; if(cur.alphaing) { firsttex += va->texs + va->blends; edata += 3*(va->tris + va->blendtris); numtexs = va->alphaback + va->alphafront; numtris = va->alphabacktris + va->alphafronttris; xtravertsva += 3*numtris; } else xtravertsva += va->verts; if(renderpath!=R_ASMGLSLANG || !apple_glsldepth_bug) { nocolorshader->set(); drawvatris(va, 3*numtris, edata); } else { int lastflags = 0, lastdraw = 0, offset = 0; for(int i = firsttex; i < firsttex + numtexs; i++) { int flags = lookupvslot(va->eslist[i].texture).slot->shader->type&SHADER_GLSLANG; if(flags != lastflags && offset > lastdraw) { (lastflags ? nocolorglslshader : nocolorshader)->set(); drawvatris(va, offset-lastdraw, edata+lastdraw); lastdraw = offset; } lastflags = flags; offset += va->eslist[i].length[1]; } if(offset > lastdraw) { (lastflags ? nocolorglslshader : nocolorshader)->set(); drawvatris(va, offset-lastdraw, va->edata+lastdraw); } } } vector foggedvas; #define startvaquery(va, flush) \ do { \ if(va->query) \ { \ flush; \ startquery(va->query); \ } \ } while(0) #define endvaquery(va, flush) \ do { \ if(va->query) \ { \ flush; \ endquery(va->query); \ } \ } while(0) void renderfoggedvas(renderstate &cur, bool doquery = false) { static Shader *fogshader = NULL; if(!fogshader) fogshader = lookupshaderbyname("fogworld"); if(fading) fogshader->setvariant(0, 2); else fogshader->set(); glDisable(GL_TEXTURE_2D); glColor3ubv(fogging ? refractcolor.v : fogcolor.v); loopv(foggedvas) { vtxarray *va = foggedvas[i]; if(cur.vbuf!=va->vbuf) changevbuf(cur, RENDERPASS_FOG, va); if(doquery) startvaquery(va, ); drawvatris(va, 3*va->tris, va->edata); vtris += va->tris; if(doquery) endvaquery(va, ); } glEnable(GL_TEXTURE_2D); foggedvas.setsize(0); } void rendershadowmappass(renderstate &cur, vtxarray *va) { if(cur.vbuf!=va->vbuf) changevbuf(cur, RENDERPASS_SHADOWMAP, va); elementset *texs = va->eslist; ushort *edata = va->edata; loopi(va->texs) { elementset &es = texs[i]; int len = es.length[1] - es.length[0]; if(len > 0) { drawtris(len, &edata[es.length[0]], es.minvert[1], es.maxvert[1]); vtris += len/3; } edata += es.length[1]; } } VAR(batchgeom, 0, 1, 1); void renderva(renderstate &cur, vtxarray *va, int pass = RENDERPASS_LIGHTMAP, bool fogpass = false, bool doquery = false) { switch(pass) { case RENDERPASS_GLOW: if(!(va->texmask&(1<texmask&(1<verts; va->shadowed = false; va->dynlightmask = 0; if(fogpass ? va->geommax.z<=reflectz-refractfog || !refractfog : va->curvfc==VFC_FOGGED) { if(!cur.alphaing && !cur.blending) foggedvas.add(va); break; } if(renderpath!=R_FIXEDFUNCTION && !envmapping && !glaring && !cur.alphaing) { va->shadowed = isshadowmapreceiver(va); calcdynlightmask(va); } if(doquery) startvaquery(va, { if(geombatches.length()) renderbatches(cur, pass); }); mergetexs(cur, va); if(doquery) endvaquery(va, { if(geombatches.length()) renderbatches(cur, pass); }); else if(!batchgeom && geombatches.length()) renderbatches(cur, pass); break; case RENDERPASS_LIGHTMAP_BLEND: { if(doquery) startvaquery(va, { if(geombatches.length()) renderbatches(cur, RENDERPASS_LIGHTMAP); }); mergetexs(cur, va, &va->eslist[va->texs], va->blends, va->edata + 3*va->tris); if(doquery) endvaquery(va, { if(geombatches.length()) renderbatches(cur, RENDERPASS_LIGHTMAP); }); else if(!batchgeom && geombatches.length()) renderbatches(cur, RENDERPASS_LIGHTMAP); break; } case RENDERPASS_DYNLIGHT: if(cur.dynlightpos.dist_to_bb(va->geommin, va->geommax) >= cur.dynlightradius) break; vverts += va->verts; mergetexs(cur, va); if(!batchgeom && geombatches.length()) renderbatches(cur, pass); break; case RENDERPASS_FOG: if(cur.vbuf!=va->vbuf) changevbuf(cur, pass, va); drawvatris(va, 3*va->tris, va->edata); xtravertsva += va->verts; break; case RENDERPASS_SHADOWMAP: if(isshadowmapreceiver(va)) rendershadowmappass(cur, va); break; case RENDERPASS_CAUSTICS: if(cur.vbuf!=va->vbuf) changevbuf(cur, pass, va); drawvatris(va, 3*va->tris, va->edata); xtravertsva += va->verts; break; case RENDERPASS_Z: if(doquery) startvaquery(va, ); renderzpass(cur, va); if(doquery) endvaquery(va, ); break; } } GLuint attenxytex = 0, attenztex = 0; static GLuint createattenxytex(int size) { uchar *data = new uchar[size*size], *dst = data; loop(y, size) loop(x, size) { float dx = 2*float(x)/(size-1) - 1, dy = 2*float(y)/(size-1) - 1; float atten = max(0.0f, 1.0f - dx*dx - dy*dy); *dst++ = uchar(atten*255); } GLuint tex = 0; glGenTextures(1, &tex); createtexture(tex, size, size, data, 3, 1, GL_ALPHA); delete[] data; return tex; } static GLuint createattenztex(int size) { uchar *data = new uchar[size], *dst = data; loop(z, size) { float dz = 2*float(z)/(size-1) - 1; float atten = dz*dz; *dst++ = uchar(atten*255); } GLuint tex = 0; glGenTextures(1, &tex); createtexture(tex, size, 1, data, 3, 1, GL_ALPHA, GL_TEXTURE_1D); delete[] data; return tex; } #define NUMCAUSTICS 32 static Texture *caustictex[NUMCAUSTICS] = { NULL }; void loadcaustics(bool force) { static bool needcaustics = false; if(force) needcaustics = true; if(!caustics || !needcaustics) return; useshaderbyname("caustic"); if(caustictex[0]) return; loopi(NUMCAUSTICS) { defformatstring(name)( renderpath==R_FIXEDFUNCTION ? "packages/caustics/caust%.2d.png" : "packages/caustics/caust%.2d.png", i); caustictex[i] = textureload(name); } } void cleanupva() { clearvas(worldroot); clearqueries(); if(attenxytex) { glDeleteTextures(1, &attenxytex); attenxytex = 0; } if(attenztex) { glDeleteTextures(1, &attenztex); attenztex = 0; } loopi(NUMCAUSTICS) caustictex[i] = NULL; } VARR(causticscale, 0, 50, 10000); VARR(causticmillis, 0, 75, 1000); VARFP(caustics, 0, 1, 1, loadcaustics()); void setupcaustics(int tmu, float blend, GLfloat *color = NULL) { if(!caustictex[0]) loadcaustics(true); GLfloat s[4] = { 0.011f, 0, 0.0066f, 0 }; GLfloat t[4] = { 0, 0.011f, 0.0066f, 0 }; loopk(3) { s[k] *= 100.0f/causticscale; t[k] *= 100.0f/causticscale; } int tex = (lastmillis/causticmillis)%NUMCAUSTICS; float frac = float(lastmillis%causticmillis)/causticmillis; if(color) color[3] = frac; else glColor4f(1, 1, 1, frac); loopi(2) { glActiveTexture_(GL_TEXTURE0_ARB+tmu+i); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, caustictex[(tex+i)%NUMCAUSTICS]->id); if(renderpath==R_FIXEDFUNCTION) { setuptexgen(); if(color) setuptmu(tmu+i, !i ? "$1 , $0 @ Ca" : "= P"); else setuptmu(tmu+i, !i ? "= T" : "T , P @ Ca"); glTexGenfv(GL_S, GL_OBJECT_PLANE, s); glTexGenfv(GL_T, GL_OBJECT_PLANE, t); } } if(renderpath!=R_FIXEDFUNCTION) { SETSHADER(caustic); setlocalparamfv("texgenS", SHPARAM_VERTEX, 0, s); setlocalparamfv("texgenT", SHPARAM_VERTEX, 1, t); setlocalparamf("frameoffset", SHPARAM_PIXEL, 0, blend*(1-frac), blend*frac, blend); } } void setupTMUs(renderstate &cur, float causticspass, bool fogpass) { if(renderpath==R_FIXEDFUNCTION) { if(nolights) cur.lightmaptmu = -1; else if(maxtmus>=3) { if(maxtmus>=4 && (hasTEX || hasTE4) && causticspass>=1) { cur.causticstmu = 0; cur.diffusetmu = 2; cur.lightmaptmu = 3; if(maxtmus>=5 && glowpass && !cur.alphaing) cur.glowtmu = 4; } else if(glowpass && !cur.alphaing) cur.glowtmu = 2; } if(cur.glowtmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); setuptmu(cur.glowtmu, "P + T", "= Pa"); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } if(cur.causticstmu>=0) setupcaustics(cur.causticstmu, causticspass, cur.color); } else { // need to invalidate vertex params in case they were used somewhere else for streaming params invalidateenvparams(SHPARAM_VERTEX, 10, RESERVEDSHADERPARAMS + MAXSHADERPARAMS - 10); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_COLOR_ARRAY); loopi(8-2) { glActiveTexture_(GL_TEXTURE2_ARB+i); glEnable(GL_TEXTURE_2D); } glActiveTexture_(GL_TEXTURE0_ARB); setenvparamf("colorparams", SHPARAM_PIXEL, 6, 2, 2, 2, 1); setenvparamf("camera", SHPARAM_VERTEX, 4, camera1->o.x, camera1->o.y, camera1->o.z, 1); setenvparamf("ambient", SHPARAM_PIXEL, 5, ambientcolor.x/255.0f, ambientcolor.y/255.0f, ambientcolor.z/255.0f); setenvparamf("millis", SHPARAM_VERTEX, 6, lastmillis/1000.0f, lastmillis/1000.0f, lastmillis/1000.0f); } glColor4fv(cur.color); if(cur.lightmaptmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); setuptmu(cur.lightmaptmu, "P * T x 2", "= Pa"); glEnable(GL_TEXTURE_2D); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); glEnable(GL_TEXTURE_2D); setuptmu(cur.diffusetmu, cur.diffusetmu>0 ? "P * T" : "= T", cur.alphaing ? "= Ca" : (cur.diffusetmu>0 ? "= Ta" : "Ca * Ta")); } // diffusetmu glEnableClientState(GL_TEXTURE_COORD_ARRAY); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } void cleanupTMUs(renderstate &cur, float causticspass, bool fogpass) { if(cur.lightmaptmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); resettmu(cur.lightmaptmu); glDisable(GL_TEXTURE_2D); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } if(cur.glowtmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.glowtmu); resettmu(cur.glowtmu); if(cur.envscale.x) disableenv(cur); else disableglow(cur); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } if(cur.causticstmu>=0) loopi(2) { glActiveTexture_(GL_TEXTURE0_ARB+cur.causticstmu+i); resettmu(cur.causticstmu+i); disabletexgen(); glDisable(GL_TEXTURE_2D); } if(cur.lightmaptmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); glClientActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); resettmu(cur.diffusetmu); glDisable(GL_TEXTURE_2D); } glDisableClientState(GL_TEXTURE_COORD_ARRAY); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); if(renderpath!=R_FIXEDFUNCTION) { glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_COLOR_ARRAY); loopi(8-2) { glActiveTexture_(GL_TEXTURE2_ARB+i); glDisable(GL_TEXTURE_2D); } } if(cur.lightmaptmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB); glClientActiveTexture_(GL_TEXTURE0_ARB); glEnable(GL_TEXTURE_2D); } } #define FIRSTVA (reflecting ? reflectedva : visibleva) #define NEXTVA (reflecting ? va->rnext : va->next) static void rendergeommultipass(renderstate &cur, int pass, bool fogpass) { cur.vbuf = 0; cur.texgendim = -1; for(vtxarray *va = FIRSTVA; va; va = NEXTVA) { if(!va->texs) continue; if(refracting) { if((refracting < 0 ? va->geommin.z > reflectz : va->geommax.z <= reflectz) || va->occluded >= OCCLUDE_GEOM) continue; if(ishiddencube(va->o, va->size)) continue; } else if(reflecting) { if(va->geommax.z <= reflectz) continue; } else if(va->occluded >= OCCLUDE_GEOM) continue; if(fogpass ? va->geommax.z <= reflectz-refractfog || !refractfog : va->curvfc==VFC_FOGGED) continue; renderva(cur, va, pass, fogpass); } if(geombatches.length()) renderbatches(cur, pass); } VAR(oqgeom, 0, 1, 1); VAR(dbgffsm, 0, 0, 1); VAR(dbgffdl, 0, 0, 1); VAR(ffdlscissor, 0, 1, 1); static void setupenvpass(renderstate &cur) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1, 1, 1, 1); cur.envscale = vec(-1, -1, -1); cur.glowtmu = 0; setuptmu(0, "= T", "= Ca"); glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_CUBE_MAP_ARB); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glEnable(GL_TEXTURE_GEN_R); glMatrixMode(GL_TEXTURE); glLoadMatrixf(envmatrix.v); glMatrixMode(GL_MODELVIEW); glEnableClientState(GL_NORMAL_ARRAY); glActiveTexture_(GL_TEXTURE1_ARB); glClientActiveTexture_(GL_TEXTURE1_ARB); cur.specmask = false; cur.diffusetmu = 1; setuptmu(1, "= P", "Pa * Ta"); glEnableClientState(GL_TEXTURE_COORD_ARRAY); } static void cleanuptexgen(renderstate &cur) { if(cur.texgendim >= 0 && cur.texgendim <= 2) { glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } } static void cleanupenvpass(renderstate &cur) { glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_TEXTURE_2D); resettmu(1); cleanuptexgen(cur); glActiveTexture_(GL_TEXTURE0_ARB); glClientActiveTexture_(GL_TEXTURE0_ARB); resettmu(0); glDisableClientState(GL_NORMAL_ARRAY); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_R); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glDisable(GL_TEXTURE_CUBE_MAP_ARB); glEnable(GL_TEXTURE_2D); } void rendergeom(float causticspass, bool fogpass) { if(causticspass && ((renderpath==R_FIXEDFUNCTION && maxtmus<2) || !causticscale || !causticmillis)) causticspass = 0; bool mainpass = !reflecting && !refracting && !envmapping && !glaring, doOQ = hasOQ && oqfrags && oqgeom && mainpass, doZP = doOQ && zpass, doSM = shadowmap && !envmapping && !glaring && renderpath!=R_FIXEDFUNCTION; renderstate cur; if(mainpass) { flipqueries(); vtris = vverts = 0; } if(!doZP) { if(shadowmap && hasFBO && mainpass) rendershadowmap(); setupTMUs(cur, causticspass, fogpass); if(doSM) pushshadowmap(); } int hasdynlights = finddynlights(); resetbatches(); glEnableClientState(GL_VERTEX_ARRAY); int blends = 0; for(vtxarray *va = FIRSTVA; va; va = NEXTVA) { if(!va->texs) continue; if(refracting) { if((refracting < 0 ? va->geommin.z > reflectz : va->geommax.z <= reflectz) || va->occluded >= OCCLUDE_GEOM) continue; if(ishiddencube(va->o, va->size)) continue; } else if(reflecting) { if(va->geommax.z <= reflectz) continue; } else if(doOQ && (zpass || va->distance > oqdist) && !insideva(va, camera1->o)) { if(va->parent && va->parent->occluded >= OCCLUDE_BB) { va->query = NULL; va->occluded = OCCLUDE_PARENT; continue; } va->occluded = va->query && va->query->owner == va && checkquery(va->query) ? min(va->occluded+1, int(OCCLUDE_BB)) : OCCLUDE_NOTHING; va->query = newquery(va); if((!va->query && zpass) || !va->occluded) va->occluded = pvsoccluded(va->geommin, va->geommax) ? OCCLUDE_GEOM : OCCLUDE_NOTHING; if(va->occluded >= OCCLUDE_GEOM) { if(va->query) { if(!zpass && geombatches.length()) renderbatches(cur, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP); renderquery(cur, va->query, va); } continue; } } else { va->query = NULL; va->occluded = pvsoccluded(va->geommin, va->geommax) ? OCCLUDE_GEOM : OCCLUDE_NOTHING; if(va->occluded >= OCCLUDE_GEOM) continue; } if(!doZP) blends += va->blends; renderva(cur, va, doZP ? RENDERPASS_Z : (nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP), fogpass, doOQ); } if(geombatches.length()) renderbatches(cur, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP); if(!cur.colormask) { cur.colormask = true; glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); } if(!cur.depthmask) { cur.depthmask = true; glDepthMask(GL_TRUE); } bool multipassing = false; if(doZP) { glFlush(); if(shadowmap && hasFBO && mainpass) { glDisableClientState(GL_VERTEX_ARRAY); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } rendershadowmap(); glEnableClientState(GL_VERTEX_ARRAY); } setupTMUs(cur, causticspass, fogpass); if(doSM) pushshadowmap(); if(!multipassing) { multipassing = true; glDepthFunc(GL_LEQUAL); } cur.vbuf = 0; cur.texgendim = -1; for(vtxarray *va = visibleva; va; va = va->next) { if(!va->texs || va->occluded >= OCCLUDE_GEOM) continue; blends += va->blends; renderva(cur, va, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP, fogpass); } if(geombatches.length()) renderbatches(cur, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP); for(vtxarray *va = visibleva; va; va = va->next) { if(!va->texs || va->occluded < OCCLUDE_GEOM) continue; else if((va->parent && va->parent->occluded >= OCCLUDE_BB) || (va->query && checkquery(va->query))) { va->occluded = OCCLUDE_BB; continue; } else { va->occluded = pvsoccluded(va->geommin, va->geommax) ? OCCLUDE_GEOM : OCCLUDE_NOTHING; if(va->occluded >= OCCLUDE_GEOM) continue; } blends += va->blends; renderva(cur, va, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP, fogpass); } if(geombatches.length()) renderbatches(cur, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP); } if(blends && (renderpath!=R_FIXEDFUNCTION || !nolights)) { if(!multipassing) { multipassing = true; glDepthFunc(GL_LEQUAL); } glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); cur.vbuf = 0; cur.texgendim = -1; cur.blending = true; if(cur.lightmaptmu>=0) { glActiveTexture_(GL_TEXTURE0_ARB+cur.lightmaptmu); setuptmu(cur.lightmaptmu, "P * T x 2", "= Ta"); glActiveTexture_(GL_TEXTURE0_ARB+cur.diffusetmu); } for(vtxarray *va = FIRSTVA; va; va = NEXTVA) { if(!va->blends) continue; if(refracting) { if(refracting < 0 ? va->geommin.z > reflectz : va->geommax.z <= reflectz) continue; if(ishiddencube(va->o, va->size)) continue; if(va->occluded >= OCCLUDE_GEOM) continue; } else if(reflecting) { if(va->geommax.z <= reflectz) continue; } else if(va->occluded >= OCCLUDE_GEOM) continue; if(fogpass ? va->geommax.z <= reflectz-refractfog || !refractfog : va->curvfc==VFC_FOGGED) continue; renderva(cur, va, RENDERPASS_LIGHTMAP_BLEND, fogpass); } if(geombatches.length()) renderbatches(cur, RENDERPASS_LIGHTMAP); cur.blending = false; glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glDisable(GL_BLEND); glDepthMask(GL_TRUE); } if(doSM) popshadowmap(); cleanupTMUs(cur, causticspass, fogpass); if(foggedvas.length()) renderfoggedvas(cur, doOQ && !zpass); if(renderpath==R_FIXEDFUNCTION ? (glowpass && cur.skipped) || (causticspass>=1 && cur.causticstmu<0) || (shadowmap && shadowmapcasters) || hasdynlights : causticspass) { if(!multipassing) { multipassing = true; glDepthFunc(GL_LEQUAL); } glDepthMask(GL_FALSE); glEnable(GL_BLEND); if(renderpath==R_FIXEDFUNCTION && glowpass && cur.skipped&(1<=1 && cur.causticstmu<0 : causticspass) { setupcaustics(0, causticspass); glBlendFunc(GL_ZERO, renderpath==R_FIXEDFUNCTION ? GL_SRC_COLOR : GL_ONE_MINUS_SRC_COLOR); glFogfv(GL_FOG_COLOR, renderpath==R_FIXEDFUNCTION ? onefog : zerofog); if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); rendergeommultipass(cur, RENDERPASS_CAUSTICS, fogpass); if(fading) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); loopi(2) { glActiveTexture_(GL_TEXTURE0_ARB+i); resettmu(i); if(renderpath==R_FIXEDFUNCTION || !i) { resettmu(i); disabletexgen(); } if(i) glDisable(GL_TEXTURE_2D); } glActiveTexture_(GL_TEXTURE0_ARB); } if(renderpath==R_FIXEDFUNCTION && shadowmap && shadowmapcasters) { glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR); glFogfv(GL_FOG_COLOR, zerofog); pushshadowmap(); if(dbgffsm) { glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); glColor3f(1, 0, 1); } rendergeommultipass(cur, RENDERPASS_SHADOWMAP, fogpass); if(dbgffsm) { glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); } popshadowmap(); } if(renderpath==R_FIXEDFUNCTION && hasdynlights) { glBlendFunc(GL_SRC_ALPHA, dbgffdl ? GL_ZERO : GL_ONE); glFogfv(GL_FOG_COLOR, zerofog); if(!attenxytex) attenxytex = createattenxytex(64); glBindTexture(GL_TEXTURE_2D, attenxytex); setuptmu(0, "= C", "= Ta"); setuptexgen(); glActiveTexture_(GL_TEXTURE1_ARB); setuptmu(1, "= P", "Pa - Ta"); setuptexgen(1); if(!attenztex) attenztex = createattenztex(64); glBindTexture(GL_TEXTURE_1D, attenztex); glEnable(GL_TEXTURE_1D); glActiveTexture_(GL_TEXTURE2_ARB); glClientActiveTexture_(GL_TEXTURE2_ARB); cur.diffusetmu = 2; setuptmu(2, "P * T x 4", "= Pa"); glEnable(GL_TEXTURE_2D); glEnableClientState(GL_TEXTURE_COORD_ARRAY); for(int n = 0; getdynlight(n, cur.dynlightpos, cur.dynlightradius, cur.lightcolor); n++) { cur.lightcolor.mul(0.5f); cur.colorscale = vec(1, 1, 1); glColor3f(cur.lightcolor.x, cur.lightcolor.y, cur.lightcolor.z); if(ffdlscissor) { float sx1, sy1, sx2, sy2; calcspherescissor(cur.dynlightpos, cur.dynlightradius, sx1, sy1, sx2, sy2); pushscissor(sx1, sy1, sx2, sy2); } changedynlightpos(cur); rendergeommultipass(cur, RENDERPASS_DYNLIGHT, fogpass); if(ffdlscissor) popscissor(); } glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_TEXTURE_2D); resettmu(2); cleanuptexgen(cur); glActiveTexture_(GL_TEXTURE1_ARB); glDisable(GL_TEXTURE_1D); resettmu(1); disabletexgen(1); glActiveTexture_(GL_TEXTURE0_ARB); glClientActiveTexture_(GL_TEXTURE0_ARB); resettmu(0); disabletexgen(); } glFogfv(GL_FOG_COLOR, cur.fogcolor); glDisable(GL_BLEND); glDepthMask(GL_TRUE); } if(multipassing) glDepthFunc(GL_LESS); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); } void renderalphageom(bool fogpass) { static vector alphavas; alphavas.setsize(0); bool hasback = false; for(vtxarray *va = FIRSTVA; va; va = NEXTVA) { if(!va->alphabacktris && !va->alphafronttris) continue; if(refracting) { if((refracting < 0 ? va->geommin.z > reflectz : va->geommax.z <= reflectz) || va->occluded >= OCCLUDE_BB) continue; if(ishiddencube(va->o, va->size)) continue; if(va->occluded >= OCCLUDE_GEOM && pvsoccluded(va->geommin, va->geommax)) continue; } else if(reflecting) { if(va->geommax.z <= reflectz) continue; } else { if(va->occluded >= OCCLUDE_BB) continue; if(va->occluded >= OCCLUDE_GEOM && pvsoccluded(va->geommin, va->geommax)) continue; } if(fogpass ? va->geommax.z <= reflectz-refractfog || !refractfog : va->curvfc==VFC_FOGGED) continue; alphavas.add(va); if(va->alphabacktris) hasback = true; } if(alphavas.empty()) return; resetbatches(); renderstate cur; cur.alphaing = 1; glEnableClientState(GL_VERTEX_ARRAY); glGetFloatv(GL_FOG_COLOR, cur.fogcolor); loop(front, 2) if(front || hasback) { cur.alphaing = front+1; if(!front) glCullFace(GL_FRONT); cur.vbuf = 0; cur.texgendim = -1; loopv(alphavas) renderva(cur, alphavas[i], RENDERPASS_Z); if(cur.depthmask) { cur.depthmask = false; glDepthMask(GL_FALSE); } cur.colormask = true; glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); setupTMUs(cur, 0, fogpass); glDepthFunc(GL_LEQUAL); glEnable(GL_BLEND); if(renderpath==R_FIXEDFUNCTION) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); else glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); cur.vbuf = 0; cur.texgendim = -1; cur.skipped = 0; cur.colorscale = vec(1, 1, 1); loopk(3) cur.color[k] = 1; cur.alphascale = -1; loopv(alphavas) if(front || alphavas[i]->alphabacktris) renderva(cur, alphavas[i], RENDERPASS_LIGHTMAP, fogpass); if(geombatches.length()) renderbatches(cur, nolights ? RENDERPASS_COLOR : RENDERPASS_LIGHTMAP); cleanupTMUs(cur, 0, fogpass); if(renderpath==R_FIXEDFUNCTION && glowpass && cur.skipped) { if(cur.depthmask) { cur.depthmask = false; glDepthMask(GL_FALSE); } if(cur.skipped&(1<alphabacktris) renderva(cur, alphavas[i], RENDERPASS_ENVMAP, fogpass); if(geombatches.length()) renderbatches(cur, RENDERPASS_ENVMAP); cleanupenvpass(cur); } if(cur.skipped&(1<alphabacktris) renderva(cur, alphavas[i], RENDERPASS_GLOW, fogpass); if(geombatches.length()) renderbatches(cur, RENDERPASS_GLOW); cleanuptexgen(cur); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glFogfv(GL_FOG_COLOR, cur.fogcolor); } if(!front) { cur.diffusetmu = 0; cur.lightmaptmu = 1; cur.glowtmu = -1; setupTMUs(cur, 0, fogpass); } } else if(renderpath!=R_FIXEDFUNCTION) { glFogfv(GL_FOG_COLOR, cur.fogcolor); } if(!cur.depthmask) { cur.depthmask = true; glDepthMask(GL_TRUE); } glDisable(GL_BLEND); glDepthFunc(GL_LESS); if(!front) glCullFace(GL_BACK); } glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, fading ? GL_FALSE : GL_TRUE); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } glDisableClientState(GL_VERTEX_ARRAY); } void findreflectedvas(vector &vas, int prevvfc = VFC_PART_VISIBLE) { loopv(vas) { vtxarray *va = vas[i]; if(prevvfc >= VFC_NOT_VISIBLE) va->curvfc = prevvfc; if(va->curvfc == VFC_FOGGED || va->curvfc == PVS_FOGGED || va->o.z+va->size <= reflectz || isfoggedcube(va->o, va->size)) continue; bool render = true; if(va->curvfc == VFC_FULL_VISIBLE) { if(va->occluded >= OCCLUDE_BB) continue; if(va->occluded >= OCCLUDE_GEOM) render = false; } else if(va->curvfc == PVS_FULL_VISIBLE) continue; if(render) { if(va->curvfc >= VFC_NOT_VISIBLE) va->distance = (int)vadist(va, camera1->o); vtxarray **vprev = &reflectedva, *vcur = reflectedva; while(vcur && va->distance > vcur->distance) { vprev = &vcur->rnext; vcur = vcur->rnext; } va->rnext = *vprev; *vprev = va; } if(va->children.length()) findreflectedvas(va->children, va->curvfc); } } void renderreflectedgeom(bool causticspass, bool fogpass) { if(reflecting) { reflectedva = NULL; findreflectedvas(varoot); rendergeom(causticspass ? 1 : 0, fogpass); } else rendergeom(causticspass ? 1 : 0, fogpass); } static vtxarray *prevskyva = NULL; void renderskyva(vtxarray *va, bool explicitonly = false) { if(!prevskyva || va->vbuf != prevskyva->vbuf) { if(!prevskyva) glEnableClientState(GL_VERTEX_ARRAY); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, va->vbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, va->skybuf); } glVertexPointer(3, GL_FLOAT, VTXSIZE, va->vdata[0].pos.v); } drawvatris(va, explicitonly ? va->explicitsky : va->sky+va->explicitsky, explicitonly ? va->skydata+va->sky : va->skydata); if(!explicitonly) xtraverts += va->sky/3; xtraverts += va->explicitsky/3; prevskyva = va; } int renderedsky = 0, renderedexplicitsky = 0, renderedskyfaces = 0, renderedskyclip = INT_MAX; static inline void updateskystats(vtxarray *va) { renderedsky += va->sky; renderedexplicitsky += va->explicitsky; renderedskyfaces |= va->skyfaces&0x3F; if(!(va->skyfaces&0x1F) || camera1->o.z < va->skyclip) renderedskyclip = min(renderedskyclip, va->skyclip); else renderedskyclip = 0; } void renderreflectedskyvas(vector &vas, int prevvfc = VFC_PART_VISIBLE) { loopv(vas) { vtxarray *va = vas[i]; if(prevvfc >= VFC_NOT_VISIBLE) va->curvfc = prevvfc; if((va->curvfc == VFC_FULL_VISIBLE && va->occluded >= OCCLUDE_BB) || va->curvfc==PVS_FULL_VISIBLE) continue; if(va->o.z+va->size <= reflectz || ishiddencube(va->o, va->size)) continue; if(va->sky+va->explicitsky) { updateskystats(va); renderskyva(va); } if(va->children.length()) renderreflectedskyvas(va->children, va->curvfc); } } bool rendersky(bool explicitonly) { prevskyva = NULL; renderedsky = renderedexplicitsky = renderedskyfaces = 0; renderedskyclip = INT_MAX; if(reflecting) { renderreflectedskyvas(varoot); } else for(vtxarray *va = visibleva; va; va = va->next) { if((va->occluded >= OCCLUDE_BB && va->skyfaces&0x80) || !(va->sky+va->explicitsky)) continue; // count possibly visible sky even if not actually rendered updateskystats(va); if(explicitonly && !va->explicitsky) continue; renderskyva(va, explicitonly); } if(prevskyva) { glDisableClientState(GL_VERTEX_ARRAY); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } } return renderedsky+renderedexplicitsky > 0; } sauerbraten-0.0.20130203.dfsg/engine/shader.cpp0000644000175000017500000024323212055646311020625 0ustar vincentvincent// shader.cpp: OpenGL assembly/GLSL shader management #include "engine.h" struct GlobalShaderParamState : ShaderParamState { uint version; GlobalShaderParamState() : version(0) {} }; Shader *Shader::lastshader = NULL; Shader *defaultshader = NULL, *rectshader = NULL, *cubemapshader = NULL, *notextureshader = NULL, *nocolorshader = NULL, *nocolorglslshader = NULL, *foggedshader = NULL, *foggednotextureshader = NULL, *stdworldshader = NULL, *lineshader = NULL, *foggedlineshader = NULL; static hashtable shaders; static Shader *curshader = NULL; static vector curparams; static GlobalShaderParamState vertexparamstate[RESERVEDSHADERPARAMS + MAXSHADERPARAMS], pixelparamstate[RESERVEDSHADERPARAMS + MAXSHADERPARAMS]; static bool dirtyenvparams = false, standardshader = false, forceshaders = true; static uint paramversion = 0; VAR(reservevpparams, 1, 16, 0); VAR(maxvpenvparams, 1, 0, 0); VAR(maxvplocalparams, 1, 0, 0); VAR(maxfpenvparams, 1, 0, 0); VAR(maxfplocalparams, 1, 0, 0); VAR(maxtexcoords, 1, 0, 0); VAR(maxvsuniforms, 1, 0, 0); VAR(maxfsuniforms, 1, 0, 0); VAR(maxvaryings, 1, 0, 0); VAR(dbgshader, 0, 0, 2); void loadshaders() { standardshader = true; execfile(renderpath==R_GLSLANG ? "data/glsl.cfg" : "data/stdshader.cfg"); standardshader = false; defaultshader = lookupshaderbyname("default"); stdworldshader = lookupshaderbyname("stdworld"); if(!defaultshader || !stdworldshader) fatal("cannot find shader definitions"); extern Slot dummyslot; dummyslot.shader = stdworldshader; extern int ati_line_bug; rectshader = lookupshaderbyname("rect"); cubemapshader = lookupshaderbyname("cubemap"); notextureshader = lookupshaderbyname("notexture"); nocolorshader = lookupshaderbyname("nocolor"); nocolorglslshader = lookupshaderbyname("nocolorglsl"); foggedshader = lookupshaderbyname("fogged"); foggednotextureshader = lookupshaderbyname("foggednotexture"); lineshader = lookupshaderbyname(ati_line_bug && renderpath == R_ASMGLSLANG ? "notextureglsl" : "notexture"); foggedlineshader = lookupshaderbyname(ati_line_bug && renderpath == R_ASMGLSLANG ? "foggednotextureglsl" : "foggednotexture"); defaultshader->set(); } Shader *lookupshaderbyname(const char *name) { Shader *s = shaders.access(name); return s && s->detailshader ? s : NULL; } static bool compileasmshader(GLenum type, GLuint &idx, const char *def, const char *tname, const char *name, bool msg = true, bool nativeonly = false) { glGenProgramsARB_(1, &idx); glBindProgramARB_(type, idx); def += strspn(def, " \t\r\n"); glProgramStringARB_(type, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)strlen(def), def); GLint err = -1, native = 1; glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &err); extern int apple_vp_bug; if(type!=GL_VERTEX_PROGRAM_ARB || !apple_vp_bug) glGetProgramivARB_(type, GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB, &native); if(msg && err!=-1) { conoutf(CON_ERROR, "COMPILE ERROR (%s:%s) - %s", tname, name, glGetString(GL_PROGRAM_ERROR_STRING_ARB)); if(err>=0 && err<(int)strlen(def)) { FILE *l = getlogfile(); if(l) { fwrite(def, 1, err, l); def += err; fputs(" <> \n", l); fputs(def, l); } } } else if(msg && !native) conoutf(CON_ERROR, "%s:%s EXCEEDED NATIVE LIMITS", tname, name); glBindProgramARB_(type, 0); if(err!=-1 || (!native && nativeonly)) { glDeleteProgramsARB_(1, &idx); idx = 0; } return native!=0; } static void showglslinfo(GLenum type, GLuint obj, const char *name, const char *source) { GLint length = 0; if(type) glGetShaderiv_(obj, GL_INFO_LOG_LENGTH, &length); else glGetProgramiv_(obj, GL_INFO_LOG_LENGTH, &length); if(length > 1) { conoutf(CON_ERROR, "GLSL ERROR (%s:%s)", type == GL_VERTEX_SHADER ? "VS" : (type == GL_FRAGMENT_SHADER ? "FS" : "PROG"), name); FILE *l = getlogfile(); if(l) { GLchar *log = new GLchar[length]; if(type) glGetShaderInfoLog_(obj, length, &length, log); else glGetProgramInfoLog_(obj, length, &length, log); fprintf(l, "%s\n", log); if(source) loopi(1000) { const char *next = strchr(source, '\n'); fprintf(l, "%d: ", i+1); fwrite(source, 1, next ? next - source + 1 : strlen(source), l); if(!next) { fputc('\n', l); break; } source = next + 1; } delete[] log; } } } static void compileglslshader(GLenum type, GLuint &obj, const char *def, const char *name, bool msg = true) { const GLchar *source = (const GLchar *)(def + strspn(def, " \t\r\n")); obj = glCreateShader_(type); glShaderSource_(obj, 1, &source, NULL); glCompileShader_(obj); GLint success; glGetShaderiv_(obj, GL_COMPILE_STATUS, &success); if(!success) { if(msg) showglslinfo(type, obj, name, source); glDeleteShader_(obj); obj = 0; } else if(dbgshader > 1 && msg) showglslinfo(type, obj, name, source); } VAR(dbgubo, 0, 0, 1); static void bindglsluniform(Shader &s, UniformLoc &u) { u.loc = glGetUniformLocation_(s.program, u.name); if(!u.blockname) return; if(hasUBO) { GLuint bidx = glGetUniformBlockIndex_(s.program, u.blockname); GLuint uidx = GL_INVALID_INDEX; glGetUniformIndices_(s.program, 1, &u.name, &uidx); if(bidx != GL_INVALID_INDEX && uidx != GL_INVALID_INDEX) { GLint sizeval = 0, offsetval = 0, strideval = 0; glGetActiveUniformBlockiv_(s.program, bidx, GL_UNIFORM_BLOCK_DATA_SIZE, &sizeval); if(sizeval <= 0) return; glGetActiveUniformsiv_(s.program, 1, &uidx, GL_UNIFORM_OFFSET, &offsetval); if(u.stride > 0) { glGetActiveUniformsiv_(s.program, 1, &uidx, GL_UNIFORM_ARRAY_STRIDE, &strideval); if(strideval > u.stride) return; } u.offset = offsetval; u.size = sizeval; glUniformBlockBinding_(s.program, bidx, u.binding); if(dbgubo) conoutf(CON_DEBUG, "UBO: %s:%s:%d, offset: %d, size: %d, stride: %d", u.name, u.blockname, u.binding, offsetval, sizeval, strideval); } } else if(hasBUE) { GLint size = glGetUniformBufferSize_(s.program, u.loc), stride = 0; if(size <= 0) return; if(u.stride > 0) { defformatstring(elem1name)("%s[1]", u.name); GLint elem1loc = glGetUniformLocation_(s.program, elem1name); if(elem1loc == -1) return; GLintptr elem0off = glGetUniformOffset_(s.program, u.loc), elem1off = glGetUniformOffset_(s.program, elem1loc); stride = elem1off - elem0off; if(stride > u.stride) return; } u.offset = 0; u.size = size; if(dbgubo) conoutf(CON_DEBUG, "BUE: %s:%s:%d, offset: %d, size: %d, stride: %d", u.name, u.blockname, u.binding, 0, size, stride); } } static void linkglslprogram(Shader &s, bool msg = true) { s.program = s.vsobj && s.psobj ? glCreateProgram_() : 0; GLint success = 0; if(s.program) { glAttachShader_(s.program, s.vsobj); glAttachShader_(s.program, s.psobj); loopv(s.attriblocs) { AttribLoc &a = s.attriblocs[i]; glBindAttribLocation_(s.program, a.loc, a.name); } glLinkProgram_(s.program); glGetProgramiv_(s.program, GL_LINK_STATUS, &success); } if(success) { glUseProgram_(s.program); loopi(8) { defformatstring(arg)("tex%d", i); GLint loc = glGetUniformLocation_(s.program, arg); if(loc != -1) glUniform1i_(loc, i); } loopv(s.defaultparams) { ShaderParam ¶m = s.defaultparams[i]; string pname; if(param.type==SHPARAM_UNIFORM) copystring(pname, param.name); else formatstring(pname)("%s%d", param.type==SHPARAM_VERTEX ? "v" : "p", param.index); param.loc = glGetUniformLocation_(s.program, pname); } loopv(s.uniformlocs) bindglsluniform(s, s.uniformlocs[i]); glUseProgram_(0); } else if(s.program) { if(msg) showglslinfo(GL_FALSE, s.program, s.name, NULL); glDeleteProgram_(s.program); s.program = 0; } } bool checkglslsupport() { const GLchar *vsstr = "void main(void) {\n" " gl_Position = ftransform();\n" "}\n"; #if 0 /* check if GLSL profile supports loops */ const GLchar *psstr = "uniform int N;\n" "uniform vec4 delta;\n" "void main(void) {\n" " vec4 test = vec4(0.0, 0.0, 0.0, 0.0);\n" " for(int i = 0; i < N; i++) test += delta;\n" " gl_FragColor = test;\n" "}\n"; #else const GLchar *psstr = "void main(void) {\n" " gl_FragColor = vec4(0.0);\n" "}\n"; #endif GLuint vsobj = glCreateShader_(GL_VERTEX_SHADER), psobj = glCreateShader_(GL_FRAGMENT_SHADER); GLuint program = glCreateProgram_(); GLint success = 0; if(vsobj && psobj && program) { glShaderSource_(vsobj, 1, &vsstr, NULL); glCompileShader_(vsobj); glGetShaderiv_(vsobj, GL_COMPILE_STATUS, &success); if(success) { glShaderSource_(psobj, 1, &psstr, NULL); glCompileShader_(psobj); glGetShaderiv_(psobj, GL_COMPILE_STATUS, &success); if(success) { glAttachShader_(program, vsobj); glAttachShader_(program, psobj); glLinkProgram_(program); glGetProgramiv_(program, GL_LINK_STATUS, &success); } } } if(vsobj) glDeleteShader_(vsobj); if(psobj) glDeleteShader_(psobj); if(program) glDeleteProgram_(program); return success!=0; } #define ALLOCEXTPARAM 0xFF #define UNUSEDEXTPARAM 0xFE static int addextparam(Shader &s, const char *name, int type, int index, int loc) { if(!(s.numextparams%4)) { LocalShaderParamState *extparams = new LocalShaderParamState[s.numextparams+4]; if(s.extparams) { memcpy(extparams, s.extparams, s.numextparams*sizeof(LocalShaderParamState)); delete[] s.extparams; } s.extparams = extparams; } int extindex = s.numextparams; LocalShaderParamState &ext = s.extparams[extindex]; ext.name = name; ext.type = type; ext.index = index; ext.loc = loc; s.numextparams++; return extindex; } static void allocglsluniformparam(Shader &s, int type, int index, bool local = false) { ShaderParamState &val = (type==SHPARAM_VERTEX ? vertexparamstate[index] : pixelparamstate[index]); int loc = val.name ? glGetUniformLocation_(s.program, val.name) : -1; if(loc == -1) { defformatstring(altname)("%s%d", type==SHPARAM_VERTEX ? "v" : "p", index); loc = glGetUniformLocation_(s.program, altname); } if(loc >= 0) loopi(s.numextparams) { LocalShaderParamState &ext = s.extparams[i]; if(ext.loc != loc) continue; if(ext.type==SHPARAM_LOOKUP) { ext.name = val.name; ext.type = type; ext.index = local ? -1 : index; } if(type==SHPARAM_VERTEX) s.extvertparams[index] = i; else s.extpixparams[index] = i; return; } if(loc == -1) { if(type==SHPARAM_VERTEX) s.extvertparams[index] = local ? UNUSEDEXTPARAM : ALLOCEXTPARAM; else s.extpixparams[index] = local ? UNUSEDEXTPARAM : ALLOCEXTPARAM; return; } int extindex = addextparam(s, val.name, type, local ? -1 : index, loc); if(type==SHPARAM_VERTEX) s.extvertparams[index] = extindex; else s.extpixparams[index] = extindex; } static void setglsluniformformat(Shader &s, const char *name, GLenum format, int size) { switch(format) { case GL_FLOAT: case GL_FLOAT_VEC2: case GL_FLOAT_VEC3: break; case GL_FLOAT_VEC4: default: return; } if(size > 1 || !strncmp(name, "gl_", 3)) return; int loc = glGetUniformLocation_(s.program, name); if(loc < 0) return; loopvj(s.defaultparams) if(s.defaultparams[j].loc == loc) { s.defaultparams[j].format = format; return; } loopj(s.numextparams) if(s.extparams[j].loc == loc) { s.extparams[j].format = format; return; } int extindex = addextparam(s, NULL, SHPARAM_LOOKUP, -1, loc); if(extindex >= 0) s.extparams[extindex].format = format; } static void allocglslactiveuniforms(Shader &s) { GLint numactive = 0; glGetProgramiv_(s.program, GL_ACTIVE_UNIFORMS, &numactive); string name; loopi(numactive) { GLsizei namelen = 0; GLint size = 0; GLenum format = GL_FLOAT_VEC4; name[0] = '\0'; glGetActiveUniform_(s.program, i, sizeof(name)-1, &namelen, &size, &format, name); if(namelen <= 0) continue; name[clamp(int(namelen), 0, (int)sizeof(name)-2)] = '\0'; setglsluniformformat(s, name, format, size); } } static inline bool duplicateenvparam(GlobalShaderParamState ¶m) { loopj(RESERVEDSHADERPARAMS) { GlobalShaderParamState &vp = vertexparamstate[j]; if(vp.name && !vp.local && vp.version > param.version && !strcmp(vp.name, param.name)) return true; GlobalShaderParamState &pp = pixelparamstate[j]; if(pp.name && !pp.local && pp.version > param.version && !strcmp(pp.name, param.name)) return true; } return false; } void Shader::allocenvparams(Slot *slot) { if(!(type & SHADER_GLSLANG)) return; if(slot) { #define UNIFORMTEX(name, tmu) \ { \ loc = glGetUniformLocation_(program, name); \ int val = tmu; \ if(loc != -1) glUniform1i_(loc, val); \ } int loc, tmu = 2; if(type & SHADER_NORMALSLMS) { UNIFORMTEX("lmcolor", 1); UNIFORMTEX("lmdir", 2); tmu++; } else UNIFORMTEX("lightmap", 1); if(type & SHADER_ENVMAP) UNIFORMTEX("envmap", tmu++); UNIFORMTEX("shadowmap", 7); int stex = 0; loopv(slot->sts) { Slot::Tex &t = slot->sts[i]; switch(t.type) { case TEX_DIFFUSE: UNIFORMTEX("diffusemap", 0); break; case TEX_NORMAL: UNIFORMTEX("normalmap", tmu++); break; case TEX_GLOW: UNIFORMTEX("glowmap", tmu++); break; case TEX_DECAL: UNIFORMTEX("decal", tmu++); break; case TEX_SPEC: if(t.combined<0) UNIFORMTEX("specmap", tmu++); break; case TEX_DEPTH: if(t.combined<0) UNIFORMTEX("depthmap", tmu++); break; case TEX_UNKNOWN: { defformatstring(sname)("stex%d", stex++); UNIFORMTEX(sname, tmu++); break; } } } } if(!extvertparams) { extvertparams = new uchar[2*RESERVEDSHADERPARAMS]; extpixparams = extvertparams + RESERVEDSHADERPARAMS; } memset(extvertparams, ALLOCEXTPARAM, 2*RESERVEDSHADERPARAMS); loopi(RESERVEDSHADERPARAMS) if(vertexparamstate[i].name && !vertexparamstate[i].local && !duplicateenvparam(vertexparamstate[i])) allocglsluniformparam(*this, SHPARAM_VERTEX, i); loopi(RESERVEDSHADERPARAMS) if(pixelparamstate[i].name && !pixelparamstate[i].local && !duplicateenvparam(pixelparamstate[i])) allocglsluniformparam(*this, SHPARAM_PIXEL, i); allocglslactiveuniforms(*this); } static inline void setuniformval(LocalShaderParamState &l, const float *val) { if(memcmp(l.curval, val, sizeof(l.curval))) { memcpy(l.curval, val, sizeof(l.curval)); switch(l.format) { case GL_FLOAT: glUniform1fv_(l.loc, 1, l.curval); break; case GL_FLOAT_VEC2: glUniform2fv_(l.loc, 1, l.curval); break; case GL_FLOAT_VEC3: glUniform3fv_(l.loc, 1, l.curval); break; case GL_FLOAT_VEC4: glUniform4fv_(l.loc, 1, l.curval); break; } } } static inline void flushparam(int type, int index) { ShaderParamState &val = (type==SHPARAM_VERTEX ? vertexparamstate[index] : pixelparamstate[index]); if(Shader::lastshader && Shader::lastshader->type&SHADER_GLSLANG) { uchar &extindex = (type==SHPARAM_VERTEX ? Shader::lastshader->extvertparams[index] : Shader::lastshader->extpixparams[index]); if(extindex == ALLOCEXTPARAM) allocglsluniformparam(*Shader::lastshader, type, index, val.local); if(extindex < Shader::lastshader->numextparams) setuniformval(Shader::lastshader->extparams[extindex], val.val); } else if(val.dirty==ShaderParamState::DIRTY) { glProgramEnvParameter4fvARB_(type==SHPARAM_VERTEX ? GL_VERTEX_PROGRAM_ARB : GL_FRAGMENT_PROGRAM_ARB, index, val.val); val.dirty = ShaderParamState::CLEAN; } } static inline bool sortparamversions(const GlobalShaderParamState *x, const GlobalShaderParamState *y) { return x->version < y->version; } static uint resetparamversions() { GlobalShaderParamState *params[2*(RESERVEDSHADERPARAMS + MAXSHADERPARAMS)]; loopi(RESERVEDSHADERPARAMS + MAXSHADERPARAMS) { params[2*i+0] = &vertexparamstate[i]; params[2*i+1] = &pixelparamstate[i]; } quicksort(params, 2*(RESERVEDSHADERPARAMS + MAXSHADERPARAMS), sortparamversions); paramversion = 0; loopi(2*(RESERVEDSHADERPARAMS + MAXSHADERPARAMS)) params[i]->version = ++paramversion; return paramversion; } static inline ShaderParamState &setparamf(const char *name, int type, int index, float x, float y, float z, float w) { GlobalShaderParamState &val = (type==SHPARAM_VERTEX ? vertexparamstate[index] : pixelparamstate[index]); val.name = name; val.version = ++paramversion > 0 ? paramversion : resetparamversions(); if(val.dirty==ShaderParamState::INVALID || val.val[0]!=x || val.val[1]!=y || val.val[2]!=z || val.val[3]!=w) { val.val[0] = x; val.val[1] = y; val.val[2] = z; val.val[3] = w; val.dirty = ShaderParamState::DIRTY; } return val; } static inline ShaderParamState &setparamfv(const char *name, int type, int index, const float *v) { GlobalShaderParamState &val = (type==SHPARAM_VERTEX ? vertexparamstate[index] : pixelparamstate[index]); val.name = name; val.version = ++paramversion > 0 ? paramversion : resetparamversions(); if(val.dirty==ShaderParamState::INVALID || memcmp(val.val, v, sizeof(val.val))) { memcpy(val.val, v, sizeof(val.val)); val.dirty = ShaderParamState::DIRTY; } return val; } void setenvparamf(const char *name, int type, int index, float x, float y, float z, float w) { ShaderParamState &val = setparamf(name, type, index, x, y, z, w); val.local = false; if(val.dirty==ShaderParamState::DIRTY) dirtyenvparams = true; } void setenvparamfv(const char *name, int type, int index, const float *v) { ShaderParamState &val = setparamfv(name, type, index, v); val.local = false; if(val.dirty==ShaderParamState::DIRTY) dirtyenvparams = true; } void flushenvparamf(const char *name, int type, int index, float x, float y, float z, float w) { ShaderParamState &val = setparamf(name, type, index, x, y, z, w); val.local = false; flushparam(type, index); } void flushenvparamfv(const char *name, int type, int index, const float *v) { ShaderParamState &val = setparamfv(name, type, index, v); val.local = false; flushparam(type, index); } void setlocalparamf(const char *name, int type, int index, float x, float y, float z, float w) { ShaderParamState &val = setparamf(name, type, index, x, y, z, w); val.local = true; flushparam(type, index); } void setlocalparamfv(const char *name, int type, int index, const float *v) { ShaderParamState &val = setparamfv(name, type, index, v); val.local = true; flushparam(type, index); } void invalidateenvparams(int type, int start, int count) { GlobalShaderParamState *paramstate = type==SHPARAM_VERTEX ? vertexparamstate : pixelparamstate; int end = min(start + count, RESERVEDSHADERPARAMS + MAXSHADERPARAMS); while(start < end) { paramstate[start].dirty = ShaderParamState::INVALID; start++; } } void Shader::flushenvparams(Slot *slot) { if(type & SHADER_GLSLANG) { if(!used) allocenvparams(slot); loopi(numextparams) { LocalShaderParamState &ext = extparams[i]; if(ext.index >= 0) setuniformval(ext, ext.type==SHPARAM_VERTEX ? vertexparamstate[ext.index].val : pixelparamstate[ext.index].val); } } else if(dirtyenvparams) { loopi(RESERVEDSHADERPARAMS) { ShaderParamState &val = vertexparamstate[i]; if(val.local || val.dirty!=ShaderParamState::DIRTY) continue; glProgramEnvParameter4fvARB_(GL_VERTEX_PROGRAM_ARB, i, val.val); val.dirty = ShaderParamState::CLEAN; } loopi(RESERVEDSHADERPARAMS) { ShaderParamState &val = pixelparamstate[i]; if(val.local || val.dirty!=ShaderParamState::DIRTY) continue; glProgramEnvParameter4fvARB_(GL_FRAGMENT_PROGRAM_ARB, i, val.val); val.dirty = ShaderParamState::CLEAN; } dirtyenvparams = false; } used = true; } static inline void setglslslotparam(const ShaderParam &p, LocalShaderParamState &l, uint &mask, int i) { if(!(mask&(1< &defaultparams, Slot &slot, VSlot &vslot) { uint unimask = 0; loopv(vslot.params) { ShaderParam &p = vslot.params[i]; if(!defaultparams.inrange(p.loc)) continue; LocalShaderParamState &l = defaultparams[p.loc]; setglslslotparam(p, l, unimask, p.loc); } loopv(slot.params) { ShaderParam &p = slot.params[i]; if(!defaultparams.inrange(p.loc)) continue; LocalShaderParamState &l = defaultparams[p.loc]; setglslslotparam(p, l, unimask, p.loc); } loopv(defaultparams) { LocalShaderParamState &l = defaultparams[i]; setglslslotparam(l, l, unimask, i); } } static inline void setasmslotparam(const ShaderParam &p, LocalShaderParamState &l, uint &mask) { if(!(mask&(1< &defaultparams, Slot &slot, VSlot &vslot) { uint vertmask = 0, pixmask = 0; loopv(vslot.params) { ShaderParam &p = vslot.params[i]; if(!defaultparams.inrange(p.loc) || p.type==SHPARAM_UNIFORM) continue; LocalShaderParamState &l = defaultparams[p.loc]; setasmslotparam(p, l, l.type==SHPARAM_VERTEX ? vertmask : pixmask); } loopv(slot.params) { ShaderParam &p = slot.params[i]; if(!defaultparams.inrange(p.loc) || p.type==SHPARAM_UNIFORM) continue; LocalShaderParamState &l = defaultparams[p.loc]; setasmslotparam(p, l, l.type==SHPARAM_VERTEX ? vertmask : pixmask); } loopv(defaultparams) { LocalShaderParamState &l = defaultparams[i]; if(l.type!=SHPARAM_UNIFORM) setasmslotparam(l, l, l.type==SHPARAM_VERTEX ? vertmask : pixmask); } } void Shader::setslotparams(Slot &slot, VSlot &vslot) { if(type & SHADER_GLSLANG) setglslslotparams(defaultparams, slot, vslot); else setasmslotparams(defaultparams, slot, vslot); } void Shader::bindprograms() { if(this == lastshader || type&(SHADER_DEFERRED|SHADER_INVALID)) return; if(type & SHADER_GLSLANG) { glUseProgram_(program); } else { if(lastshader && lastshader->type & SHADER_GLSLANG) glUseProgram_(0); glBindProgramARB_(GL_VERTEX_PROGRAM_ARB, vs); glBindProgramARB_(GL_FRAGMENT_PROGRAM_ARB, ps); } lastshader = this; } VARFN(shaders, useshaders, -1, -1, 1, initwarning("shaders")); VARF(shaderprecision, 0, 0, 2, initwarning("shader quality")); VARF(forceglsl, -1, -1, 1, initwarning("shaders")); bool Shader::compile() { if(type & SHADER_GLSLANG) { if(!vsstr) vsobj = !reusevs || reusevs->type&SHADER_INVALID ? 0 : reusevs->vsobj; else compileglslshader(GL_VERTEX_SHADER, vsobj, vsstr, name, dbgshader || !variantshader); if(!psstr) psobj = !reuseps || reuseps->type&SHADER_INVALID ? 0 : reuseps->psobj; else compileglslshader(GL_FRAGMENT_SHADER, psobj, psstr, name, dbgshader || !variantshader); linkglslprogram(*this, !variantshader); return program!=0; } else { if(renderpath!=R_ASMSHADER && renderpath!=R_ASMGLSLANG) return false; if(!vsstr) vs = !reusevs || reusevs->type&SHADER_INVALID ? 0 : reusevs->vs; else if(!compileasmshader(GL_VERTEX_PROGRAM_ARB, vs, vsstr, "VS", name, dbgshader || !variantshader, variantshader!=NULL)) native = false; if(!psstr) ps = !reuseps || reuseps->type&SHADER_INVALID ? 0 : reuseps->ps; else if(!compileasmshader(GL_FRAGMENT_PROGRAM_ARB, ps, psstr, "PS", name, dbgshader || !variantshader, variantshader!=NULL)) native = false; return vs && ps && (!variantshader || native); } } void Shader::cleanup(bool invalid) { detailshader = NULL; used = false; native = true; if(vs) { if(!reusevs) glDeleteProgramsARB_(1, &vs); vs = 0; } if(ps) { if(!reuseps) glDeleteProgramsARB_(1, &ps); ps = 0; } if(vsobj) { if(!reusevs) glDeleteShader_(vsobj); vsobj = 0; } if(psobj) { if(!reuseps) glDeleteShader_(psobj); psobj = 0; } if(program) { glDeleteProgram_(program); program = 0; } numextparams = 0; DELETEA(extparams); DELETEA(extvertparams); extpixparams = NULL; loopv(defaultparams) memset(defaultparams[i].curval, -1, sizeof(defaultparams[i].curval)); if(standard || invalid) { type = SHADER_INVALID; loopi(MAXVARIANTROWS) variants[i].setsize(0); DELETEA(vsstr); DELETEA(psstr); DELETEA(defer); defaultparams.setsize(0); attriblocs.setsize(0); uniformlocs.setsize(0); altshader = NULL; loopi(MAXSHADERDETAIL) fastshader[i] = this; reusevs = reuseps = NULL; } } static void genattriblocs(Shader &s, const char *vs, const char *ps) { static int len = strlen("#pragma CUBE2_attrib"); string name; int loc; while((vs = strstr(vs, "#pragma CUBE2_attrib"))) { if(sscanf(vs, "#pragma CUBE2_attrib %100s %d", name, &loc) == 2) s.attriblocs.add(AttribLoc(getshaderparamname(name), loc)); vs += len; } } static void genuniformlocs(Shader &s, const char *vs, const char *ps) { static int len = strlen("#pragma CUBE2_uniform"); string name, blockname; int binding, stride; while((vs = strstr(vs, "#pragma CUBE2_uniform"))) { int numargs = sscanf(vs, "#pragma CUBE2_uniform %100s %100s %d %d", name, blockname, &binding, &stride); if(numargs >= 3) s.uniformlocs.add(UniformLoc(getshaderparamname(name), getshaderparamname(blockname), binding, numargs >= 4 ? stride : 0)); else if(numargs >= 1) s.uniformlocs.add(UniformLoc(getshaderparamname(name))); vs += len; } } Shader *newshader(int type, const char *name, const char *vs, const char *ps, Shader *variant = NULL, int row = 0) { if(Shader::lastshader) { if(renderpath==R_ASMSHADER || renderpath==R_ASMGLSLANG) { glBindProgramARB_(GL_VERTEX_PROGRAM_ARB, 0); glBindProgramARB_(GL_FRAGMENT_PROGRAM_ARB, 0); } if(renderpath==R_GLSLANG || renderpath==R_ASMGLSLANG) glUseProgram_(0); Shader::lastshader = NULL; } Shader *exists = shaders.access(name); char *rname = exists ? exists->name : newstring(name); Shader &s = shaders[rname]; s.name = rname; s.vsstr = newstring(vs); s.psstr = newstring(ps); DELETEA(s.defer); s.type = type; s.variantshader = variant; s.standard = standardshader; if(forceshaders) s.forced = true; s.reusevs = s.reuseps = NULL; if(variant) { int row = 0, col = 0; if(!vs[0] || sscanf(vs, "%d , %d", &row, &col) >= 1) { DELETEA(s.vsstr); s.reusevs = !vs[0] ? variant : (variant->variants[row].inrange(col) ? variant->variants[row][col] : NULL); } row = col = 0; if(!ps[0] || sscanf(ps, "%d , %d", &row, &col) >= 1) { DELETEA(s.psstr); s.reuseps = !ps[0] ? variant : (variant->variants[row].inrange(col) ? variant->variants[row][col] : NULL); } } if(variant) loopv(variant->defaultparams) s.defaultparams.add(variant->defaultparams[i]); else loopv(curparams) s.defaultparams.add(curparams[i]); s.attriblocs.setsize(0); s.uniformlocs.setsize(0); if(type & SHADER_GLSLANG) { genattriblocs(s, vs, ps); genuniformlocs(s, vs, ps); } if(renderpath!=R_FIXEDFUNCTION && !s.compile()) { s.cleanup(true); if(variant) shaders.remove(rname); return NULL; } if(variant) variant->variants[row].add(&s); s.fixdetailshader(); return &s; } void setupshaders() { if(renderpath==R_ASMSHADER || renderpath==R_ASMGLSLANG) { GLint val; glGetProgramivARB_(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, &val); maxvpenvparams = val; glGetProgramivARB_(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &val); maxvplocalparams = val; glGetProgramivARB_(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, &val); maxfpenvparams = val; glGetProgramivARB_(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &val); maxfplocalparams = val; } if(renderpath==R_GLSLANG || renderpath==R_ASMGLSLANG) { GLint val; glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &val); maxvsuniforms = val/4; glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, &val); maxfsuniforms = val/4; glGetIntegerv(GL_MAX_VARYING_FLOATS, &val); maxvaryings = val; } if(renderpath != R_FIXEDFUNCTION) { GLint val; glGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, &val); maxtexcoords = val; } standardshader = true; if(renderpath == R_GLSLANG) { defaultshader = newshader(SHADER_GLSLANG, "default", "void main(void) {\n" " gl_Position = ftransform();\n" " gl_TexCoord[0] = gl_MultiTexCoord0;\n" " gl_FrontColor = gl_Color;\n" "}\n", "uniform sampler2D tex0;\n" "void main(void) {\n" " gl_FragColor = gl_Color * texture2D(tex0, gl_TexCoord[0].xy);\n" "}\n"); notextureshader = newshader(SHADER_GLSLANG, "notexture", "void main(void) {\n" " gl_Position = ftransform();\n" " gl_FrontColor = gl_Color;\n" "}\n", "void main(void) {\n" " gl_FragColor = gl_Color;\n" "}\n"); } else { if(renderpath==R_ASMSHADER || renderpath==R_ASMGLSLANG) { glEnable(GL_VERTEX_PROGRAM_ARB); glEnable(GL_FRAGMENT_PROGRAM_ARB); } defaultshader = newshader(0, "default", "!!ARBvp1.0\n" "OPTION ARB_position_invariant;\n" "MOV result.texcoord[0], vertex.texcoord[0];\n" "MOV result.color, vertex.color;\n" "END\n", "!!ARBfp1.0\n" "TEMP color;\n" "TEX color, fragment.texcoord[0], texture[0], 2D;\n" "MUL result.color, fragment.color, color;\n" "END\n"); notextureshader = newshader(0, "notexture", "!!ARBvp1.0\n" "OPTION ARB_position_invariant;\n" "MOV result.color, vertex.color;\n" "END\n", "!!ARBfp1.0\n" "TEX result.color, fragment.texcoord[0], texture[0], 2D;\n" "END\n"); } standardshader = false; if(!defaultshader || !notextureshader) fatal("failed to setup shaders"); } static const char *findglslmain(const char *s) { const char *main = strstr(s, "main"); if(!main) return NULL; for(; main >= s; main--) switch(*main) { case '\r': case '\n': case ';': return main + 1; } return s; } static uint findusedtexcoords(const char *str) { uint used = 0; for(;;) { const char *tc = strstr(str, "result.texcoord["); if(!tc) break; tc += strlen("result.texcoord["); int n = strtol(tc, (char **)&str, 10); if(n<0 || n>=16) continue; used |= 1<=(int)sizeof(texcoords)) continue; while(*str && *str!=']') str++; if(*str==']') { if(*++str!='.') { texcoords[n] = 0xF; continue; } for(;;) { switch(*++str) { case 'r': case 'x': texcoords[n] |= 1; continue; case 'g': case 'y': texcoords[n] |= 2; continue; case 'b': case 'z': texcoords[n] |= 4; continue; case 'a': case 'w': texcoords[n] |= 8; continue; } break; } } } loopi(sizeof(texcoords)) if(texcoords[i]>0 && texcoords[i]<0xF) { loopk(4) if(!(texcoords[i]&(1< &vsbuf, vector &psbuf, int fogtc, int fogcomp) { char *fogcoord = strstr(vsbuf.getbuf(), "result.fogcoord"); if(!fogcoord) return; static const int fogcoordlen = strlen("result.fogcoord"); char *afterfogcoord = fogcoord + fogcoordlen; if(*afterfogcoord=='.') afterfogcoord += 2; defformatstring(repfogcoord)("result.texcoord[%d].%c", fogtc, fogcomp==3 ? 'w' : 'x'+fogcomp); memcpy(fogcoord, repfogcoord, afterfogcoord - fogcoord); vsbuf.insert(afterfogcoord - vsbuf.getbuf(), repfogcoord + (afterfogcoord - fogcoord), strlen(repfogcoord) - (afterfogcoord - fogcoord)); char *fogoption = strstr(psbuf.getbuf(), "OPTION ARB_fog_linear;"); if(!fogoption) return; static const int fogoptionlen = strlen("OPTION ARB_fog_linear;"); memcpy(fogoption, "TEMP emufogcolor; ", fogoptionlen); char *str = psbuf.getbuf(); for(;;) { static const int colorlen = strlen("result.color"); str = strstr(str, "result.color"); if(!str) break; if(str[colorlen]!='.' || (str[colorlen+1]!='a' && str[colorlen+1]!='w')) memcpy(str, " emufogcolor", colorlen); str += colorlen; } defformatstring(fogtcstr)("fragment.texcoord[%d].%c", fogtc, fogcomp==3 ? 'w' : 'x'+fogcomp); static const int fragfogcoordlen = strlen("fragment.fogcoord.x"); str = strstr(psbuf.getbuf(), "fragment.fogcoord.x"); if(str) { memcpy(str, fogtcstr, fragfogcoordlen); psbuf.insert(&str[fragfogcoordlen] - psbuf.getbuf(), &fogtcstr[fragfogcoordlen], strlen(fogtcstr) - fragfogcoordlen); } char *end = strstr(psbuf.getbuf(), "END"); if(end) psbuf.setsize(end - psbuf.getbuf()); defformatstring(calcfog)( "TEMP emufog;\n" "SUB emufog.x, state.fog.params.z, %s;\n" "MUL_SAT emufog.x, emufog.x, state.fog.params.w;\n" "LRP result.color.rgb, emufog.x, emufogcolor, state.fog.color;\n" "END\n", fogtcstr); psbuf.put(calcfog, strlen(calcfog)+1); } VAR(reserveshadowmaptc, 1, 0, 0); VAR(reservedynlighttc, 1, 0, 0); VAR(minimizedynlighttcusage, 1, 0, 0); static void gengenericvariant(Shader &s, const char *sname, const char *vs, const char *ps, int row) { bool vschanged = false, pschanged = false; vector vsv, psv; vsv.put(vs, strlen(vs)+1); psv.put(ps, strlen(ps)+1); static const int len = strlen("#pragma CUBE2_variant"), olen = strlen("override"); for(char *vspragma = vsv.getbuf();; vschanged = true) { vspragma = strstr(vspragma, "#pragma CUBE2_variant"); if(!vspragma) break; memset(vspragma, ' ', len); vspragma += len; if(!strncmp(vspragma, "override", olen)) { memset(vspragma, ' ', olen); vspragma += olen; char *end = vspragma + strcspn(vspragma, "\n\r"); int endlen = strspn(end, "\n\r"); memset(end, ' ', endlen); } } for(char *pspragma = psv.getbuf();; pschanged = true) { pspragma = strstr(pspragma, "#pragma CUBE2_variant"); if(!pspragma) break; memset(pspragma, ' ', len); pspragma += len; if(!strncmp(pspragma, "override", olen)) { memset(pspragma, ' ', olen); pspragma += olen; char *end = pspragma + strcspn(pspragma, "\n\r"); int endlen = strspn(end, "\n\r"); memset(end, ' ', endlen); } } defformatstring(varname)("%s", s.variants[row].length(), row, sname); defformatstring(reuse)("%d", row); newshader(s.type, varname, vschanged ? vsv.getbuf() : reuse, pschanged ? psv.getbuf() : reuse, &s, row); } static bool genwatervariant(Shader &s, const char *sname, vector &vs, vector &ps, int row) { char *vspragma = strstr(vs.getbuf(), "#pragma CUBE2_water"); if(!vspragma) return false; char *pspragma = strstr(ps.getbuf(), "#pragma CUBE2_water"); if(!pspragma) return false; vspragma += strcspn(vspragma, "\n"); if(*vspragma) vspragma++; pspragma += strcspn(pspragma, "\n"); if(*pspragma) pspragma++; if(s.type & SHADER_GLSLANG) { const char *fadedef = "waterfade = gl_Vertex.z*waterfadeparams.x + waterfadeparams.y;\n"; vs.insert(vspragma-vs.getbuf(), fadedef, strlen(fadedef)); const char *fadeuse = "gl_FragColor.a = waterfade;\n"; ps.insert(pspragma-ps.getbuf(), fadeuse, strlen(fadeuse)); const char *fadedecl = "uniform vec4 waterfadeparams; varying float waterfade;\n"; const char *vsmain = findglslmain(vs.getbuf()), *psmain = findglslmain(ps.getbuf()); vs.insert(vsmain ? vsmain - vs.getbuf() : 0, fadedecl, strlen(fadedecl)); ps.insert(psmain ? psmain - ps.getbuf() : 0, fadedecl, strlen(fadedecl)); } else { int fadetc = -1, fadecomp = -1; if(!findunusedtexcoordcomponent(vs.getbuf(), fadetc, fadecomp)) { uint usedtc = findusedtexcoords(vs.getbuf()); int reservetc = row%2 ? reserveshadowmaptc : reservedynlighttc; loopi(maxtexcoords-reservetc) if(!(usedtc&(1<=0) { defformatstring(fadedef)("MAD result.texcoord[%d].%c, vertex.position.z, program.env[8].x, program.env[8].y;\n", fadetc, fadecomp==3 ? 'w' : 'x'+fadecomp); vs.insert(vspragma-vs.getbuf(), fadedef, strlen(fadedef)); defformatstring(fadeuse)("MOV result.color.a, fragment.texcoord[%d].%c;\n", fadetc, fadecomp==3 ? 'w' : 'x'+fadecomp); ps.insert(pspragma-ps.getbuf(), fadeuse, strlen(fadeuse)); } else // fallback - use fog value, works under water but not above { const char *fogfade = "MAD result.color.a, fragment.fogcoord.x, program.env[8].z, program.env[8].w;\n"; ps.insert(pspragma-ps.getbuf(), fogfade, strlen(fogfade)); } } defformatstring(name)("%s", sname); Shader *variant = newshader(s.type, name, vs.getbuf(), ps.getbuf(), &s, row); return variant!=NULL; } static void genwatervariant(Shader &s, const char *sname, const char *vs, const char *ps, int row = 2) { vector vsw, psw; vsw.put(vs, strlen(vs)+1); psw.put(ps, strlen(ps)+1); genwatervariant(s, sname, vsw, psw, row); } static void gendynlightvariant(Shader &s, const char *sname, const char *vs, const char *ps, int row = 0) { int numlights = 0, lights[MAXDYNLIGHTS]; int emufogtc = -1, emufogcomp = -1; if(s.type & SHADER_GLSLANG) numlights = maxvaryings < 48 || minimizedynlighttcusage ? 1 : MAXDYNLIGHTS; else { uint usedtc = findusedtexcoords(vs); int reservetc = row%2 ? reserveshadowmaptc : reservedynlighttc; if(maxtexcoords-reservetc<0) return; int limit = minimizedynlighttcusage ? 1 : MAXDYNLIGHTS; loopi(maxtexcoords-reservetc) if(!(usedtc&(1<=limit) break; } extern int emulatefog; if(emulatefog && reservetc>0 && numlights+1 vspragma) vsmain = vs; psmain = findglslmain(ps); if(psmain > pspragma) psmain = ps; } vector vsdl, psdl; loopi(MAXDYNLIGHTS) { vsdl.setsize(0); psdl.setsize(0); if(vsmain >= vs) vsdl.put(vs, vsmain - vs); if(psmain >= ps) psdl.put(ps, psmain - ps); if(s.type & SHADER_GLSLANG) { loopk(i+1) { defformatstring(pos)("%sdynlight%d%s%s", !k || k==numlights ? "uniform vec4 " : " ", k, k < numlights ? "pos" : "offset", k==i || k+1==numlights ? ";\n" : ","); if(k=numlights) formatstring(tc)( "%s" "MAD dynlightdir.xyz, fragment.texcoord[%d], program.env[%d].w, program.env[%d];\n", k==numlights ? "TEMP dynlightdir;\n" : "", lights[0], k-1, k-1); else if(ati_dph_bug || lights[k]==emufogtc) formatstring(tc)( "MAD result.texcoord[%d].xyz, vertex.position, program.env[%d].w, program.env[%d];\n", lights[k], 10+k, 10+k); else formatstring(tc)( "MAD result.texcoord[%d].xyz, vertex.position, program.env[%d].w, program.env[%d];\n" "MOV result.texcoord[%d].w, 1;\n", lights[k], 10+k, 10+k, lights[k]); if(k < numlights) vsdl.put(tc, strlen(tc)); else psdl.put(tc, strlen(tc)); if(s.type & SHADER_GLSLANG) formatstring(dl)( "%s.rgb += dynlight%dcolor.rgb * (1.0 - clamp(dot(dynlight%ddir, dynlight%ddir), 0.0, 1.0));\n", pslight, k, k, k); else if(k>=numlights) formatstring(dl)( "DP3_SAT dynlight.x, dynlightdir, dynlightdir;\n" "SUB dynlight.x, 1, dynlight.x;\n" "MAD %s.rgb, program.env[%d], dynlight.x, %s;\n", pslight, 10+k, pslight); else if(ati_dph_bug || lights[k]==emufogtc) formatstring(dl)( "%s" "DP3_SAT dynlight.x, fragment.texcoord[%d], fragment.texcoord[%d];\n" "SUB dynlight.x, 1, dynlight.x;\n" "MAD %s.rgb, program.env[%d], dynlight.x, %s;\n", !k ? "TEMP dynlight;\n" : "", lights[k], lights[k], pslight, 10+k, pslight); else formatstring(dl)( "%s" "DPH_SAT dynlight.x, -fragment.texcoord[%d], fragment.texcoord[%d];\n" "MAD %s.rgb, program.env[%d], dynlight.x, %s;\n", !k ? "TEMP dynlight;\n" : "", lights[k], lights[k], pslight, 10+k, pslight); psdl.put(dl, strlen(dl)); } vsdl.put(vspragma, strlen(vspragma)+1); psdl.put(pspragma, strlen(pspragma)+1); if(emufogtc >= 0 && i+1 == numlights) genemufog(vsdl, psdl, emufogtc, emufogcomp); defformatstring(name)("%s", i+1, sname); Shader *variant = newshader(s.type, name, vsdl.getbuf(), psdl.getbuf(), &s, row); if(!variant) return; if(row < 4) genwatervariant(s, name, vsdl, psdl, row+2); } } static void genshadowmapvariant(Shader &s, const char *sname, const char *vs, const char *ps, int row = 1) { int smtc = -1, emufogtc = -1, emufogcomp = -1; if(!(s.type & SHADER_GLSLANG)) { uint usedtc = findusedtexcoords(vs); if(maxtexcoords-reserveshadowmaptc<0) return; loopi(maxtexcoords-reserveshadowmaptc) if(!(usedtc&(1<0 && !(usedtc&(1<<(maxtexcoords-reserveshadowmaptc))) && strstr(ps, "OPTION ARB_fog_linear;")) { if(!strstr(vs, "result.fogcoord") || !findunusedtexcoordcomponent(vs, emufogtc, emufogcomp)) return; smtc = maxtexcoords-reserveshadowmaptc; } if(smtc<0) return; } const char *vspragma = strstr(vs, "#pragma CUBE2_shadowmap"), *pspragma = strstr(ps, "#pragma CUBE2_shadowmap"); string pslight; vspragma += strcspn(vspragma, "\n"); if(*vspragma) vspragma++; if(sscanf(pspragma, "#pragma CUBE2_shadowmap %100s", pslight)!=1) return; pspragma += strcspn(pspragma, "\n"); if(*pspragma) pspragma++; const char *vsmain = vs, *psmain = ps; if(s.type & SHADER_GLSLANG) { vsmain = findglslmain(vs); if(vsmain > vspragma) vsmain = vs; psmain = findglslmain(ps); if(psmain > pspragma) psmain = ps; } vector vssm, pssm; if(vsmain >= vs) vssm.put(vs, vsmain - vs); if(psmain >= ps) pssm.put(ps, psmain - ps); if(s.type & SHADER_GLSLANG) { const char *tc = "varying vec3 shadowmaptc;\n"; vssm.put(tc, strlen(tc)); pssm.put(tc, strlen(tc)); const char *smtex = "uniform sampler2D shadowmap;\n" "uniform vec4 shadowmapambient;\n"; pssm.put(smtex, strlen(smtex)); } vssm.put(vsmain, vspragma-vsmain); pssm.put(psmain, pspragma-psmain); extern int smoothshadowmappeel; if(s.type & SHADER_GLSLANG) { const char *tc = "shadowmaptc = vec3(gl_TextureMatrix[2] * gl_Vertex);\n"; vssm.put(tc, strlen(tc)); const char *sm = smoothshadowmappeel ? "vec4 smvals = texture2D(shadowmap, shadowmaptc.xy);\n" "vec2 smdiff = clamp(smvals.xz - shadowmaptc.zz*smvals.y, 0.0, 1.0);\n" "float shadowed = clamp((smdiff.x > 0.0 ? smvals.w : 0.0) - 8.0*smdiff.y, 0.0, 1.0);\n" : "vec4 smvals = texture2D(shadowmap, shadowmaptc.xy);\n" "float smtest = shadowmaptc.z*smvals.y;\n" "float shadowed = smtest < smvals.x && smtest > smvals.z ? smvals.w : 0.0;\n"; pssm.put(sm, strlen(sm)); defformatstring(smlight)( "%s.rgb -= shadowed*clamp(%s.rgb - shadowmapambient.rgb, 0.0, 1.0);\n", pslight, pslight); pssm.put(smlight, strlen(smlight)); } else { defformatstring(tc)( "DP4 result.texcoord[%d].x, state.matrix.texture[2].row[0], vertex.position;\n" "DP4 result.texcoord[%d].y, state.matrix.texture[2].row[1], vertex.position;\n" "DP4 result.texcoord[%d].z, state.matrix.texture[2].row[2], vertex.position;\n", smtc, smtc, smtc); vssm.put(tc, strlen(tc)); defformatstring(sm)( smoothshadowmappeel ? "TEMP smvals, smdiff, smambient;\n" "TEX smvals, fragment.texcoord[%d], texture[7], 2D;\n" "MAD_SAT smdiff.xy, -fragment.texcoord[%d].z, smvals.y, smvals.xzzz;\n" "CMP smvals.w, -smdiff.x, smvals.w, 0;\n" "MAD_SAT smvals.w, -8, smdiff.y, smvals.w;\n" : "TEMP smvals, smtest, smambient;\n" "TEX smvals, fragment.texcoord[%d], texture[7], 2D;\n" "MUL smtest.y, fragment.texcoord[%d].z, smvals.y;\n" "SLT smtest.xy, smtest.y, smvals.xzzz;\n" "MAD_SAT smvals.w, smvals.w, smtest.x, -smtest.y;\n", smtc, smtc); pssm.put(sm, strlen(sm)); formatstring(sm)( "SUB_SAT smambient.rgb, %s, program.env[7];\n" "MAD %s.rgb, smvals.w, -smambient, %s;\n", pslight, pslight, pslight); pssm.put(sm, strlen(sm)); } if(!hasFBO) for(char *s = pssm.getbuf();;) { s = strstr(s, "smvals.w"); if(!s) break; s[7] = 'y'; s += 8; } vssm.put(vspragma, strlen(vspragma)+1); pssm.put(pspragma, strlen(pspragma)+1); if(emufogtc >= 0) genemufog(vssm, pssm, emufogtc, emufogcomp); defformatstring(name)("%s", sname); Shader *variant = newshader(s.type, name, vssm.getbuf(), pssm.getbuf(), &s, row); if(!variant) return; genwatervariant(s, name, vssm.getbuf(), pssm.getbuf(), row+2); if(strstr(vs, "#pragma CUBE2_dynlight")) gendynlightvariant(s, name, vssm.getbuf(), pssm.getbuf(), row); } static void genfogshader(vector &vsbuf, vector &psbuf, const char *vs, const char *ps) { const char *vspragma = strstr(vs, "#pragma CUBE2_fog"), *pspragma = strstr(ps, "#pragma CUBE2_fog"); if(!vspragma && !pspragma) return; static const int pragmalen = strlen("#pragma CUBE2_fog"); const char *vsend = strrchr(vs, '}'); if(vsend) { vsbuf.put(vs, vsend - vs); const char *vsdef = "\n#define FOG_COORD "; const char *vsfog = "\ngl_FogFragCoord = -dot((FOG_COORD), gl_ModelViewMatrixTranspose[2]);\n"; int clen = 0; if(vspragma) { vspragma += pragmalen; while(*vspragma && !iscubespace(*vspragma)) vspragma++; vspragma += strspn(vspragma, " \t\v\f"); clen = strcspn(vspragma, "\r\n"); } if(clen <= 0) { vspragma = "gl_Vertex"; clen = strlen(vspragma); } vsbuf.put(vsdef, strlen(vsdef)); vsbuf.put(vspragma, clen); vsbuf.put(vsfog, strlen(vsfog)); vsbuf.put(vsend, strlen(vsend)+1); } const char *psend = strrchr(ps, '}'); if(psend) { psbuf.put(ps, psend - ps); const char *psdef = "\n#define FOG_COLOR "; const char *psfog = pspragma && !strncmp(pspragma+pragmalen, "rgba", 4) ? "\ngl_FragColor = mix((FOG_COLOR), gl_FragColor, clamp((gl_Fog.end - gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0));\n" : "\ngl_FragColor.rgb = mix((FOG_COLOR).rgb, gl_FragColor.rgb, clamp((gl_Fog.end - gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0));\n"; int clen = 0; if(pspragma) { pspragma += pragmalen; while(iscubealpha(*pspragma)) pspragma++; while(*pspragma && !iscubespace(*pspragma)) pspragma++; pspragma += strspn(pspragma, " \t\v\f"); clen = strcspn(pspragma, "\r\n"); } if(clen <= 0) { pspragma = "gl_Fog.color"; clen = strlen(pspragma); } psbuf.put(psdef, strlen(psdef)); psbuf.put(pspragma, clen); psbuf.put(psfog, strlen(psfog)); psbuf.put(psend, strlen(psend)+1); } } static void genuniformdefs(vector &vsbuf, vector &psbuf, const char *vs, const char *ps, Shader *variant = NULL) { if(variant ? variant->defaultparams.empty() : curparams.empty()) return; const char *vsmain = findglslmain(vs), *psmain = findglslmain(ps); if(!vsmain || !psmain) return; vsbuf.put(vs, vsmain - vs); psbuf.put(ps, psmain - ps); if(variant) loopv(variant->defaultparams) { defformatstring(uni)("\nuniform vec4 %s;\n", variant->defaultparams[i].name); vsbuf.put(uni, strlen(uni)); psbuf.put(uni, strlen(uni)); } else loopv(curparams) { defformatstring(uni)("\nuniform vec4 %s;\n", curparams[i].name); vsbuf.put(uni, strlen(uni)); psbuf.put(uni, strlen(uni)); } vsbuf.put(vsmain, strlen(vsmain)+1); psbuf.put(psmain, strlen(psmain)+1); } VAR(defershaders, 0, 1, 1); void defershader(int *type, const char *name, const char *contents) { Shader *exists = shaders.access(name); if(exists && !(exists->type&SHADER_INVALID)) return; if(!defershaders) { execute(contents); return; } char *rname = exists ? exists->name : newstring(name); Shader &s = shaders[rname]; s.name = rname; DELETEA(s.defer); s.defer = newstring(contents); s.type = SHADER_DEFERRED | *type; s.standard = standardshader; } void useshader(Shader *s) { if(!(s->type&SHADER_DEFERRED) || !s->defer) return; char *defer = s->defer; s->defer = NULL; bool wasstandard = standardshader, wasforcing = forceshaders; int oldflags = identflags; standardshader = s->standard; forceshaders = false; identflags &= ~IDF_PERSIST; curparams.shrink(0); execute(defer); identflags = oldflags; forceshaders = wasforcing; standardshader = wasstandard; delete[] defer; if(s->type&SHADER_DEFERRED) { DELETEA(s->defer); s->type = SHADER_INVALID; } } void fixshaderdetail() { // must null out separately because fixdetailshader can recursively set it enumerate(shaders, Shader, s, { if(!s.forced) s.detailshader = NULL; }); enumerate(shaders, Shader, s, { if(s.forced) s.fixdetailshader(); }); linkslotshaders(); } int Shader::uniformlocversion() { static int version = 0; if(++version >= 0) return version; version = 0; enumerate(shaders, Shader, s, { loopvj(s.uniformlocs) s.uniformlocs[j].version = -1; }); return version; } VARF(nativeshaders, 0, 1, 1, fixshaderdetail()); VARFP(shaderdetail, 0, MAXSHADERDETAIL, MAXSHADERDETAIL, fixshaderdetail()); void Shader::fixdetailshader(bool force, bool recurse) { Shader *alt = this; detailshader = NULL; do { Shader *cur = shaderdetail < MAXSHADERDETAIL ? alt->fastshader[shaderdetail] : alt; if(cur->type&SHADER_DEFERRED && force) useshader(cur); if(!(cur->type&SHADER_INVALID)) { if(cur->type&SHADER_DEFERRED) break; detailshader = cur; if(cur->native || !nativeshaders) break; } alt = alt->altshader; } while(alt && alt!=this); if(recurse && detailshader) loopi(MAXVARIANTROWS) loopvj(detailshader->variants[i]) detailshader->variants[i][j]->fixdetailshader(force, false); } Shader *useshaderbyname(const char *name) { Shader *s = shaders.access(name); if(!s) return NULL; if(!s->detailshader) s->fixdetailshader(); s->forced = true; return s; } void shader(int *type, char *name, char *vs, char *ps) { if(lookupshaderbyname(name)) return; if((*type & SHADER_GLSLANG ? renderpath!=R_GLSLANG && renderpath!=R_ASMGLSLANG : renderpath==R_GLSLANG) || (!hasCM && strstr(ps, *type & SHADER_GLSLANG ? "textureCube" : "CUBE;")) || (!hasTR && strstr(ps, *type & SHADER_GLSLANG ? "texture2DRect" : "RECT;"))) { curparams.shrink(0); return; } if(renderpath!=R_FIXEDFUNCTION) { defformatstring(info)("shader %s", name); renderprogress(loadprogress, info); } vector vsbuf, psbuf, vsbak, psbak; #define GENSHADER(cond, body) \ if(cond) \ { \ if(vsbuf.length()) { vsbak.setsize(0); vsbak.put(vs, strlen(vs)+1); vs = vsbak.getbuf(); vsbuf.setsize(0); } \ if(psbuf.length()) { psbak.setsize(0); psbak.put(ps, strlen(ps)+1); ps = psbak.getbuf(); psbuf.setsize(0); } \ body; \ if(vsbuf.length()) vs = vsbuf.getbuf(); \ if(psbuf.length()) ps = psbuf.getbuf(); \ } if(renderpath!=R_FIXEDFUNCTION) { if(*type & SHADER_GLSLANG) { GENSHADER(curparams.length(), genuniformdefs(vsbuf, psbuf, vs, ps)); GENSHADER(strstr(vs, "#pragma CUBE2_fog") || strstr(ps, "#pragma CUBE2_fog"), genfogshader(vsbuf, psbuf, vs, ps)); } } Shader *s = newshader(*type, name, vs, ps); if(s && renderpath!=R_FIXEDFUNCTION) { // '#' is a comment in vertex/fragment programs, while '#pragma' allows an escape for GLSL, so can handle both at once if(strstr(vs, "#pragma CUBE2_water")) genwatervariant(*s, s->name, vs, ps); if(strstr(vs, "#pragma CUBE2_shadowmap")) genshadowmapvariant(*s, s->name, vs, ps); if(strstr(vs, "#pragma CUBE2_dynlight")) gendynlightvariant(*s, s->name, vs, ps); } curparams.shrink(0); } void variantshader(int *type, char *name, int *row, char *vs, char *ps) { if(*row < 0) { shader(type, name, vs, ps); return; } if(renderpath==R_FIXEDFUNCTION && standardshader) return; Shader *s = lookupshaderbyname(name); if(!s) return; defformatstring(varname)("%s", s->variants[*row].length(), *row, name); //defformatstring(info)("shader %s", varname); //renderprogress(loadprogress, info); vector vsbuf, psbuf, vsbak, psbak; if(renderpath!=R_FIXEDFUNCTION) { if(*type & SHADER_GLSLANG) { GENSHADER(s->defaultparams.length(), genuniformdefs(vsbuf, psbuf, vs, ps, s)); GENSHADER(strstr(vs, "#pragma CUBE2_fog") || strstr(ps, "#pragma CUBE2_fog"), genfogshader(vsbuf, psbuf, vs, ps)); } } Shader *v = newshader(*type, varname, vs, ps, s, *row); if(v && renderpath!=R_FIXEDFUNCTION) { // '#' is a comment in vertex/fragment programs, while '#pragma' allows an escape for GLSL, so can handle both at once if(strstr(vs, "#pragma CUBE2_dynlight")) gendynlightvariant(*s, varname, vs, ps, *row); if(strstr(ps, "#pragma CUBE2_variant") || strstr(vs, "#pragma CUBE2_variant")) gengenericvariant(*s, varname, vs, ps, *row); } } void setshader(char *name) { curparams.shrink(0); Shader *s = shaders.access(name); if(!s) { if(renderpath!=R_FIXEDFUNCTION) conoutf(CON_ERROR, "no such shader: %s", name); } else curshader = s; } ShaderParam *findshaderparam(Slot &s, const char *name, int type = -1, int index = -1) { loopv(s.params) { ShaderParam ¶m = s.params[i]; if((name && param.name && !strcmp(name, param.name)) || (param.type==type && param.index==index)) return ¶m; } if(!s.shader->detailshader) return NULL; loopv(s.shader->detailshader->defaultparams) { ShaderParam ¶m = s.shader->detailshader->defaultparams[i]; if((name && param.name && !strcmp(name, param.name)) || (param.type==type && param.index==index)) return ¶m; } return NULL; } ShaderParam *findshaderparam(VSlot &s, const char *name, int type = -1, int index = -1) { loopv(s.params) { ShaderParam ¶m = s.params[i]; if((name && param.name && !strcmp(name, param.name)) || (param.type==type && param.index==index)) return ¶m; } return findshaderparam(*s.slot, name, type, index); } void resetslotshader() { curshader = NULL; curparams.shrink(0); } void setslotshader(Slot &s) { s.shader = curshader; if(!s.shader) { s.shader = stdworldshader; return; } loopv(curparams) s.params.add(curparams[i]); } static void linkslotshaderparams(vector ¶ms, Shader *sh, bool load) { if(sh) loopv(params) { int loc = -1; ShaderParam ¶m = params[i]; loopv(sh->defaultparams) { ShaderParam &dparam = sh->defaultparams[i]; if(param.name ? dparam.name==param.name : dparam.type==param.type && dparam.index==param.index) { if(memcmp(param.val, dparam.val, sizeof(param.val))) loc = i; break; } } param.loc = loc; } else if(load) loopv(params) params[i].loc = -1; } void linkslotshader(Slot &s, bool load) { if(!s.shader) return; if(load && !s.shader->detailshader) s.shader->fixdetailshader(); Shader *sh = s.shader->detailshader; linkslotshaderparams(s.params, sh, load); } void linkvslotshader(VSlot &s, bool load) { if(!s.slot->shader) return; Shader *sh = s.slot->shader->detailshader; linkslotshaderparams(s.params, sh, load); if(!sh) return; if(s.slot->texmask&(1<val[k], 0.0f, 1.0f); ShaderParam *pulseparam = findshaderparam(s, "pulseglowcolor"), *speedparam = findshaderparam(s, "pulseglowspeed"); if(pulseparam) loopk(3) s.pulseglowcolor[k] = clamp(pulseparam->val[k], 0.0f, 1.0f); if(speedparam) s.pulseglowspeed = speedparam->val[0]/1000.0f; } if(sh->type&SHADER_ENVMAP) { ShaderParam *envparam = findshaderparam(s, "envscale"); if(envparam) loopk(3) s.envscale[k] = clamp(envparam->val[k], 0.0f, 1.0f); } } void altshader(char *origname, char *altname) { Shader *orig = shaders.access(origname), *alt = shaders.access(altname); if(!orig || !alt) return; orig->altshader = alt; orig->fixdetailshader(false); } void fastshader(char *nice, char *fast, int *detail) { Shader *ns = shaders.access(nice), *fs = shaders.access(fast); if(!ns || !fs) return; loopi(min(*detail+1, MAXSHADERDETAIL)) ns->fastshader[i] = fs; ns->fixdetailshader(false); } COMMAND(shader, "isss"); COMMAND(variantshader, "isiss"); COMMAND(setshader, "s"); COMMAND(altshader, "ss"); COMMAND(fastshader, "ssi"); COMMAND(defershader, "iss"); ICOMMAND(forceshader, "s", (const char *name), useshaderbyname(name)); void isshaderdefined(char *name) { Shader *s = lookupshaderbyname(name); intret(s ? 1 : 0); } void isshadernative(char *name) { Shader *s = lookupshaderbyname(name); intret(s && s->native ? 1 : 0); } COMMAND(isshaderdefined, "s"); COMMAND(isshadernative, "s"); static hashset shaderparamnames(256); const char *getshaderparamname(const char *name) { const char **exists = shaderparamnames.access(name); if(exists) return *exists; name = newstring(name); shaderparamnames[name] = name; return name; } void addshaderparam(const char *name, int type, int n, float x, float y, float z, float w) { if((type==SHPARAM_VERTEX || type==SHPARAM_PIXEL) && (n<0 || n>=MAXSHADERPARAMS)) { conoutf(CON_ERROR, "shader param index must be 0..%d\n", MAXSHADERPARAMS-1); return; } if(name) name = getshaderparamname(name); loopv(curparams) { ShaderParam ¶m = curparams[i]; if(param.type == type && (name ? param.name==name : param.index == n)) { param.val[0] = x; param.val[1] = y; param.val[2] = z; param.val[3] = w; return; } } ShaderParam param = {name, type, n, -1, {x, y, z, w}}; curparams.add(param); } ICOMMAND(setvertexparam, "iffff", (int *n, float *x, float *y, float *z, float *w), addshaderparam(NULL, SHPARAM_VERTEX, *n, *x, *y, *z, *w)); ICOMMAND(setpixelparam, "iffff", (int *n, float *x, float *y, float *z, float *w), addshaderparam(NULL, SHPARAM_PIXEL, *n, *x, *y, *z, *w)); ICOMMAND(setuniformparam, "sffff", (char *name, float *x, float *y, float *z, float *w), addshaderparam(name, SHPARAM_UNIFORM, -1, *x, *y, *z, *w)); ICOMMAND(setshaderparam, "sffff", (char *name, float *x, float *y, float *z, float *w), addshaderparam(name, SHPARAM_LOOKUP, -1, *x, *y, *z, *w)); ICOMMAND(defvertexparam, "siffff", (char *name, int *n, float *x, float *y, float *z, float *w), addshaderparam(name[0] ? name : NULL, SHPARAM_VERTEX, *n, *x, *y, *z, *w)); ICOMMAND(defpixelparam, "siffff", (char *name, int *n, float *x, float *y, float *z, float *w), addshaderparam(name[0] ? name : NULL, SHPARAM_PIXEL, *n, *x, *y, *z, *w)); ICOMMAND(defuniformparam, "sffff", (char *name, float *x, float *y, float *z, float *w), addshaderparam(name, SHPARAM_UNIFORM, -1, *x, *y, *z, *w)); #define NUMPOSTFXBINDS 10 struct postfxtex { GLuint id; int scale, used; postfxtex() : id(0), scale(0), used(-1) {} }; vector postfxtexs; int postfxbinds[NUMPOSTFXBINDS]; GLuint postfxfb = 0; int postfxw = 0, postfxh = 0; struct postfxpass { Shader *shader; vec4 params; uint inputs, freeinputs; int outputbind, outputscale; postfxpass() : shader(NULL), inputs(1), freeinputs(1), outputbind(0), outputscale(0) {} }; vector postfxpasses; static int allocatepostfxtex(int scale) { loopv(postfxtexs) { postfxtex &t = postfxtexs[i]; if(t.scale==scale && t.used < 0) return i; } postfxtex &t = postfxtexs.add(); t.scale = scale; glGenTextures(1, &t.id); createtexture(t.id, max(screen->w>>scale, 1), max(screen->h>>scale, 1), NULL, 3, 1, GL_RGB, GL_TEXTURE_RECTANGLE_ARB); return postfxtexs.length()-1; } void cleanuppostfx(bool fullclean) { if(fullclean && postfxfb) { glDeleteFramebuffers_(1, &postfxfb); postfxfb = 0; } loopv(postfxtexs) glDeleteTextures(1, &postfxtexs[i].id); postfxtexs.shrink(0); postfxw = 0; postfxh = 0; } void renderpostfx() { if(postfxpasses.empty() || renderpath==R_FIXEDFUNCTION) return; if(postfxw != screen->w || postfxh != screen->h) { cleanuppostfx(false); postfxw = screen->w; postfxh = screen->h; } int binds[NUMPOSTFXBINDS]; loopi(NUMPOSTFXBINDS) binds[i] = -1; loopv(postfxtexs) postfxtexs[i].used = -1; binds[0] = allocatepostfxtex(0); postfxtexs[binds[0]].used = 0; glBindTexture(GL_TEXTURE_RECTANGLE_ARB, postfxtexs[binds[0]].id); glCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, screen->w, screen->h); if(hasFBO && postfxpasses.length() > 1) { if(!postfxfb) glGenFramebuffers_(1, &postfxfb); glBindFramebuffer_(GL_FRAMEBUFFER_EXT, postfxfb); } setenvparamf("millis", SHPARAM_VERTEX, 1, lastmillis/1000.0f, lastmillis/1000.0f, lastmillis/1000.0f); loopv(postfxpasses) { postfxpass &p = postfxpasses[i]; int tex = -1; if(!postfxpasses.inrange(i+1)) { if(hasFBO && postfxpasses.length() > 1) glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); } else { tex = allocatepostfxtex(p.outputscale); if(hasFBO) glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_RECTANGLE_ARB, postfxtexs[tex].id, 0); } int w = tex >= 0 ? max(screen->w>>postfxtexs[tex].scale, 1) : screen->w, h = tex >= 0 ? max(screen->h>>postfxtexs[tex].scale, 1) : screen->h; glViewport(0, 0, w, h); p.shader->set(); setlocalparamfv("params", SHPARAM_VERTEX, 0, p.params.v); setlocalparamfv("params", SHPARAM_PIXEL, 0, p.params.v); int tw = w, th = h, tmu = 0; loopj(NUMPOSTFXBINDS) if(p.inputs&(1<= 0) { if(!tmu) { tw = max(screen->w>>postfxtexs[binds[j]].scale, 1); th = max(screen->h>>postfxtexs[binds[j]].scale, 1); } else glActiveTexture_(GL_TEXTURE0_ARB + tmu); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, postfxtexs[binds[j]].id); ++tmu; } if(tmu) glActiveTexture_(GL_TEXTURE0_ARB); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f(-1, -1); glTexCoord2f(tw, 0); glVertex2f( 1, -1); glTexCoord2f(0, th); glVertex2f(-1, 1); glTexCoord2f(tw, th); glVertex2f( 1, 1); glEnd(); loopj(NUMPOSTFXBINDS) if(p.freeinputs&(1<= 0) { postfxtexs[binds[j]].used = -1; binds[j] = -1; } if(tex >= 0) { if(binds[p.outputbind] >= 0) postfxtexs[binds[p.outputbind]].used = -1; binds[p.outputbind] = tex; postfxtexs[tex].used = p.outputbind; if(!hasFBO) { glBindTexture(GL_TEXTURE_RECTANGLE_ARB, postfxtexs[tex].id); glCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, w, h); } } } } static bool addpostfx(const char *name, int outputbind, int outputscale, uint inputs, uint freeinputs, const vec4 ¶ms) { if(!hasTR || !*name) return false; Shader *s = useshaderbyname(name); if(!s) { conoutf(CON_ERROR, "no such postfx shader: %s", name); return false; } postfxpass &p = postfxpasses.add(); p.shader = s; p.outputbind = outputbind; p.outputscale = outputscale; p.inputs = inputs; p.freeinputs = freeinputs; p.params = params; return true; } void clearpostfx() { postfxpasses.shrink(0); cleanuppostfx(false); } COMMAND(clearpostfx, ""); ICOMMAND(addpostfx, "siisffff", (char *name, int *bind, int *scale, char *inputs, float *x, float *y, float *z, float *w), { int inputmask = inputs[0] ? 0 : 1; int freemask = inputs[0] ? 0 : 1; bool freeinputs = true; for(; *inputs; inputs++) if(isdigit(*inputs)) { inputmask |= 1<<(*inputs-'0'); if(freeinputs) freemask |= 1<<(*inputs-'0'); } else if(*inputs=='+') freeinputs = false; else if(*inputs=='-') freeinputs = true; inputmask &= (1<=maxtmus) return; tmu &t = tmus[n]; if(t.mode!=GL_MODULATE) { t.mode = GL_MODULATE; glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, t.mode); } if(t.rgb.scale != 1) { t.rgb.scale = 1; glTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, t.rgb.scale); } if(t.alpha.scale != 1) { t.alpha.scale = 1; glTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, t.alpha.scale); } } void scaletmu(int n, int rgbscale, int alphascale) { if(renderpath!=R_FIXEDFUNCTION || n>=maxtmus) return; tmu &t = tmus[n]; if(rgbscale && t.rgb.scale != rgbscale) { t.rgb.scale = rgbscale; glTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, t.rgb.scale); } if(alphascale && t.alpha.scale != alphascale) { t.alpha.scale = alphascale; glTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, t.alpha.scale); } } void colortmu(int n, float r, float g, float b, float a) { if(renderpath!=R_FIXEDFUNCTION || n>=maxtmus) return; tmu &t = tmus[n]; if(t.color[0] != r || t.color[1] != g || t.color[2] != b || t.color[3] != a) { t.color[0] = r; t.color[1] = g; t.color[2] = b; t.color[3] = a; glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, t.color); } } void committmufunc(GLenum mode, bool rgb, tmufunc &dst, tmufunc &src) { if(dst.combine!=src.combine) glTexEnvi(GL_TEXTURE_ENV, rgb ? GL_COMBINE_RGB_ARB : GL_COMBINE_ALPHA_ARB, src.combine); loopi(3) { if(dst.sources[i]!=src.sources[i]) glTexEnvi(GL_TEXTURE_ENV, (rgb ? GL_SOURCE0_RGB_ARB : GL_SOURCE0_ALPHA_ARB)+i, src.sources[i]); if(dst.ops[i]!=src.ops[i]) glTexEnvi(GL_TEXTURE_ENV, (rgb ? GL_OPERAND0_RGB_ARB : GL_OPERAND0_ALPHA_ARB)+i, src.ops[i]); } if(mode==GL_COMBINE4_NV) { if(dst.sources[3]!=src.sources[3]) glTexEnvi(GL_TEXTURE_ENV, rgb ? GL_SOURCE3_RGB_NV : GL_SOURCE3_ALPHA_NV, src.sources[3]); if(dst.ops[3]!=src.ops[3]) glTexEnvi(GL_TEXTURE_ENV, rgb ? GL_OPERAND3_RGB_NV : GL_OPERAND3_ALPHA_NV, src.ops[3]); } if(dst.scale!=src.scale) glTexEnvi(GL_TEXTURE_ENV, rgb ? GL_RGB_SCALE_ARB : GL_ALPHA_SCALE, src.scale); dst = src; } void setuptmu(int n, const char *rgbfunc, const char *alphafunc) { if(renderpath!=R_FIXEDFUNCTION || n>=maxtmus) return; static tmu init = INITTMU; tmu f = tmus[n]; f.mode = GL_COMBINE_ARB; if(rgbfunc) parsetmufunc(f, f.rgb, rgbfunc); else f.rgb = init.rgb; if(alphafunc) parsetmufunc(f, f.alpha, alphafunc); else f.alpha = init.alpha; tmu &t = tmus[n]; if(t.mode!=f.mode) { t.mode = f.mode; glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, t.mode); } committmufunc(f.mode, true, t.rgb, f.rgb); committmufunc(f.mode, false, t.alpha, f.alpha); } VAR(nolights, 1, 0, 0); VAR(nowater, 1, 0, 0); VAR(nomasks, 1, 0, 0); void inittmus() { if(hasTE && hasMT) { GLint val; glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &val); maxtmus = max(1, min(MAXTMUS, int(val))); loopi(maxtmus) { glActiveTexture_(GL_TEXTURE0_ARB+i); resettmu(i); } glActiveTexture_(GL_TEXTURE0_ARB); } else if(hasTE) { maxtmus = 1; resettmu(0); } if(renderpath==R_FIXEDFUNCTION) { if(maxtmus<4) caustics = 0; if(maxtmus<2) { nolights = nowater = nomasks = 1; extern int lightmodels; lightmodels = 0; } } } void cleanupshaders() { cleanuppostfx(true); defaultshader = notextureshader = nocolorshader = foggedshader = foggednotextureshader = NULL; enumerate(shaders, Shader, s, s.cleanup()); Shader::lastshader = NULL; if(renderpath==R_ASMSHADER || renderpath==R_ASMGLSLANG) { glBindProgramARB_(GL_VERTEX_PROGRAM_ARB, 0); glBindProgramARB_(GL_FRAGMENT_PROGRAM_ARB, 0); glDisable(GL_VERTEX_PROGRAM_ARB); glDisable(GL_FRAGMENT_PROGRAM_ARB); } if(renderpath==R_GLSLANG || renderpath==R_ASMGLSLANG) glUseProgram_(0); loopi(RESERVEDSHADERPARAMS + MAXSHADERPARAMS) { vertexparamstate[i].dirty = ShaderParamState::INVALID; pixelparamstate[i].dirty = ShaderParamState::INVALID; } tmu invalidtmu = INVALIDTMU; loopi(MAXTMUS) tmus[i] = invalidtmu; } void reloadshaders() { identflags &= ~IDF_PERSIST; loadshaders(); identflags |= IDF_PERSIST; if(renderpath==R_FIXEDFUNCTION) return; linkslotshaders(); enumerate(shaders, Shader, s, { if(!s.standard && !(s.type&(SHADER_DEFERRED|SHADER_INVALID)) && !s.variantshader) { defformatstring(info)("shader %s", s.name); renderprogress(0.0, info); if(!s.compile()) s.cleanup(true); loopi(MAXVARIANTROWS) loopvj(s.variants[i]) { Shader *v = s.variants[i][j]; if((v->reusevs && v->reusevs->type&SHADER_INVALID) || (v->reuseps && v->reuseps->type&SHADER_INVALID) || !v->compile()) v->cleanup(true); } } if(s.forced && !s.detailshader) s.fixdetailshader(); }); } void setupblurkernel(int radius, float sigma, float *weights, float *offsets) { if(radius<1 || radius>MAXBLURRADIUS) return; sigma *= 2*radius; float total = 1.0f/sigma; weights[0] = total; offsets[0] = 0; // rely on bilinear filtering to sample 2 pixels at once // transforms a*X + b*Y into (u+v)*[X*u/(u+v) + Y*(1 - u/(u+v))] loopi(radius) { float weight1 = exp(-((2*i)*(2*i)) / (2*sigma*sigma)) / sigma, weight2 = exp(-((2*i+1)*(2*i+1)) / (2*sigma*sigma)) / sigma, scale = weight1 + weight2, offset = 2*i+1 + weight2 / scale; weights[i+1] = scale; offsets[i+1] = offset; total += 2*scale; } loopi(radius+1) weights[i] /= total; for(int i = radius+1; i <= MAXBLURRADIUS; i++) weights[i] = offsets[i] = 0; } void setblurshader(int pass, int size, int radius, float *weights, float *offsets, GLenum target) { if(radius<1 || radius>MAXBLURRADIUS) return; static Shader *blurshader[7][2] = { { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL } }, *blurrectshader[7][2] = { { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL }, { NULL, NULL } }; Shader *&s = (target == GL_TEXTURE_RECTANGLE_ARB ? blurrectshader : blurshader)[radius-1][pass]; if(!s) { defformatstring(name)("blur%c%d%s", 'x'+pass, radius, target == GL_TEXTURE_RECTANGLE_ARB ? "rect" : ""); s = lookupshaderbyname(name); } s->set(); setlocalparamfv("weights", SHPARAM_PIXEL, 0, weights); setlocalparamfv("weights2", SHPARAM_PIXEL, 2, &weights[4]); setlocalparamf("offsets", SHPARAM_VERTEX, 1, pass==0 ? offsets[1]/size : offsets[0]/size, pass==1 ? offsets[1]/size : offsets[0]/size, (offsets[2] - offsets[1])/size, (offsets[3] - offsets[2])/size); loopk(4) { static const char *names[4] = { "offset4", "offset5", "offset6", "offset7" }; setlocalparamf(names[k], SHPARAM_PIXEL, 3+k, pass==0 ? offsets[4+k]/size : offsets[0]/size, pass==1 ? offsets[4+k]/size : offsets[0]/size, 0, 0); } } sauerbraten-0.0.20130203.dfsg/engine/serverbrowser.cpp0000644000175000017500000004712612075052370022273 0ustar vincentvincent// serverbrowser.cpp: eihrul's concurrent resolver, and server browser window management #include "engine.h" #include "SDL_thread.h" struct resolverthread { SDL_Thread *thread; const char *query; int starttime; }; struct resolverresult { const char *query; ENetAddress address; }; vector resolverthreads; vector resolverqueries; vector resolverresults; SDL_mutex *resolvermutex; SDL_cond *querycond, *resultcond; #define RESOLVERTHREADS 2 #define RESOLVERLIMIT 3000 int resolverloop(void * data) { resolverthread *rt = (resolverthread *)data; SDL_LockMutex(resolvermutex); SDL_Thread *thread = rt->thread; SDL_UnlockMutex(resolvermutex); if(!thread || SDL_GetThreadID(thread) != SDL_ThreadID()) return 0; while(thread == rt->thread) { SDL_LockMutex(resolvermutex); while(resolverqueries.empty()) SDL_CondWait(querycond, resolvermutex); rt->query = resolverqueries.pop(); rt->starttime = totalmillis; SDL_UnlockMutex(resolvermutex); ENetAddress address = { ENET_HOST_ANY, ENET_PORT_ANY }; enet_address_set_host(&address, rt->query); SDL_LockMutex(resolvermutex); if(rt->query && thread == rt->thread) { resolverresult &rr = resolverresults.add(); rr.query = rt->query; rr.address = address; rt->query = NULL; rt->starttime = 0; SDL_CondSignal(resultcond); } SDL_UnlockMutex(resolvermutex); } return 0; } void resolverinit() { resolvermutex = SDL_CreateMutex(); querycond = SDL_CreateCond(); resultcond = SDL_CreateCond(); SDL_LockMutex(resolvermutex); loopi(RESOLVERTHREADS) { resolverthread &rt = resolverthreads.add(); rt.query = NULL; rt.starttime = 0; rt.thread = SDL_CreateThread(resolverloop, &rt); } SDL_UnlockMutex(resolvermutex); } void resolverstop(resolverthread &rt) { SDL_LockMutex(resolvermutex); if(rt.query) { #ifndef __APPLE__ SDL_KillThread(rt.thread); #endif rt.thread = SDL_CreateThread(resolverloop, &rt); } rt.query = NULL; rt.starttime = 0; SDL_UnlockMutex(resolvermutex); } void resolverclear() { if(resolverthreads.empty()) return; SDL_LockMutex(resolvermutex); resolverqueries.shrink(0); resolverresults.shrink(0); loopv(resolverthreads) { resolverthread &rt = resolverthreads[i]; resolverstop(rt); } SDL_UnlockMutex(resolvermutex); } void resolverquery(const char *name) { if(resolverthreads.empty()) resolverinit(); SDL_LockMutex(resolvermutex); resolverqueries.add(name); SDL_CondSignal(querycond); SDL_UnlockMutex(resolvermutex); } bool resolvercheck(const char **name, ENetAddress *address) { bool resolved = false; SDL_LockMutex(resolvermutex); if(!resolverresults.empty()) { resolverresult &rr = resolverresults.pop(); *name = rr.query; address->host = rr.address.host; resolved = true; } else loopv(resolverthreads) { resolverthread &rt = resolverthreads[i]; if(rt.query && totalmillis - rt.starttime > RESOLVERLIMIT) { resolverstop(rt); *name = rt.query; resolved = true; } } SDL_UnlockMutex(resolvermutex); return resolved; } bool resolverwait(const char *name, ENetAddress *address) { if(resolverthreads.empty()) resolverinit(); defformatstring(text)("resolving %s... (esc to abort)", name); renderprogress(0, text); SDL_LockMutex(resolvermutex); resolverqueries.add(name); SDL_CondSignal(querycond); int starttime = SDL_GetTicks(), timeout = 0; bool resolved = false; for(;;) { SDL_CondWaitTimeout(resultcond, resolvermutex, 250); loopv(resolverresults) if(resolverresults[i].query == name) { address->host = resolverresults[i].address.host; resolverresults.remove(i); resolved = true; break; } if(resolved) break; timeout = SDL_GetTicks() - starttime; renderprogress(min(float(timeout)/RESOLVERLIMIT, 1.0f), text); if(interceptkey(SDLK_ESCAPE)) timeout = RESOLVERLIMIT + 1; if(timeout > RESOLVERLIMIT) break; } if(!resolved && timeout > RESOLVERLIMIT) { loopv(resolverthreads) { resolverthread &rt = resolverthreads[i]; if(rt.query == name) { resolverstop(rt); break; } } } SDL_UnlockMutex(resolvermutex); return resolved; } SDL_Thread *connthread = NULL; SDL_mutex *connmutex = NULL; SDL_cond *conncond = NULL; struct connectdata { ENetSocket sock; ENetAddress address; int result; }; // do this in a thread to prevent timeouts // could set timeouts on sockets, but this is more reliable and gives more control int connectthread(void *data) { SDL_LockMutex(connmutex); if(!connthread || SDL_GetThreadID(connthread) != SDL_ThreadID()) { SDL_UnlockMutex(connmutex); return 0; } connectdata cd = *(connectdata *)data; SDL_UnlockMutex(connmutex); int result = enet_socket_connect(cd.sock, &cd.address); SDL_LockMutex(connmutex); if(!connthread || SDL_GetThreadID(connthread) != SDL_ThreadID()) { enet_socket_destroy(cd.sock); SDL_UnlockMutex(connmutex); return 0; } ((connectdata *)data)->result = result; SDL_CondSignal(conncond); SDL_UnlockMutex(connmutex); return 0; } #define CONNLIMIT 20000 int connectwithtimeout(ENetSocket sock, const char *hostname, const ENetAddress &address) { defformatstring(text)("connecting to %s... (esc to abort)", hostname); renderprogress(0, text); if(!connmutex) connmutex = SDL_CreateMutex(); if(!conncond) conncond = SDL_CreateCond(); SDL_LockMutex(connmutex); connectdata cd = { sock, address, -1 }; connthread = SDL_CreateThread(connectthread, &cd); int starttime = SDL_GetTicks(), timeout = 0; for(;;) { if(!SDL_CondWaitTimeout(conncond, connmutex, 250)) { if(cd.result<0) enet_socket_destroy(sock); break; } timeout = SDL_GetTicks() - starttime; renderprogress(min(float(timeout)/CONNLIMIT, 1.0f), text); if(interceptkey(SDLK_ESCAPE)) timeout = CONNLIMIT + 1; if(timeout > CONNLIMIT) break; } /* thread will actually timeout eventually if its still trying to connect * so just leave it (and let it destroy socket) instead of causing problems on some platforms by killing it */ connthread = NULL; SDL_UnlockMutex(connmutex); return cd.result; } enum { UNRESOLVED = 0, RESOLVING, RESOLVED }; struct serverinfo { enum { WAITING = INT_MAX, MAXPINGS = 3 }; string name, map, sdesc; int port, numplayers, resolved, ping, lastping, nextping; int pings[MAXPINGS]; vector attr; ENetAddress address; bool keep; const char *password; serverinfo() : port(-1), numplayers(0), resolved(UNRESOLVED), keep(false), password(NULL) { name[0] = map[0] = sdesc[0] = '\0'; clearpings(); } ~serverinfo() { DELETEA(password); } void clearpings() { ping = WAITING; loopk(MAXPINGS) pings[k] = WAITING; nextping = 0; lastping = -1; } void cleanup() { clearpings(); attr.setsize(0); numplayers = 0; } void reset() { lastping = -1; } void checkdecay(int decay) { if(lastping >= 0 && totalmillis - lastping >= decay) cleanup(); if(lastping < 0) lastping = totalmillis; } void calcping() { int numpings = 0, totalpings = 0; loopk(MAXPINGS) if(pings[k] != WAITING) { totalpings += pings[k]; numpings++; } ping = numpings ? totalpings/numpings : WAITING; } void addping(int rtt, int millis) { if(millis >= lastping) lastping = -1; pings[nextping] = rtt; nextping = (nextping+1)%MAXPINGS; calcping(); } static bool compare(serverinfo *a, serverinfo *b) { bool ac = server::servercompatible(a->name, a->sdesc, a->map, a->ping, a->attr, a->numplayers), bc = server::servercompatible(b->name, b->sdesc, b->map, b->ping, b->attr, b->numplayers); if(ac > bc) return true; if(bc > ac) return false; if(a->keep > b->keep) return true; if(a->keep < b->keep) return false; if(a->numplayers < b->numplayers) return false; if(a->numplayers > b->numplayers) return true; if(a->ping > b->ping) return false; if(a->ping < b->ping) return true; int cmp = strcmp(a->name, b->name); if(cmp != 0) return cmp < 0; if(a->port < b->port) return true; if(a->port > b->port) return false; return false; } }; vector servers; ENetSocket pingsock = ENET_SOCKET_NULL; int lastinfo = 0; static serverinfo *newserver(const char *name, int port, uint ip = ENET_HOST_ANY) { serverinfo *si = new serverinfo; si->address.host = ip; si->address.port = server::serverinfoport(port); if(ip!=ENET_HOST_ANY) si->resolved = RESOLVED; si->port = port; if(name) copystring(si->name, name); else if(ip==ENET_HOST_ANY || enet_address_get_host_ip(&si->address, si->name, sizeof(si->name)) < 0) { delete si; return NULL; } servers.add(si); return si; } void addserver(const char *name, int port, const char *password, bool keep) { if(port <= 0) port = server::serverport(); loopv(servers) { serverinfo *s = servers[i]; if(strcmp(s->name, name) || s->port != port) continue; if(password && (!s->password || strcmp(s->password, password))) { DELETEA(s->password); s->password = newstring(password); } if(keep && !s->keep) s->keep = true; return; } serverinfo *s = newserver(name, port); if(!s) return; if(password) s->password = newstring(password); s->keep = keep; } VARP(searchlan, 0, 0, 1); VARP(servpingrate, 1000, 5000, 60000); VARP(servpingdecay, 1000, 15000, 60000); VARP(maxservpings, 0, 10, 1000); void pingservers() { if(pingsock == ENET_SOCKET_NULL) { pingsock = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM); if(pingsock == ENET_SOCKET_NULL) { lastinfo = totalmillis; return; } enet_socket_set_option(pingsock, ENET_SOCKOPT_NONBLOCK, 1); enet_socket_set_option(pingsock, ENET_SOCKOPT_BROADCAST, 1); } ENetBuffer buf; uchar ping[MAXTRANS]; ucharbuf p(ping, sizeof(ping)); putint(p, totalmillis); static int lastping = 0; if(lastping >= servers.length()) lastping = 0; loopi(maxservpings ? min(servers.length(), maxservpings) : servers.length()) { serverinfo &si = *servers[lastping]; if(++lastping >= servers.length()) lastping = 0; if(si.address.host == ENET_HOST_ANY) continue; buf.data = ping; buf.dataLength = p.length(); enet_socket_send(pingsock, &si.address, &buf, 1); si.checkdecay(servpingdecay); } if(searchlan) { ENetAddress address; address.host = ENET_HOST_BROADCAST; address.port = server::laninfoport(); buf.data = ping; buf.dataLength = p.length(); enet_socket_send(pingsock, &address, &buf, 1); } lastinfo = totalmillis; } void checkresolver() { int resolving = 0; loopv(servers) { serverinfo &si = *servers[i]; if(si.resolved == RESOLVED) continue; if(si.address.host == ENET_HOST_ANY) { if(si.resolved == UNRESOLVED) { si.resolved = RESOLVING; resolverquery(si.name); } resolving++; } } if(!resolving) return; const char *name = NULL; for(;;) { ENetAddress addr = { ENET_HOST_ANY, ENET_PORT_ANY }; if(!resolvercheck(&name, &addr)) break; loopv(servers) { serverinfo &si = *servers[i]; if(name == si.name) { si.resolved = RESOLVED; si.address.host = addr.host; break; } } } } static int lastreset = 0; void checkpings() { if(pingsock==ENET_SOCKET_NULL) return; enet_uint32 events = ENET_SOCKET_WAIT_RECEIVE; ENetBuffer buf; ENetAddress addr; uchar ping[MAXTRANS]; char text[MAXTRANS]; buf.data = ping; buf.dataLength = sizeof(ping); while(enet_socket_wait(pingsock, &events, 0) >= 0 && events) { int len = enet_socket_receive(pingsock, &addr, &buf, 1); if(len <= 0) return; serverinfo *si = NULL; loopv(servers) if(addr.host == servers[i]->address.host && addr.port == servers[i]->address.port) { si = servers[i]; break; } if(!si && searchlan) si = newserver(NULL, server::serverport(addr.port), addr.host); if(!si) continue; ucharbuf p(ping, len); int millis = getint(p), rtt = clamp(totalmillis - millis, 0, min(servpingdecay, totalmillis)); if(millis >= lastreset && rtt < servpingdecay) si->addping(rtt, millis); si->numplayers = getint(p); int numattr = getint(p); si->attr.setsize(0); loopj(numattr) { int attr = getint(p); if(p.overread()) break; si->attr.add(attr); } getstring(text, p); filtertext(si->map, text, false); getstring(text, p); filtertext(si->sdesc, text); } } void sortservers() { servers.sort(serverinfo::compare); } COMMAND(sortservers, ""); VARP(autosortservers, 0, 1, 1); VARP(autoupdateservers, 0, 1, 1); void refreshservers() { static int lastrefresh = 0; if(lastrefresh==totalmillis) return; if(totalmillis - lastrefresh > 1000) { loopv(servers) servers[i]->reset(); lastreset = totalmillis; } lastrefresh = totalmillis; checkresolver(); checkpings(); if(totalmillis - lastinfo >= servpingrate/(maxservpings ? max(1, (servers.length() + maxservpings - 1) / maxservpings) : 1)) pingservers(); if(autosortservers) sortservers(); } serverinfo *selectedserver = NULL; const char *showservers(g3d_gui *cgui, uint *header, int pagemin, int pagemax) { refreshservers(); if(servers.empty()) { if(header) execute(header); return NULL; } serverinfo *sc = NULL; for(int start = 0; start < servers.length();) { if(start > 0) cgui->tab(); if(header) execute(header); int end = servers.length(); cgui->pushlist(); loopi(10) { if(!game::serverinfostartcolumn(cgui, i)) break; for(int j = start; j < end; j++) { if(!i && j+1 - start >= pagemin && (j+1 - start >= pagemax || cgui->shouldtab())) { end = j; break; } serverinfo &si = *servers[j]; const char *sdesc = si.sdesc; if(si.address.host == ENET_HOST_ANY) sdesc = "[unknown host]"; else if(si.ping == serverinfo::WAITING) sdesc = "[waiting for response]"; if(game::serverinfoentry(cgui, i, si.name, si.port, sdesc, si.map, sdesc == si.sdesc ? si.ping : -1, si.attr, si.numplayers)) sc = &si; } game::serverinfoendcolumn(cgui, i); } cgui->poplist(); start = end; } if(selectedserver || !sc) return NULL; selectedserver = sc; return "connectselected"; } void connectselected() { if(!selectedserver) return; connectserv(selectedserver->name, selectedserver->port, selectedserver->password); selectedserver = NULL; } COMMAND(connectselected, ""); void clearservers(bool full = false) { resolverclear(); if(full) servers.deletecontents(); else loopvrev(servers) if(!servers[i]->keep) delete servers.remove(i); selectedserver = NULL; } #define RETRIEVELIMIT 20000 void retrieveservers(vector &data) { ENetSocket sock = connectmaster(); if(sock == ENET_SOCKET_NULL) return; extern char *mastername; defformatstring(text)("retrieving servers from %s... (esc to abort)", mastername); renderprogress(0, text); int starttime = SDL_GetTicks(), timeout = 0; const char *req = "list\n"; int reqlen = strlen(req); ENetBuffer buf; while(reqlen > 0) { enet_uint32 events = ENET_SOCKET_WAIT_SEND; if(enet_socket_wait(sock, &events, 250) >= 0 && events) { buf.data = (void *)req; buf.dataLength = reqlen; int sent = enet_socket_send(sock, NULL, &buf, 1); if(sent < 0) break; req += sent; reqlen -= sent; if(reqlen <= 0) break; } timeout = SDL_GetTicks() - starttime; renderprogress(min(float(timeout)/RETRIEVELIMIT, 1.0f), text); if(interceptkey(SDLK_ESCAPE)) timeout = RETRIEVELIMIT + 1; if(timeout > RETRIEVELIMIT) break; } if(reqlen <= 0) for(;;) { enet_uint32 events = ENET_SOCKET_WAIT_RECEIVE; if(enet_socket_wait(sock, &events, 250) >= 0 && events) { if(data.length() >= data.capacity()) data.reserve(4096); buf.data = data.getbuf() + data.length(); buf.dataLength = data.capacity() - data.length(); int recv = enet_socket_receive(sock, NULL, &buf, 1); if(recv <= 0) break; data.advance(recv); } timeout = SDL_GetTicks() - starttime; renderprogress(min(float(timeout)/RETRIEVELIMIT, 1.0f), text); if(interceptkey(SDLK_ESCAPE)) timeout = RETRIEVELIMIT + 1; if(timeout > RETRIEVELIMIT) break; } if(data.length()) data.add('\0'); enet_socket_destroy(sock); } bool updatedservers = false; void updatefrommaster() { vector data; retrieveservers(data); if(data.empty()) conoutf("master server not replying"); else { clearservers(); execute(data.getbuf()); } refreshservers(); updatedservers = true; } void initservers() { selectedserver = NULL; if(autoupdateservers && !updatedservers) updatefrommaster(); } ICOMMAND(addserver, "sis", (const char *name, int *port, const char *password), addserver(name, *port, password[0] ? password : NULL)); ICOMMAND(keepserver, "sis", (const char *name, int *port, const char *password), addserver(name, *port, password[0] ? password : NULL, true)); ICOMMAND(clearservers, "i", (int *full), clearservers(*full!=0)); COMMAND(updatefrommaster, ""); COMMAND(initservers, ""); void writeservercfg() { if(!game::savedservers()) return; stream *f = openutf8file(path(game::savedservers(), true), "w"); if(!f) return; int kept = 0; loopv(servers) { serverinfo *s = servers[i]; if(s->keep) { if(!kept) f->printf("// servers that should never be cleared from the server list\n\n"); if(s->password) f->printf("keepserver %s %d %s\n", escapeid(s->name), s->port, escapestring(s->password)); else f->printf("keepserver %s %d\n", escapeid(s->name), s->port); kept++; } } if(kept) f->printf("\n"); f->printf("// servers connected to are added here automatically\n\n"); loopv(servers) { serverinfo *s = servers[i]; if(!s->keep) { if(s->password) f->printf("addserver %s %d %s\n", escapeid(s->name), s->port, escapestring(s->password)); else f->printf("addserver %s %d\n", escapeid(s->name), s->port); } } delete f; } sauerbraten-0.0.20130203.dfsg/engine/iqm.h0000644000175000017500000003474512072642735017626 0ustar vincentvincentstruct iqm; struct iqmheader { char magic[16]; uint version; uint filesize; uint flags; uint num_text, ofs_text; uint num_meshes, ofs_meshes; uint num_vertexarrays, num_vertexes, ofs_vertexarrays; uint num_triangles, ofs_triangles, ofs_adjacency; uint num_joints, ofs_joints; uint num_poses, ofs_poses; uint num_anims, ofs_anims; uint num_frames, num_framechannels, ofs_frames, ofs_bounds; uint num_comment, ofs_comment; uint num_extensions, ofs_extensions; }; struct iqmmesh { uint name; uint material; uint first_vertex, num_vertexes; uint first_triangle, num_triangles; }; enum { IQM_POSITION = 0, IQM_TEXCOORD = 1, IQM_NORMAL = 2, IQM_TANGENT = 3, IQM_BLENDINDEXES = 4, IQM_BLENDWEIGHTS = 5, IQM_COLOR = 6, IQM_CUSTOM = 0x10 }; enum { IQM_BYTE = 0, IQM_UBYTE = 1, IQM_SHORT = 2, IQM_USHORT = 3, IQM_INT = 4, IQM_UINT = 5, IQM_HALF = 6, IQM_FLOAT = 7, IQM_DOUBLE = 8, }; struct iqmtriangle { uint vertex[3]; }; struct iqmjoint { uint name; int parent; vec pos; quat orient; vec size; }; struct iqmpose { int parent; uint mask; vec offsetpos; vec4 offsetorient; vec offsetsize; vec scalepos; vec4 scaleorient; vec scalesize; }; struct iqmanim { uint name; uint first_frame, num_frames; float framerate; uint flags; }; struct iqmvertexarray { uint type; uint flags; uint format; uint size; uint offset; }; struct iqm : skelmodel, skelloader { iqm(const char *name) : skelmodel(name) {} static const char *formatname() { return "iqm"; } int type() const { return MDL_IQM; } struct iqmmeshgroup : skelmeshgroup { iqmmeshgroup() { } bool loadiqmmeshes(const char *filename, const iqmheader &hdr, uchar *buf) { lilswap((uint *)&buf[hdr.ofs_vertexarrays], hdr.num_vertexarrays*sizeof(iqmvertexarray)/sizeof(uint)); lilswap((uint *)&buf[hdr.ofs_triangles], hdr.num_triangles*sizeof(iqmtriangle)/sizeof(uint)); lilswap((uint *)&buf[hdr.ofs_meshes], hdr.num_meshes*sizeof(iqmmesh)/sizeof(uint)); lilswap((uint *)&buf[hdr.ofs_joints], hdr.num_joints*sizeof(iqmjoint)/sizeof(uint)); const char *str = hdr.ofs_text ? (char *)&buf[hdr.ofs_text] : ""; float *vpos = NULL, *vnorm = NULL, *vtan = NULL, *vtc = NULL; uchar *vindex = NULL, *vweight = NULL; iqmvertexarray *vas = (iqmvertexarray *)&buf[hdr.ofs_vertexarrays]; loopi(hdr.num_vertexarrays) { iqmvertexarray &va = vas[i]; switch(va.type) { case IQM_POSITION: if(va.format != IQM_FLOAT || va.size != 3) return false; vpos = (float *)&buf[va.offset]; lilswap(vpos, 3*hdr.num_vertexes); break; case IQM_NORMAL: if(va.format != IQM_FLOAT || va.size != 3) return false; vnorm = (float *)&buf[va.offset]; lilswap(vnorm, 3*hdr.num_vertexes); break; case IQM_TANGENT: if(va.format != IQM_FLOAT || va.size != 4) return false; vtan = (float *)&buf[va.offset]; lilswap(vtan, 4*hdr.num_vertexes); break; case IQM_TEXCOORD: if(va.format != IQM_FLOAT || va.size != 2) return false; vtc = (float *)&buf[va.offset]; lilswap(vtc, 2*hdr.num_vertexes); break; case IQM_BLENDINDEXES: if(va.format != IQM_UBYTE || va.size != 4) return false; vindex = (uchar *)&buf[va.offset]; break; case IQM_BLENDWEIGHTS: if(va.format != IQM_UBYTE || va.size != 4) return false; vweight = (uchar *)&buf[va.offset]; break; } } iqmtriangle *tris = (iqmtriangle *)&buf[hdr.ofs_triangles]; iqmmesh *imeshes = (iqmmesh *)&buf[hdr.ofs_meshes]; iqmjoint *joints = (iqmjoint *)&buf[hdr.ofs_joints]; if(hdr.num_joints) { if(skel->numbones <= 0) { skel->numbones = hdr.num_joints; skel->bones = new boneinfo[skel->numbones]; loopi(hdr.num_joints) { iqmjoint &j = joints[i]; boneinfo &b = skel->bones[i]; if(!b.name) b.name = newstring(&str[j.name]); b.parent = j.parent; if(skel->shared <= 1) { j.pos.y = -j.pos.y; j.orient.x = -j.orient.x; j.orient.z = -j.orient.z; j.orient.normalize(); b.base = dualquat(j.orient, j.pos); if(b.parent >= 0) b.base.mul(skel->bones[b.parent].base, dualquat(b.base)); (b.invbase = b.base).invert(); } } } if(skel->shared <= 1) skel->linkchildren(); } loopi(hdr.num_meshes) { iqmmesh &im = imeshes[i]; skelmesh *m = new skelmesh; m->group = this; meshes.add(m); m->name = newstring(&str[im.name]); m->numverts = im.num_vertexes; if(m->numverts) { m->verts = new vert[m->numverts]; if(vtan) m->bumpverts = new bumpvert[m->numverts]; } loopj(im.num_vertexes) { int fj = j + im.first_vertex; vert &v = m->verts[j]; loopk(3) v.pos[k] = vpos[3*fj + k]; v.pos.y = -v.pos.y; v.u = vtc[2*fj + 0]; v.v = vtc[2*fj + 1]; if(vnorm) { loopk(3) v.norm[k] = vnorm[3*fj + k]; v.norm.y = -v.norm.y; if(vtan) { bumpvert &bv = m->bumpverts[j]; loopk(3) bv.tangent[k] = vtan[4*fj + k]; bv.tangent.y = -bv.tangent.y; bv.bitangent = vtan[4*fj + 3]; } } blendcombo c; int sorted = 0; if(vindex && vweight) loopk(4) sorted = c.addweight(sorted, vweight[4*fj + k], vindex[4*fj + k]); c.finalize(sorted); v.blend = m->addblendcombo(c); } m->numtris = im.num_triangles; if(m->numtris) m->tris = new tri[m->numtris]; loopj(im.num_triangles) { int fj = j + im.first_triangle; loopk(3) m->tris[j].vert[k] = tris[fj].vertex[k] - im.first_vertex; } if(!m->numtris || !m->numverts) { conoutf("empty mesh in %s", filename); meshes.removeobj(m); delete m; } } sortblendcombos(); return true; } bool loadiqmanims(const char *filename, const iqmheader &hdr, uchar *buf) { lilswap((uint *)&buf[hdr.ofs_poses], hdr.num_poses*sizeof(iqmpose)/sizeof(uint)); lilswap((uint *)&buf[hdr.ofs_anims], hdr.num_anims*sizeof(iqmanim)/sizeof(uint)); lilswap((ushort *)&buf[hdr.ofs_frames], hdr.num_frames*hdr.num_framechannels); const char *str = hdr.ofs_text ? (char *)&buf[hdr.ofs_text] : ""; iqmpose *poses = (iqmpose *)&buf[hdr.ofs_poses]; iqmanim *anims = (iqmanim *)&buf[hdr.ofs_anims]; ushort *frames = (ushort *)&buf[hdr.ofs_frames]; loopi(hdr.num_anims) { iqmanim &a = anims[i]; string name; copystring(name, filename); concatstring(name, ":"); concatstring(name, &str[a.name]); skelanimspec *sa = skel->findskelanim(name); if(sa) continue; sa = &skel->addskelanim(name); sa->frame = skel->numframes; sa->range = a.num_frames; dualquat *animbones = new dualquat[(skel->numframes+a.num_frames)*skel->numbones]; if(skel->bones) { memcpy(animbones, skel->framebones, skel->numframes*skel->numbones*sizeof(dualquat)); delete[] skel->framebones; } skel->framebones = animbones; animbones += skel->numframes*skel->numbones; skel->numframes += a.num_frames; ushort *animdata = &frames[a.first_frame*hdr.num_framechannels]; loopj(a.num_frames) { dualquat *frame = &animbones[j*skel->numbones]; loopk(skel->numbones) { iqmpose &p = poses[k]; vec pos; quat orient; pos.x = p.offsetpos.x; if(p.mask&0x01) pos.x += *animdata++ * p.scalepos.x; pos.y = -p.offsetpos.y; if(p.mask&0x02) pos.y -= *animdata++ * p.scalepos.y; pos.z = p.offsetpos.z; if(p.mask&0x04) pos.z += *animdata++ * p.scalepos.z; orient.x = -p.offsetorient.x; if(p.mask&0x08) orient.x -= *animdata++ * p.scaleorient.x; orient.y = p.offsetorient.y; if(p.mask&0x10) orient.y += *animdata++ * p.scaleorient.y; orient.z = -p.offsetorient.z; if(p.mask&0x20) orient.z -= *animdata++ * p.scaleorient.z; orient.w = p.offsetorient.w; if(p.mask&0x40) orient.w += *animdata++ * p.scaleorient.w; orient.normalize(); if(p.mask&0x380) { if(p.mask&0x80) animdata++; if(p.mask&0x100) animdata++; if(p.mask&0x200) animdata++; } frame[k] = dualquat(orient, pos); if(adjustments.inrange(k)) adjustments[k].adjust(frame[k]); boneinfo &b = skel->bones[k]; frame[k].mul(b.invbase); if(b.parent >= 0) frame[k].mul(skel->bones[b.parent].base, dualquat(frame[k])); frame[k].fixantipodal(skel->framebones[k]); } } } return true; } bool loadiqm(const char *filename, bool doloadmesh, bool doloadanim) { stream *f = openfile(filename, "rb"); if(!f) return false; uchar *buf = NULL; iqmheader hdr; if(f->read(&hdr, sizeof(hdr)) != sizeof(hdr) || memcmp(hdr.magic, "INTERQUAKEMODEL", sizeof(hdr.magic))) goto error; lilswap(&hdr.version, (sizeof(hdr) - sizeof(hdr.magic))/sizeof(uint)); if(hdr.version != 2) goto error; if(hdr.filesize > (16<<20)) goto error; // sanity check... don't load files bigger than 16 MB buf = new uchar[hdr.filesize]; if(f->read(buf + sizeof(hdr), hdr.filesize - sizeof(hdr)) != int(hdr.filesize - sizeof(hdr))) goto error; if(doloadmesh && !loadiqmmeshes(filename, hdr, buf)) goto error; if(doloadanim && !loadiqmanims(filename, hdr, buf)) goto error; delete[] buf; delete f; return true; error: if(buf) delete[] buf; delete f; return false; } bool loadmesh(const char *filename) { name = newstring(filename); return loadiqm(filename, true, false); } skelanimspec *loadanim(const char *animname) { const char *sep = strchr(animname, ':'); skelanimspec *sa = skel->findskelanim(animname, sep ? '\0' : ':'); if(!sa) { string filename; copystring(filename, animname); if(sep) filename[sep - animname] = '\0'; if(loadiqm(filename, false, true)) sa = skel->findskelanim(animname, sep ? '\0' : ':'); } return sa; } }; meshgroup *loadmeshes(const char *name, va_list args) { iqmmeshgroup *group = new iqmmeshgroup; group->shareskeleton(va_arg(args, char *)); if(!group->loadmesh(name)) { delete group; return NULL; } return group; } bool loaddefaultparts() { skelpart &mdl = *new skelpart; parts.add(&mdl); mdl.model = this; mdl.index = 0; mdl.pitchscale = mdl.pitchoffset = mdl.pitchmin = mdl.pitchmax = 0; adjustments.setsize(0); const char *fname = loadname + strlen(loadname); do --fname; while(fname >= loadname && *fname!='/' && *fname!='\\'); fname++; defformatstring(meshname)("packages/models/%s/%s.iqm", loadname, fname); mdl.meshes = sharemeshes(path(meshname), NULL); if(!mdl.meshes) return false; mdl.initanimparts(); mdl.initskins(); return true; } bool load() { if(loaded) return true; formatstring(dir)("packages/models/%s", loadname); defformatstring(cfgname)("packages/models/%s/iqm.cfg", loadname); loading = this; identflags &= ~IDF_PERSIST; if(execfile(cfgname, false) && parts.length()) // configured iqm, will call the iqm* commands below { identflags |= IDF_PERSIST; loading = NULL; loopv(parts) if(!parts[i]->meshes) return false; } else // iqm without configuration, try default tris and skin { identflags |= IDF_PERSIST; if(!loaddefaultparts()) { loading = NULL; return false; } loading = NULL; } scale /= 4; parts[0]->translate = translate; loopv(parts) { skelpart *p = (skelpart *)parts[i]; p->endanimparts(); p->meshes->shared++; } return loaded = true; } }; skelcommands iqmcommands; sauerbraten-0.0.20130203.dfsg/engine/textedit.h0000644000175000017500000005550112003067710020647 0ustar vincentvincent struct editline { enum { CHUNKSIZE = 256 }; char *text; int len, maxlen; editline() : text(NULL), len(0), maxlen(0) {} editline(const char *init) : text(NULL), len(0), maxlen(0) { set(init); } bool empty() { return len <= 0; } void clear() { DELETEA(text); len = maxlen = 0; } bool grow(int total, const char *fmt = "", ...) { if(total + 1 <= maxlen) return false; maxlen = (total + CHUNKSIZE) - total%CHUNKSIZE; char *newtext = new char[maxlen]; if(fmt) { va_list args; va_start(args, fmt); _vsnprintf(newtext, maxlen, fmt, args); va_end(args); } DELETEA(text); text = newtext; return true; } void set(const char *str, int slen = -1) { if(slen < 0) { slen = strlen(str); if(!grow(slen, "%s", str)) memcpy(text, str, slen + 1); } else { grow(slen); memcpy(text, str, slen); text[slen] = '\0'; } len = slen; } void prepend(const char *str) { int slen = strlen(str); if(!grow(slen + len, "%s%s", str, text ? text : "")) { memmove(&text[slen], text, len + 1); memcpy(text, str, slen + 1); } len += slen; } void append(const char *str) { int slen = strlen(str); if(!grow(len + slen, "%s%s", text ? text : "", str)) memcpy(&text[len], str, slen + 1); len += slen; } bool read(stream *f, int chop = -1) { if(chop < 0) chop = INT_MAX; else chop++; set(""); while(len + 1 < chop && f->getline(&text[len], min(maxlen, chop) - len)) { len += strlen(&text[len]); if(len > 0 && text[len-1] == '\n') { text[--len] = '\0'; return true; } if(len + 1 >= maxlen && len + 1 < chop) grow(len + CHUNKSIZE, "%s", text); } if(len + 1 >= chop) { char buf[CHUNKSIZE]; while(f->getline(buf, sizeof(buf))) { int blen = strlen(buf); if(blen > 0 && buf[blen-1] == '\n') return true; } } return len > 0; } void del(int start, int count) { if(!text) return; if(start < 0) { count += start; start = 0; } if(count <= 0 || start >= len) return; if(start + count > len) count = len - start - 1; memmove(&text[start], &text[start+count], len + 1 - (start + count)); len -= count; } void chop(int newlen) { if(!text) return; len = clamp(newlen, 0, len); text[len] = '\0'; } void insert(char *str, int start, int count = 0) { if(count <= 0) count = strlen(str); start = clamp(start, 0, len); grow(len + count, "%s", text ? text : ""); memmove(&text[start + count], &text[start], len - start + 1); memcpy(&text[start], str, count); len += count; } void combinelines(vector &src) { if(src.empty()) set(""); else loopv(src) { if(i) append("\n"); if(!i) set(src[i].text, src[i].len); else insert(src[i].text, len, src[i].len); } } }; struct editor { int mode; //editor mode - 1= keep while focused, 2= keep while used in gui, 3= keep forever (i.e. until mode changes) bool active, rendered; const char *name; const char *filename; int cx, cy; // cursor position - ensured to be valid after a region() or currentline() int mx, my; // selection mark, mx=-1 if following cursor - avoid direct access, instead use region() int maxx, maxy; // maxy=-1 if unlimited lines, 1 if single line editor int scrolly; // vertical scroll offset bool linewrap; int pixelwidth; // required for up/down/hit/draw/bounds int pixelheight; // -1 for variable sized, i.e. from bounds() vector lines; // MUST always contain at least one line! editor(const char *name, int mode, const char *initval) : mode(mode), active(true), rendered(false), name(newstring(name)), filename(NULL), cx(0), cy(0), mx(-1), maxx(-1), maxy(-1), scrolly(0), linewrap(false), pixelwidth(-1), pixelheight(-1) { //printf("editor %08x '%s'\n", this, name); lines.add().set(initval ? initval : ""); } ~editor() { //printf("~editor %08x '%s'\n", this, name); DELETEA(name); DELETEA(filename); clear(NULL); } void clear(const char *init = "") { cx = cy = 0; mark(false); loopv(lines) lines[i].clear(); lines.shrink(0); if(init) lines.add().set(init); } void setfile(const char *fname) { DELETEA(filename); if(fname) filename = newstring(fname); } void load() { if(!filename) return; clear(NULL); stream *file = openutf8file(filename, "r"); if(file) { while(lines.add().read(file, maxx) && (maxy < 0 || lines.length() <= maxy)); lines.pop().clear(); delete file; } if(lines.empty()) lines.add().set(""); } void save() { if(!filename) return; stream *file = openutf8file(filename, "w"); if(!file) return; loopv(lines) file->putline(lines[i].text); delete file; } void mark(bool enable) { mx = (enable) ? cx : -1; my = cy; } void selectall() { mx = my = INT_MAX; cx = cy = 0; } // constrain results to within buffer - s=start, e=end, return true if a selection range // also ensures that cy is always within lines[] and cx is valid bool region(int &sx, int &sy, int &ex, int &ey) { int n = lines.length(); assert(n != 0); if(cy < 0) cy = 0; else if(cy >= n) cy = n-1; int len = lines[cy].len; if(cx < 0) cx = 0; else if(cx > len) cx = len; if(mx >= 0) { if(my < 0) my = 0; else if(my >= n) my = n-1; len = lines[my].len; if(mx > len) mx = len; } sx = (mx >= 0) ? mx : cx; sy = (mx >= 0) ? my : cy; ex = cx; ey = cy; if(sy > ey) { swap(sy, ey); swap(sx, ex); } else if(sy==ey && sx > ex) swap(sx, ex); return (sx != ex) || (sy != ey); } bool region() { int sx, sy, ex, ey; return region(sx, sy, ex, ey); } // also ensures that cy is always within lines[] and cx is valid editline ¤tline() { int n = lines.length(); assert(n != 0); if(cy < 0) cy = 0; else if(cy >= n) cy = n-1; if(cx < 0) cx = 0; else if(cx > lines[cy].len) cx = lines[cy].len; return lines[cy]; } void copyselectionto(editor *b) { if(b==this) return; b->clear(NULL); int sx, sy, ex, ey; region(sx, sy, ex, ey); loopi(1+ey-sy) { if(b->maxy != -1 && b->lines.length() >= b->maxy) break; int y = sy+i; char *line = lines[y].text; int len = lines[y].len; if(y == sy && y == ey) { line += sx; len = ex - sx; } else if(y == sy) line += sx; else if(y == ey) len = ex; b->lines.add().set(line, len); } if(b->lines.empty()) b->lines.add().set(""); } char *tostring() { int len = 0; loopv(lines) len += lines[i].len + 1; char *str = newstring(len); int offset = 0; loopv(lines) { editline &l = lines[i]; memcpy(&str[offset], l.text, l.len); offset += l.len; str[offset++] = '\n'; } str[offset] = '\0'; return str; } char *selectiontostring() { vector buf; int sx, sy, ex, ey; region(sx, sy, ex, ey); loopi(1+ey-sy) { int y = sy+i; char *line = lines[y].text; int len = lines[y].len; if(y == sy && y == ey) { line += sx; len = ex - sx; } else if(y == sy) line += sx; else if(y == ey) len = ex; buf.put(line, len); buf.add('\n'); } buf.add('\0'); return newstring(buf.getbuf(), buf.length()-1); } void removelines(int start, int count) { loopi(count) lines[start+i].clear(); lines.remove(start, count); } bool del() // removes the current selection (if any) { int sx, sy, ex, ey; if(!region(sx, sy, ex, ey)) { mark(false); return false; } if(sy == ey) { if(sx == 0 && ex == lines[ey].len) removelines(sy, 1); else lines[sy].del(sx, ex - sx); } else { if(ey > sy+1) { removelines(sy+1, ey-(sy+1)); ey = sy+1; } if(ex == lines[ey].len) removelines(ey, 1); else lines[ey].del(0, ex); if(sx == 0) removelines(sy, 1); else lines[sy].del(sx, lines[sy].len - sx); } if(lines.empty()) lines.add().set(""); mark(false); cx = sx; cy = sy; editline ¤t = currentline(); if(cx >= current.len && cy < lines.length() - 1) { current.append(lines[cy+1].text); removelines(cy + 1, 1); } return true; } void insert(char ch) { del(); editline ¤t = currentline(); if(ch == '\n') { if(maxy == -1 || cy < maxy-1) { editline newline(¤t.text[cx]); current.chop(cx); cy = min(lines.length(), cy+1); lines.insert(cy, newline); } else current.chop(cx); cx = 0; } else { int len = current.len; if(maxx >= 0 && len > maxx-1) len = maxx-1; if(cx <= len) current.insert(&ch, cx++, 1); } } void insert(const char *s) { while(*s) insert(*s++); } void insertallfrom(editor *b) { if(b==this) return; del(); if(b->lines.length() == 1 || maxy == 1) { editline ¤t = currentline(); char *str = b->lines[0].text; int slen = b->lines[0].len; if(maxx >= 0 && b->lines[0].len + cx > maxx) slen = maxx-cx; if(slen > 0) { int len = current.len; if(maxx >= 0 && slen + cx + len > maxx) len = max(0, maxx-(cx+slen)); current.insert(str, cx, slen); cx += slen; } } else { loopv(b->lines) { if(!i) { lines[cy++].append(b->lines[i].text); } else if(i >= b->lines.length()) { cx = b->lines[i].len; lines[cy].prepend(b->lines[i].text); } else if(maxy < 0 || lines.length() < maxy) lines.insert(cy++, editline(b->lines[i].text)); } } } void key(int code, int cooked) { switch(code) { case SDLK_UP: if(linewrap) { int x, y; char *str = currentline().text; text_pos(str, cx+1, x, y, pixelwidth); if(y > 0) { cx = text_visible(str, x, y-FONTH, pixelwidth); break; } } cy--; break; case SDLK_DOWN: if(linewrap) { int x, y, width, height; char *str = currentline().text; text_pos(str, cx, x, y, pixelwidth); text_bounds(str, width, height, pixelwidth); y += FONTH; if(y < height) { cx = text_visible(str, x, y, pixelwidth); break; } } cy++; break; case -4: cy--; break; case -5: cy++; break; case SDLK_PAGEUP: cy-=pixelheight/FONTH; break; case SDLK_PAGEDOWN: cy+=pixelheight/FONTH; break; case SDLK_HOME: cx = cy = 0; break; case SDLK_END: cx = cy = INT_MAX; break; case SDLK_LEFT: cx--; break; case SDLK_RIGHT: cx++; break; case SDLK_DELETE: if(!del()) { editline ¤t = currentline(); if(cx < current.len) current.del(cx, 1); else if(cy < lines.length()-1) { //combine with next line current.append(lines[cy+1].text); removelines(cy+1, 1); } } break; case SDLK_BACKSPACE: if(!del()) { editline ¤t = currentline(); if(cx > 0) current.del(--cx, 1); else if(cy > 0) { //combine with previous line cx = lines[cy-1].len; lines[cy-1].append(current.text); removelines(cy--, 1); } } break; case SDLK_LSHIFT: case SDLK_RSHIFT: break; case SDLK_RETURN: cooked = '\n'; // fall through default: insert(cooked); break; } } void hit(int hitx, int hity, bool dragged) { int maxwidth = linewrap?pixelwidth:-1; int h = 0; for(int i = scrolly; i < lines.length(); i++) { int width, height; text_bounds(lines[i].text, width, height, maxwidth); if(h + height > pixelheight) break; if(hity >= h && hity <= h+height) { int x = text_visible(lines[i].text, hitx, hity-h, maxwidth); if(dragged) { mx = x; my = i; } else { cx = x; cy = i; }; break; } h+=height; } } int limitscrolly() { int maxwidth = linewrap?pixelwidth:-1; int slines = lines.length(); for(int ph = pixelheight; slines > 0 && ph > 0;) { int width, height; text_bounds(lines[slines-1].text, width, height, maxwidth); if(height > ph) break; ph -= height; slines--; } return slines; } void draw(int x, int y, int color, bool hit) { int maxwidth = linewrap?pixelwidth:-1; int sx, sy, ex, ey; bool selection = region(sx, sy, ex, ey); // fix scrolly so that is always on screen if(cy < scrolly) scrolly = cy; else { if(scrolly < 0) scrolly = 0; int h = 0; for(int i = cy; i >= scrolly; i--) { int width, height; text_bounds(lines[i].text, width, height, maxwidth); if(h + height > pixelheight) { scrolly = i+1; break; } h += height; } } if(selection) { // convert from cursor coords into pixel coords int psx, psy, pex, pey; text_pos(lines[sy].text, sx, psx, psy, maxwidth); text_pos(lines[ey].text, ex, pex, pey, maxwidth); int maxy = lines.length(); int h = 0; for(int i = scrolly; i < maxy; i++) { int width, height; text_bounds(lines[i].text, width, height, maxwidth); if(h + height > pixelheight) { maxy = i; break; } if(i == sy) psy += h; if(i == ey) { pey += h; break; } h += height; } maxy--; if(ey >= scrolly && sy <= maxy) { // crop top/bottom within window if(sy < scrolly) { sy = scrolly; psy = 0; psx = 0; } if(ey > maxy) { ey = maxy; pey = pixelheight - FONTH; pex = pixelwidth; } notextureshader->set(); glDisable(GL_TEXTURE_2D); glColor3ub(0xA0, 0x80, 0x80); glBegin(GL_QUADS); if(psy == pey) { glVertex2f(x+psx, y+psy); glVertex2f(x+pex, y+psy); glVertex2f(x+pex, y+pey+FONTH); glVertex2f(x+psx, y+pey+FONTH); } else { glVertex2f(x+psx, y+psy); glVertex2f(x+psx, y+psy+FONTH); glVertex2f(x+pixelwidth, y+psy+FONTH); glVertex2f(x+pixelwidth, y+psy); if(pey-psy > FONTH) { glVertex2f(x, y+psy+FONTH); glVertex2f(x+pixelwidth, y+psy+FONTH); glVertex2f(x+pixelwidth, y+pey); glVertex2f(x, y+pey); } glVertex2f(x, y+pey); glVertex2f(x, y+pey+FONTH); glVertex2f(x+pex, y+pey+FONTH); glVertex2f(x+pex, y+pey); } glEnd(); glEnable(GL_TEXTURE_2D); defaultshader->set(); } } int h = 0; for(int i = scrolly; i < lines.length(); i++) { int width, height; text_bounds(lines[i].text, width, height, maxwidth); if(h + height > pixelheight) break; draw_text(lines[i].text, x, y+h, color>>16, (color>>8)&0xFF, color&0xFF, 0xFF, hit&&(cy==i)?cx:-1, maxwidth); if(linewrap && height > FONTH) // line wrap indicator { notextureshader->set(); glDisable(GL_TEXTURE_2D); glColor3ub(0x80, 0xA0, 0x80); glBegin(GL_TRIANGLE_STRIP); glVertex2f(x, y+h+FONTH); glVertex2f(x, y+h+height); glVertex2f(x-FONTW/2, y+h+FONTH); glVertex2f(x-FONTW/2, y+h+height); glEnd(); glEnable(GL_TEXTURE_2D); defaultshader->set(); } h+=height; } } }; // a 'stack' where the last is the current focused editor static vector editors; static editor *currentfocus() { return editors.length() ? editors.last() : NULL; } static void readyeditors() { loopv(editors) editors[i]->active = (editors[i]->mode==EDITORFOREVER); } static void flusheditors() { loopvrev(editors) if(!editors[i]->active) { editor *e = editors.remove(i); DELETEP(e); } } static editor *useeditor(const char *name, int mode, bool focus, const char *initval = NULL) { loopv(editors) if(strcmp(editors[i]->name, name) == 0) { editor *e = editors[i]; if(focus) { editors.add(e); editors.remove(i); } // re-position as last e->active = true; return e; } editor *e = new editor(name, mode, initval); if(focus) editors.add(e); else editors.insert(0, e); return e; } #define TEXTCOMMAND(f, s, d, body) ICOMMAND(f, s, d,\ editor *top = currentfocus();\ if(!top || identflags&IDF_OVERRIDDEN) return;\ body\ ) ICOMMAND(textlist, "", (), // @DEBUG return list of all the editors vector s; loopv(editors) { if(i > 0) s.put(", ", 2); s.put(editors[i]->name, strlen(editors[i]->name)); } s.add('\0'); result(s.getbuf()); ); TEXTCOMMAND(textshow, "", (), // @DEBUG return the start of the buffer editline line; line.combinelines(top->lines); result(line.text); line.clear(); ); ICOMMAND(textfocus, "si", (char *name, int *mode), // focus on a (or create a persistent) specific editor, else returns current name if(*name) useeditor(name, *mode<=0 ? EDITORFOREVER : *mode, true); else if(editors.length() > 0) result(editors.last()->name); ); TEXTCOMMAND(textprev, "", (), editors.insert(0, top); editors.pop();); // return to the previous editor TEXTCOMMAND(textmode, "i", (int *m), // (1= keep while focused, 2= keep while used in gui, 3= keep forever (i.e. until mode changes)) topmost editor, return current setting if no args if(*m) top->mode = *m; else intret(top->mode); ); TEXTCOMMAND(textsave, "s", (char *file), // saves the topmost (filename is optional) if(*file) top->setfile(path(file, true)); top->save(); ); TEXTCOMMAND(textload, "s", (char *file), // loads into the topmost editor, returns filename if no args if(*file) { top->setfile(path(file, true)); top->load(); } else if(top->filename) result(top->filename); ); TEXTCOMMAND(textinit, "sss", (char *name, char *file, char *initval), // loads into named editor if no file assigned and editor has been rendered { editor *e = NULL; loopv(editors) if(!strcmp(editors[i]->name, name)) { e = editors[i]; break; } if(e && e->rendered && !e->filename && *file && (e->lines.empty() || (e->lines.length() == 1 && !strcmp(e->lines[0].text, initval)))) { e->setfile(path(file, true)); e->load(); } }); #define PASTEBUFFER "#pastebuffer" TEXTCOMMAND(textcopy, "", (), editor *b = useeditor(PASTEBUFFER, EDITORFOREVER, false); top->copyselectionto(b);); TEXTCOMMAND(textpaste, "", (), editor *b = useeditor(PASTEBUFFER, EDITORFOREVER, false); top->insertallfrom(b);); TEXTCOMMAND(textmark, "i", (int *m), // (1=mark, 2=unmark), return current mark setting if no args if(*m) top->mark(*m==1); else intret(top->region() ? 1 : 2); ); TEXTCOMMAND(textselectall, "", (), top->selectall();); TEXTCOMMAND(textclear, "", (), top->clear();); TEXTCOMMAND(textcurrentline, "", (), result(top->currentline().text);); TEXTCOMMAND(textexec, "i", (int *selected), // execute script commands from the buffer (0=all, 1=selected region only) char *script = *selected ? top->selectiontostring() : top->tostring(); execute(script); delete[] script; ); sauerbraten-0.0.20130203.dfsg/engine/pvs.cpp0000644000175000017500000012172612066675175020206 0ustar vincentvincent#include "engine.h" #include "SDL_thread.h" enum { PVS_HIDE_GEOM = 1<<0, PVS_HIDE_BB = 1<<1 }; struct pvsnode { bvec edges; uchar flags; uint children; }; static vector origpvsnodes; static bool mergepvsnodes(pvsnode &p, pvsnode *children) { loopi(7) if(children[i].flags!=children[7].flags) return false; bvec bbs[4]; loop(x, 2) loop(y, 2) { const bvec &lo = children[octaindex(2, x, y, 0)].edges, &hi = children[octaindex(2, x, y, 1)].edges; if(lo.x!=0xFF && (lo.x&0x11 || lo.y&0x11 || lo.z&0x11)) return false; if(hi.x!=0xFF && (hi.x&0x11 || hi.y&0x11 || hi.z&0x11)) return false; #define MERGEBBS(res, coord, row, col) \ if(lo.coord==0xFF) \ { \ if(hi.coord!=0xFF) \ { \ res.coord = ((hi.coord&~0x11)>>1) + 0x44; \ res.row = hi.row; \ res.col = hi.col; \ } \ } \ else if(hi.coord==0xFF) \ { \ res.coord = (lo.coord&0xEE)>>1; \ res.row = lo.row; \ res.col = lo.col; \ } \ else if(lo.row!=hi.row || lo.col!=hi.col || (lo.coord&0xF0)!=0x80 || (hi.coord&0xF)!=0) return false; \ else \ { \ res.coord = ((lo.coord&~0xF1)>>1) | (((hi.coord&~0x1F)>>1) + 0x40); \ res.row = lo.row; \ res.col = lo.col; \ } bvec &res = bbs[x + 2*y]; MERGEBBS(res, z, x, y); res.x = lo.x; res.y = lo.y; } loop(x, 2) { bvec &lo = bbs[x], &hi = bbs[x+2]; MERGEBBS(lo, y, x, z); } bvec &lo = bbs[0], &hi = bbs[1]; MERGEBBS(p.edges, x, y, z); return true; } static void genpvsnodes(cube *c, int parent = 0, const ivec &co = ivec(0, 0, 0), int size = worldsize/2) { int index = origpvsnodes.length(); loopi(8) { ivec o(i, co.x, co.y, co.z, size); pvsnode &n = origpvsnodes.add(); n.flags = 0; n.children = 0; if(c[i].children || isempty(c[i]) || c[i].material&MAT_ALPHA) memset(n.edges.v, 0xFF, 3); else loopk(3) { uint face = c[i].faces[k]; if(face==F_SOLID) n.edges[k] = 0x80; else { uchar low = max(max(face&0xF, (face>>8)&0xF), max((face>>16)&0xF, (face>>24)&0xF)), high = min(min((face>>4)&0xF, (face>>12)&0xF), min((face>>20)&0xF, (face>>28)&0xF)); if(size<8) { if(low&((8/size)-1)) { low += 8/size - (low&((8/size)-1)); } if(high&((8/size)-1)) high &= ~(8/size-1); } if(low >= high) { memset(n.edges.v, 0xFF, 3); break; } n.edges[k] = low | (high<<4); } } } int branches = 0; loopi(8) if(c[i].children) { ivec o(i, co.x, co.y, co.z, size); genpvsnodes(c[i].children, index+i, o, size>>1); if(origpvsnodes[index+i].children) branches++; } if(!branches && mergepvsnodes(origpvsnodes[parent], &origpvsnodes[index])) origpvsnodes.setsize(index); else origpvsnodes[parent].children = index; } struct shaftplane { float r, c, offset; uchar rnear, cnear, rfar, cfar; }; struct usvec { union { struct { ushort x, y, z; }; ushort v[3]; }; ushort &operator[](int i) { return v[i]; } ushort operator[](int i) const { return v[i]; } ivec toivec() const { return ivec(x, y, z); } }; struct shaftbb { union { ushort v[6]; struct { usvec min, max; }; }; shaftbb() {} shaftbb(const ivec &o, int size) { min.x = o.x; min.y = o.y; min.z = o.z; max.x = o.x + size; max.y = o.y + size; max.z = o.z + size; } shaftbb(const ivec &o, int size, const bvec &edges) { min.x = o.x + (size*(edges.x&0xF))/8; min.y = o.y + (size*(edges.y&0xF))/8; min.z = o.z + (size*(edges.z&0xF))/8; max.x = o.x + (size*(edges.x>>4))/8; max.y = o.y + (size*(edges.y>>4))/8; max.z = o.z + (size*(edges.z>>4))/8; } ushort &operator[](int i) { return v[i]; } ushort operator[](int i) const { return v[i]; } bool contains(const shaftbb &o) const { return min.x<=o.min.x && min.y<=o.min.y && min.z<=o.min.z && max.x>=o.max.x && max.y>=o.max.y && max.z>=o.max.z; } bool outside(const ivec &o, int size) const { return o.x>=max.x || o.y>=max.y || o.z>=max.z || o.x+size<=min.x || o.y+size<=min.y || o.z+size<=min.z; } bool outside(const shaftbb &o) const { return o.min.x>max.x || o.min.y>max.y || o.min.z>max.z || o.max.xmax.x || o.max.y>max.y || o.max.z>max.z; } }; struct shaft { shaftbb bounds; shaftplane planes[8]; int numplanes; shaft(const shaftbb &from, const shaftbb &to) { calcshaft(from, to); } void calcshaft(const shaftbb &from, const shaftbb &to) { uchar match = 0, color = 0; loopi(3) { if(to.min[i] < from.min[i]) { color |= 1< from.min[i]) bounds.min[i] = to.min[i]+1; else { match |= 1< from.max[i]) { color |= 8<>i)^(color>>j))&1) { int r = i%3, c = j%3, d = (r+1)%3; if(d==c) d = (c+1)%3; shaftplane &p = planes[numplanes++]; p.r = from[j] - to[j]; if(i<3 ? p.r >= 0 : p.r < 0) { p.r = -p.r; p.c = from[i] - to[i]; } else p.c = to[i] - from[i]; p.offset = -(from[i]*p.r + from[j]*p.c); p.rnear = p.r >= 0 ? r : 3+r; p.cnear = p.c >= 0 ? c : 3+c; p.rfar = p.r < 0 ? r : 3+r; p.cfar = p.c < 0 ? c : 3+c; } } bool outside(const shaftbb &o) const { if(bounds.outside(o)) return true; for(const shaftplane *p = planes; p < &planes[numplanes]; p++) { if(o[p->rnear]*p->r + o[p->cnear]*p->c + p->offset > 0) return true; } return false; } bool inside(const shaftbb &o) const { if(bounds.notinside(o)) return false; for(const shaftplane *p = planes; p < &planes[numplanes]; p++) { if(o[p->rfar]*p->r + o[p->cfar]*p->c + p->offset > 0) return false; } return true; } }; struct pvsdata { int offset, len; pvsdata() {} pvsdata(int offset, int len) : offset(offset), len(len) {} }; static vector pvsbuf; static inline uint hthash(const pvsdata &k) { uint h = 5381; loopi(k.len) h = ((h<<5)+h)^pvsbuf[k.offset+i]; return h; } static inline bool htcmp(const pvsdata &x, const pvsdata &y) { return x.len==y.len && !memcmp(&pvsbuf[x.offset], &pvsbuf[y.offset], x.len); } static SDL_mutex *pvsmutex = NULL; static hashtable pvscompress; static vector pvs; static SDL_mutex *viewcellmutex = NULL; struct viewcellrequest { int *result; ivec o; int size; }; static vector viewcellrequests; static bool genpvs_canceled = false; static int numviewcells = 0; VAR(maxpvsblocker, 1, 512, 1<<16); VAR(pvsleafsize, 1, 64, 1024); #define MAXWATERPVS 32 static struct { int height; vector matsurfs; } waterplanes[MAXWATERPVS]; static vector waterfalls; uint numwaterplanes = 0; struct pvsworker { pvsworker() : thread(NULL), pvsnodes(new pvsnode[origpvsnodes.length()]) { } ~pvsworker() { delete[] pvsnodes; } SDL_Thread *thread; pvsnode *pvsnodes; shaftbb viewcellbb; pvsnode *levels[32]; int curlevel; ivec origin; void resetlevels() { curlevel = worldscale; levels[curlevel] = &pvsnodes[0]; origin = ivec(0, 0, 0); } int hasvoxel(const ivec &p, int coord, int dir, int ocoord = 0, int odir = 0, int *omin = NULL) { uint diff = (origin.x^p.x)|(origin.y^p.y)|(origin.z^p.z); if(diff >= uint(worldsize)) return 0; diff >>= curlevel; while(diff) { curlevel++; diff >>= 1; } pvsnode *cur = levels[curlevel]; while(cur->children && !(cur->flags&PVS_HIDE_BB)) { cur = &pvsnodes[cur->children]; curlevel--; cur += ((p.z>>(curlevel-2))&4) | ((p.y>>(curlevel-1))&2) | ((p.x>>curlevel)&1); levels[curlevel] = cur; } origin = ivec(p.x&(~0<flags&PVS_HIDE_BB || cur->edges==bvec(0x80, 0x80, 0x80)) { if(omin) { int step = origin[ocoord] + (odir< *omin) *omin = step; } return origin[coord] + (dir<edges.x==0xFF) return 0; ivec bbp(p); bbp.sub(origin); ivec bbmin, bbmax; bbmin.x = ((cur->edges.x&0xF)<edges.x>>4)<= bbmax.x) return 0; bbmin.y = ((cur->edges.y&0xF)<edges.y>>4)<= bbmax.y) return 0; bbmin.z = ((cur->edges.z&0xF)<edges.z>>4)<= bbmax.z) return 0; if(omin) { int step = (odir ? bbmax[ocoord] : bbmin[ocoord]) - bbp[ocoord] + (odir - 1); if(odir ? step < *omin : step > *omin) *omin = step; } return (dir ? bbmax[coord] : bbmin[coord]) - bbp[coord] + (dir - 1); } void hidepvs(pvsnode &p) { if(p.children) { pvsnode *children = &pvsnodes[p.children]; loopi(8) hidepvs(children[i]); p.flags |= PVS_HIDE_BB; return; } p.flags |= PVS_HIDE_BB; if(p.edges.x!=0xFF) p.flags |= PVS_HIDE_GEOM; } void shaftcullpvs(shaft &s, pvsnode &p, const ivec &co = ivec(0, 0, 0), int size = worldsize) { if(p.flags&PVS_HIDE_BB) return; shaftbb bb(co, size); if(s.outside(bb)) return; if(s.inside(bb)) { hidepvs(p); return; } if(p.children) { pvsnode *children = &pvsnodes[p.children]; uchar flags = 0xFF; loopi(8) { ivec o(i, co.x, co.y, co.z, size>>1); shaftcullpvs(s, children[i], o, size>>1); flags &= children[i].flags; } if(flags & PVS_HIDE_BB) p.flags |= PVS_HIDE_BB; return; } if(p.edges.x==0xFF) return; shaftbb geom(co, size, p.edges); if(s.inside(geom)) p.flags |= PVS_HIDE_GEOM; } ringbuf prevblockers; struct cullorder { int index, dist; cullorder() {} cullorder(int index, int dist) : index(index), dist(dist) {} }; void cullpvs(pvsnode &p, const ivec &co = ivec(0, 0, 0), int size = worldsize) { if(p.flags&(PVS_HIDE_BB | PVS_HIDE_GEOM) || genpvs_canceled) return; if(p.children && !(p.flags&PVS_HIDE_BB)) { pvsnode *children = &pvsnodes[p.children]; int csize = size>>1; ivec dmin = ivec(co).add(csize>>1).sub(viewcellbb.min.toivec().add(viewcellbb.max.toivec()).shr(1)), dmax = ivec(dmin).add(csize); dmin.mul(dmin); dmax.mul(dmax); ivec diff = ivec(dmax).sub(dmin); cullorder order[8]; int dir = 0; if(diff.x < 0) { diff.x = -diff.x; dir |= 1; } if(diff.y < 0) { diff.y = -diff.y; dir |= 2; } if(diff.z < 0) { diff.z = -diff.z; dir |= 4; } order[0] = cullorder(0, 0); order[7] = cullorder(7, diff.x + diff.y + diff.z); order[1] = cullorder(1, diff.x); order[2] = cullorder(2, diff.y); order[3] = cullorder(4, diff.z); if(order[2].dist < order[1].dist) swap(order[1], order[2]); if(order[3].dist < order[2].dist) swap(order[2], order[3]); if(order[2].dist < order[1].dist) swap(order[1], order[2]); cullorder dxy(order[1].index|order[2].index, order[1].dist+order[2].dist), dxz(order[1].index|order[3].index, order[1].dist+order[3].dist), dyz(order[2].index|order[3].index, order[2].dist+order[3].dist); int j; for(j = 4; j > 0 && dxy.dist < order[j-1].dist; --j) order[j] = order[j-1]; order[j] = dxy; for(j = 5; j > 0 && dxz.dist < order[j-1].dist; --j) order[j] = order[j-1]; order[j] = dxz; for(j = 6; j > 0 && dyz.dist < order[j-1].dist; --j) order[j] = order[j-1]; order[j] = dyz; loopi(8) { int index = order[i].index^dir; ivec o(index, co.x, co.y, co.z, csize); cullpvs(children[index], o, csize); } if(!(p.flags & PVS_HIDE_BB)) return; } bvec edges = p.children ? bvec(0x80, 0x80, 0x80) : p.edges; if(edges.x==0xFF) return; shaftbb geom(co, size, edges); ivec diff = geom.max.toivec().sub(viewcellbb.min.toivec()).abs(); cullorder order[3] = { cullorder(0, diff.x), cullorder(1, diff.y), cullorder(2, diff.z) }; if(order[1].dist > order[0].dist) swap(order[0], order[1]); if(order[2].dist > order[1].dist) swap(order[1], order[2]); if(order[1].dist > order[0].dist) swap(order[0], order[1]); loopi(6) { int dim = order[i >= 3 ? i-3 : i].index, dc = (i >= 3) != (geom.max[dim] <= viewcellbb.min[dim]) ? 1 : 0, r = R[dim], c = C[dim]; int ccenter = geom.min[c]; if(geom.min[r]==geom.max[r] || geom.min[c]==geom.max[c]) continue; while(ccenter < geom.max[c]) { ivec rmin; rmin[dim] = geom[dim + 3*dc] + (dc ? -1 : 0); rmin[r] = geom.min[r]; rmin[c] = ccenter; ivec rmax = rmin; rmax[r] = geom.max[r] - 1; int rcenter = (rmin[r] + rmax[r])/2; resetlevels(); for(int minstep = -1, maxstep = 1; (minstep || maxstep) && rmax[r] - rmin[r] < maxpvsblocker;) { if(minstep) minstep = hasvoxel(rmin, r, 0); if(maxstep) maxstep = hasvoxel(rmax, r, 1); rmin[r] += minstep; rmax[r] += maxstep; } rmin[r] = rcenter + (rmin[r] - rcenter)/2; rmax[r] = rcenter + (rmax[r] - rcenter)/2; if(rmin[r]>=geom.min[r] && rmax[r]=geom.min[r] && rmax[r]=geom.min[c] && cmax[c]geom.min[r]) emin[r] = geom.min[r]; if(emax[r]= viewcellbb.max[dim] || bb.max[dim] <= viewcellbb.min[dim]) { int ddir = bb.min[dim] >= viewcellbb.max[dim] ? 1 : -1, dval = ddir>0 ? USHRT_MAX-1 : 0, dlimit = maxpvsblocker, numsides = 0; loopj(4) { ivec dmax; int odim = j < 2 ? c : r; if(j&1) { if(bb.max[odim] >= viewcellbb.max[odim]) continue; dmax[odim] = bb.max[odim]-1; } else { if(bb.min[odim] <= viewcellbb.min[odim]) continue; dmax[odim] = bb.min[odim]; } numsides++; dmax[dim] = bb.min[dim]; int stepdim = j < 2 ? r : c, stepstart = bb.min[stepdim], stepend = bb.max[stepdim]; int dstep = ddir; for(; dstep && ddir*(dmax[dim] - (int)bb.min[dim]) < dlimit;) { dmax[dim] += dstep; dstep = ddir > 0 ? INT_MAX : INT_MIN; dmax[stepdim] = stepstart; resetlevels(); for(int step = 1; step && dmax[stepdim] < stepend;) { step = hasvoxel(dmax, stepdim, 1, dim, (ddir+1)/2, &dstep); dmax[stepdim] += step; } if(dmax[stepdim] < stepend) dstep = 0; } dlimit = min(dlimit, ddir*(dmax[dim] - (int)bb.min[dim])); if(!dstep) dmax[dim] -= ddir; if(ddir>0) dval = min(dval, dmax[dim]); else dval = max(dval, dmax[dim]); } if(numsides>0) { if(ddir>0) bb.max[dim] = dval+1; else bb.min[dim] = dval; } //printf("(%d,%d,%d) x %d,%d,%d, side %d, ccenter = %d, origin = (%d,%d,%d), size = %d\n", bb.min.x, bb.min.y, bb.min.z, bb.max.x-bb.min.x, bb.max.y-bb.min.y, bb.max.z-bb.min.z, i, ccenter, co.x, co.y, co.z, size); } bool dup = false; loopvj(prevblockers) { if(prevblockers[j].contains(bb)) { dup = true; break; } } if(!dup) { shaft s(viewcellbb, bb); shaftcullpvs(s, pvsnodes[0]); prevblockers.add(bb); } if(bb.contains(geom)) return; ccenter = cmax[c] + 1; } } } bool compresspvs(pvsnode &p, int size, int threshold) { if(!p.children) return true; if(p.flags&PVS_HIDE_BB) { p.children = 0; return true; } pvsnode *children = &pvsnodes[p.children]; bool canreduce = true; loopi(8) { if(!compresspvs(children[i], size/2, threshold)) canreduce = false; } if(canreduce) { int hide = children[7].flags&PVS_HIDE_BB; loopi(7) if((children[i].flags&PVS_HIDE_BB)!=hide) canreduce = false; if(canreduce) { p.flags = (p.flags & ~PVS_HIDE_BB) | hide; p.children = 0; return true; } } if(size <= threshold) { p.children = 0; return true; } return false; } vector outbuf; bool serializepvs(pvsnode &p, int storage = -1) { if(!p.children) { outbuf.add(0xFF); loopi(8) outbuf.add(p.flags&PVS_HIDE_BB ? 0xFF : 0); return true; } int index = outbuf.length(); pvsnode *children = &pvsnodes[p.children]; int i = 0; uchar leafvalues = 0; if(storage>=0) { for(; i < 8; i++) { pvsnode &child = children[i]; if(child.flags&PVS_HIDE_BB) leafvalues |= 1<255) { outbuf[storage] = 0; return false; } outbuf[storage] = uchar(offset); } outbuf.add(0); loopj(8) outbuf.add(leafvalues&(1< &matsurfs) { if(pvsnodes[0].flags & PVS_HIDE_BB) return true; if(!pvsnodes[0].children) return false; loopv(matsurfs) { materialsurface &m = *matsurfs[i]; ivec bborigin(m.o), bbsize(0, 0, 0); int dim = dimension(m.orient); bbsize[C[dim]] = m.csize; bbsize[R[dim]] = m.rsize; bborigin[dim] -= 2; bbsize[dim] = 2; if(!materialoccluded(pvsnodes[0], vec(0, 0, 0), worldsize/2, bborigin, bbsize)) return false; } return true; } int wateroccluded, waterbytes; void calcpvs(const ivec &co, int size) { loopk(3) { viewcellbb.min[k] = co[k]; viewcellbb.max[k] = co[k]+size; } memcpy(pvsnodes, origpvsnodes.getbuf(), origpvsnodes.length()*sizeof(pvsnode)); prevblockers.clear(); cullpvs(pvsnodes[0]); wateroccluded = 0; loopi(numwaterplanes) { if(waterplanes[i].height < 0) { if(waterfalls.length() && materialoccluded(waterfalls)) wateroccluded |= 1<>(i*8))&0xFF); pvsbuf.put(outbuf.getbuf(), outbuf.length()); int *val = pvscompress.access(key); if(val) pvsbuf.setsize(key.offset); else { val = &pvscompress[key]; *val = pvs.length(); pvs.add(key); } if(pvsmutex) SDL_UnlockMutex(pvsmutex); return *val; } static int run(void *data) { pvsworker *w = (pvsworker *)data; SDL_LockMutex(viewcellmutex); while(viewcellrequests.length()) { viewcellrequest req = viewcellrequests.pop(); SDL_UnlockMutex(viewcellmutex); int result = w->genviewcell(req.o, req.size); SDL_LockMutex(viewcellmutex); *req.result = result; } SDL_UnlockMutex(viewcellmutex); return 0; } }; struct viewcellnode { uchar leafmask; union viewcellchild { int pvs; viewcellnode *node; } children[8]; viewcellnode() : leafmask(0xFF) { loopi(8) children[i].pvs = -1; } ~viewcellnode() { loopi(8) if(!(leafmask&(1< pvsworkers; static volatile bool check_genpvs_progress = false; static Uint32 genpvs_timer(Uint32 interval, void *param) { check_genpvs_progress = true; return interval; } static int totalviewcells = 0; static void show_genpvs_progress(int unique = pvs.length(), int processed = numviewcells) { float bar1 = float(processed) / float(totalviewcells>0 ? totalviewcells : 1); defformatstring(text1)("%d%% - %d of %d view cells (%d unique)", int(bar1 * 100), processed, totalviewcells, unique); renderprogress(bar1, text1); if(interceptkey(SDLK_ESCAPE)) genpvs_canceled = true; check_genpvs_progress = false; } static shaftbb pvsbounds; static void calcpvsbounds() { loopk(3) pvsbounds.min[k] = USHRT_MAX; loopk(3) pvsbounds.max[k] = 0; extern vector valist; loopv(valist) { vtxarray *va = valist[i]; loopk(3) { if(va->geommin[k]>va->geommax[k]) continue; pvsbounds.min[k] = min(pvsbounds.min[k], (ushort)va->geommin[k]); pvsbounds.max[k] = max(pvsbounds.max[k], (ushort)va->geommax[k]); } } } static inline bool isallclip(cube *c) { loopi(8) { cube &h = c[i]; if(h.children ? !isallclip(h.children) : (!isentirelysolid(h) && (h.material&MATF_CLIP)!=MAT_CLIP)) return false; } return true; } static int countviewcells(cube *c, const ivec &co, int size, int threshold) { int count = 0; loopi(8) { ivec o(i, co.x, co.y, co.z, size); if(pvsbounds.outside(o, size)) continue; cube &h = c[i]; if(h.children) { if(size>threshold) { count += countviewcells(h.children, o, size>>1, threshold); continue; } if(isallclip(h.children)) continue; } else if(isentirelysolid(h) || (h.material&MATF_CLIP)==MAT_CLIP) continue; count++; } return count; } static void genviewcells(viewcellnode &p, cube *c, const ivec &co, int size, int threshold) { if(genpvs_canceled) return; loopi(8) { ivec o(i, co.x, co.y, co.z, size); if(pvsbounds.outside(o, size)) continue; cube &h = c[i]; if(h.children) { if(size>threshold) { p.leafmask &= ~(1<>1, threshold); continue; } if(isallclip(h.children)) continue; } else if(isentirelysolid(h) || (h.material&MATF_CLIP)==MAT_CLIP) continue; if(pvsworkers.length()) { if(genpvs_canceled) return; p.children[i].pvs = pvsworkers[0]->genviewcell(o, size); if(check_genpvs_progress) show_genpvs_progress(); } else { viewcellrequest &req = viewcellrequests.add(); req.result = &p.children[i].pvs; req.o = o; req.size = size; } } } static viewcellnode *viewcells = NULL; static int lockedwaterplanes[MAXWATERPVS]; static uchar *curpvs = NULL, *lockedpvs = NULL; static int curwaterpvs = 0, lockedwaterpvs = 0; static inline pvsdata *lookupviewcell(const vec &p) { uint x = uint(floor(p.x)), y = uint(floor(p.y)), z = uint(floor(p.z)); if(!viewcells || (x|y|z)>=uint(worldsize)) return NULL; viewcellnode *vc = viewcells; for(int scale = worldscale-1; scale>=0; scale--) { int i = octastep(x, y, z, scale); if(vc->leafmask&(1<children[i].pvs>=0 ? &pvs[vc->children[i].pvs] : NULL; } vc = vc->children[i].node; } return NULL; } static void lockpvs_(bool lock) { if(lockedpvs) DELETEA(lockedpvs); if(!lock) return; pvsdata *d = lookupviewcell(camera1->o); if(!d) return; int wbytes = d->len%9, len = d->len - wbytes; lockedpvs = new uchar[len]; memcpy(lockedpvs, &pvsbuf[d->offset + wbytes], len); lockedwaterpvs = 0; loopi(wbytes) lockedwaterpvs |= pvsbuf[d->offset + i] << (i*8); loopi(MAXWATERPVS) lockedwaterplanes[i] = waterplanes[i].height; conoutf("locked view cell at %.1f, %.1f, %.1f", camera1->o.x, camera1->o.y, camera1->o.z); } VARF(lockpvs, 0, 0, 1, lockpvs_(lockpvs!=0)); VARN(pvs, usepvs, 0, 1, 1); VARN(waterpvs, usewaterpvs, 0, 1, 1); void setviewcell(const vec &p) { if(!usepvs) curpvs = NULL; else if(lockedpvs) { curpvs = lockedpvs; curwaterpvs = lockedwaterpvs; } else { pvsdata *d = lookupviewcell(p); curpvs = d ? &pvsbuf[d->offset] : NULL; curwaterpvs = 0; if(d) { loopi(d->len%9) curwaterpvs |= *curpvs++ << (i*8); } } if(!usepvs || !usewaterpvs) curwaterpvs = 0; } void clearpvs() { DELETEP(viewcells); pvs.setsize(0); pvsbuf.setsize(0); curpvs = NULL; numwaterplanes = 0; lockpvs = 0; lockpvs_(false); } COMMAND(clearpvs, ""); static void findwaterplanes() { extern vector valist; loopi(MAXWATERPVS) { waterplanes[i].height = -1; waterplanes[i].matsurfs.setsize(0); } waterfalls.setsize(0); numwaterplanes = 0; loopv(valist) { vtxarray *va = valist[i]; loopj(va->matsurfs) { materialsurface &m = va->matbuf[j]; if((m.material&MATF_VOLUME)!=MAT_WATER || m.orient==O_BOTTOM) { j += m.skip; continue; } if(m.orient!=O_TOP) { waterfalls.add(&m); continue; } loopk(numwaterplanes) if(waterplanes[k].height == m.o.z) { waterplanes[k].matsurfs.add(&m); goto nextmatsurf; } if(numwaterplanes < MAXWATERPVS) { waterplanes[numwaterplanes].height = m.o.z; waterplanes[numwaterplanes].matsurfs.add(&m); numwaterplanes++; } nextmatsurf:; } } if(waterfalls.length() > 0 && numwaterplanes < MAXWATERPVS) numwaterplanes++; } void testpvs(int *vcsize) { lockpvs_(false); uint oldnumwaterplanes = numwaterplanes; int oldwaterplanes[MAXWATERPVS]; loopi(numwaterplanes) oldwaterplanes[i] = waterplanes[i].height; findwaterplanes(); pvsnode &root = origpvsnodes.add(); memset(root.edges.v, 0xFF, 3); root.flags = 0; root.children = 0; genpvsnodes(worldroot); genpvs_canceled = false; check_genpvs_progress = false; int size = *vcsize>0 ? *vcsize : 32; for(int mask = 1; mask < size; mask <<= 1) size &= ~mask; ivec o = camera1->o; o.mask(~(size-1)); pvsworker w; int len; lockedpvs = w.testviewcell(o, size, &lockedwaterpvs, &len); loopi(MAXWATERPVS) lockedwaterplanes[i] = waterplanes[i].height; lockpvs = 1; conoutf("generated test view cell of size %d at %.1f, %.1f, %.1f (%d B)", size, camera1->o.x, camera1->o.y, camera1->o.z, len); origpvsnodes.setsize(0); numwaterplanes = oldnumwaterplanes; loopi(numwaterplanes) waterplanes[i].height = oldwaterplanes[i]; } COMMAND(testpvs, "i"); void genpvs(int *viewcellsize) { if(worldsize > 1<<15) { conoutf(CON_ERROR, "map is too large for PVS"); return; } renderbackground("generating PVS (esc to abort)"); genpvs_canceled = false; Uint32 start = SDL_GetTicks(); renderprogress(0, "finding view cells"); clearpvs(); calcpvsbounds(); findwaterplanes(); pvsnode &root = origpvsnodes.add(); memset(root.edges.v, 0xFF, 3); root.flags = 0; root.children = 0; genpvsnodes(worldroot); totalviewcells = countviewcells(worldroot, ivec(0, 0, 0), worldsize>>1, *viewcellsize>0 ? *viewcellsize : 32); numviewcells = 0; genpvs_canceled = false; check_genpvs_progress = false; SDL_TimerID timer = NULL; int numthreads = pvsthreads > 0 ? pvsthreads : numcpus; if(numthreads<=1) { pvsworkers.add(new pvsworker); timer = SDL_AddTimer(500, genpvs_timer, NULL); } viewcells = new viewcellnode; genviewcells(*viewcells, worldroot, ivec(0, 0, 0), worldsize>>1, *viewcellsize>0 ? *viewcellsize : 32); if(numthreads<=1) { SDL_RemoveTimer(timer); } else { renderprogress(0, "creating threads"); if(!pvsmutex) pvsmutex = SDL_CreateMutex(); if(!viewcellmutex) viewcellmutex = SDL_CreateMutex(); loopi(numthreads) { pvsworker *w = pvsworkers.add(new pvsworker); w->thread = SDL_CreateThread(pvsworker::run, w); } show_genpvs_progress(0, 0); while(!genpvs_canceled) { SDL_Delay(500); SDL_LockMutex(viewcellmutex); int unique = pvs.length(), processed = numviewcells, remaining = viewcellrequests.length(); SDL_UnlockMutex(viewcellmutex); show_genpvs_progress(unique, processed); if(!remaining) break; } SDL_LockMutex(viewcellmutex); viewcellrequests.setsize(0); SDL_UnlockMutex(viewcellmutex); loopv(pvsworkers) SDL_WaitThread(pvsworkers[i]->thread, NULL); } pvsworkers.deletecontents(); origpvsnodes.setsize(0); pvscompress.clear(); Uint32 end = SDL_GetTicks(); if(genpvs_canceled) { clearpvs(); conoutf("genpvs aborted"); } else conoutf("generated %d unique view cells totaling %.1f kB and averaging %d B (%.1f seconds)", pvs.length(), pvsbuf.length()/1024.0f, pvsbuf.length()/max(pvs.length(), 1), (end - start) / 1000.0f); } COMMAND(genpvs, "i"); void pvsstats() { conoutf("%d unique view cells totaling %.1f kB and averaging %d B", pvs.length(), pvsbuf.length()/1024.0f, pvsbuf.length()/max(pvs.length(), 1)); } COMMAND(pvsstats, ""); static inline bool pvsoccluded(uchar *buf, const ivec &co, int size, const ivec &bborigin, const ivec &bbsize) { uchar leafmask = buf[0]; loopoctabox(co, size, bborigin, bbsize) { ivec o(i, co.x, co.y, co.z, size); if(leafmask&(1<>1, bborigin, bbsize)&~leafvalues)) return false; } else if(!pvsoccluded(buf+9*buf[1+i], o, size>>1, bborigin, bbsize)) return false; } return true; } static inline bool pvsoccluded(uchar *buf, const ivec &bborigin, const ivec &bbsize) { int diff = (bborigin.x^(bborigin.x+bbsize.x)) | (bborigin.y^(bborigin.y+bbsize.y)) | (bborigin.z^(bborigin.z+bbsize.z)); if(diff&~((1<putchar(p.leafmask); loopi(8) { if(p.leafmask&(1<putlil(p.children[i].pvs); else saveviewcells(f, *p.children[i].node); } } void savepvs(stream *f) { uint totallen = pvsbuf.length() | (numwaterplanes>0 ? 0x80000000U : 0); f->putlil(totallen); if(numwaterplanes>0) { f->putlil(numwaterplanes); loopi(numwaterplanes) { f->putlil(waterplanes[i].height); if(waterplanes[i].height < 0) break; } } loopv(pvs) f->putlil(pvs[i].len); f->write(pvsbuf.getbuf(), pvsbuf.length()); saveviewcells(f, *viewcells); } viewcellnode *loadviewcells(stream *f) { viewcellnode *p = new viewcellnode; p->leafmask = f->getchar(); loopi(8) { if(p->leafmask&(1<children[i].pvs = f->getlil(); else p->children[i].node = loadviewcells(f); } return p; } void loadpvs(stream *f, int numpvs) { uint totallen = f->getlil(); if(totallen & 0x80000000U) { totallen &= ~0x80000000U; numwaterplanes = f->getlil(); loopi(numwaterplanes) waterplanes[i].height = f->getlil(); } int offset = 0; loopi(numpvs) { ushort len = f->getlil(); pvs.add(pvsdata(offset, len)); offset += len; } f->read(pvsbuf.reserve(totallen).buf, totallen); pvsbuf.advance(totallen); viewcells = loadviewcells(f); } int getnumviewcells() { return pvs.length(); } sauerbraten-0.0.20130203.dfsg/engine/worldio.cpp0000644000175000017500000014417112071421015021026 0ustar vincentvincent// worldio.cpp: loading & saving of maps and savegames #include "engine.h" void cutogz(char *s) { char *ogzp = strstr(s, ".ogz"); if(ogzp) *ogzp = '\0'; } void getmapfilenames(const char *fname, const char *cname, char *pakname, char *mapname, char *cfgname) { if(!cname) cname = fname; string name; copystring(name, cname, 100); cutogz(name); char *slash = strpbrk(name, "/\\"); if(slash) { copystring(pakname, name, slash-name+1); copystring(cfgname, slash+1); } else { copystring(pakname, "base"); copystring(cfgname, name); } if(strpbrk(fname, "/\\")) copystring(mapname, fname); else formatstring(mapname)("base/%s", fname); cutogz(mapname); } static void fixent(entity &e, int version) { if(version <= 10 && e.type >= 7) e.type++; if(version <= 12 && e.type >= 8) e.type++; if(version <= 14 && e.type >= ET_MAPMODEL && e.type <= 16) { if(e.type == 16) e.type = ET_MAPMODEL; else e.type++; } if(version <= 20 && e.type >= ET_ENVMAP) e.type++; if(version <= 21 && e.type >= ET_PARTICLES) e.type++; if(version <= 22 && e.type >= ET_SOUND) e.type++; if(version <= 23 && e.type >= ET_SPOTLIGHT) e.type++; if(version <= 30 && (e.type == ET_MAPMODEL || e.type == ET_PLAYERSTART)) e.attr1 = (int(e.attr1)+180)%360; if(version <= 31 && e.type == ET_MAPMODEL) { int yaw = (int(e.attr1)%360 + 360)%360 + 7; e.attr1 = yaw - yaw%15; } } bool loadents(const char *fname, vector &ents, uint *crc) { string pakname, mapname, mcfgname, ogzname; getmapfilenames(fname, NULL, pakname, mapname, mcfgname); formatstring(ogzname)("packages/%s.ogz", mapname); path(ogzname); stream *f = opengzfile(ogzname, "rb"); if(!f) return false; octaheader hdr; if(f->read(&hdr, 7*sizeof(int))!=int(7*sizeof(int))) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } lilswap(&hdr.version, 6); if(memcmp(hdr.magic, "OCTA", 4) || hdr.worldsize <= 0|| hdr.numents < 0) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } if(hdr.version>MAPVERSION) { conoutf(CON_ERROR, "map %s requires a newer version of Cube 2: Sauerbraten", ogzname); delete f; return false; } compatheader chdr; if(hdr.version <= 28) { if(f->read(&chdr.lightprecision, sizeof(chdr) - 7*sizeof(int)) != int(sizeof(chdr) - 7*sizeof(int))) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } } else { int extra = 0; if(hdr.version <= 29) extra++; if(f->read(&hdr.blendmap, sizeof(hdr) - (7+extra)*sizeof(int)) != int(sizeof(hdr) - (7+extra)*sizeof(int))) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } } if(hdr.version <= 28) { lilswap(&chdr.lightprecision, 3); hdr.blendmap = chdr.blendmap; hdr.numvars = 0; hdr.numvslots = 0; } else { lilswap(&hdr.blendmap, 2); if(hdr.version <= 29) hdr.numvslots = 0; else lilswap(&hdr.numvslots, 1); } loopi(hdr.numvars) { int type = f->getchar(), ilen = f->getlil(); f->seek(ilen, SEEK_CUR); switch(type) { case ID_VAR: f->getlil(); break; case ID_FVAR: f->getlil(); break; case ID_SVAR: { int slen = f->getlil(); f->seek(slen, SEEK_CUR); break; } } } string gametype; copystring(gametype, "fps"); bool samegame = true; int eif = 0; if(hdr.version>=16) { int len = f->getchar(); f->read(gametype, len+1); } if(strcmp(gametype, game::gameident())) { samegame = false; conoutf(CON_WARN, "WARNING: loading map from %s game, ignoring entities except for lights/mapmodels", gametype); } if(hdr.version>=16) { eif = f->getlil(); int extrasize = f->getlil(); f->seek(extrasize, SEEK_CUR); } if(hdr.version<14) { f->seek(256, SEEK_CUR); } else { ushort nummru = f->getlil(); f->seek(nummru*sizeof(ushort), SEEK_CUR); } loopi(min(hdr.numents, MAXENTS)) { entity &e = ents.add(); f->read(&e, sizeof(entity)); lilswap(&e.o.x, 3); lilswap(&e.attr1, 5); fixent(e, hdr.version); if(eif > 0) f->seek(eif, SEEK_CUR); if(samegame) { entities::readent(e, NULL, hdr.version); } else if(e.type>=ET_GAMESPECIFIC || hdr.version<=14) { ents.pop(); continue; } } if(crc) { f->seek(0, SEEK_END); *crc = f->getcrc(); } delete f; return true; } #ifndef STANDALONE string ogzname, bakname, cfgname, picname; VARP(savebak, 0, 2, 2); void setmapfilenames(const char *fname, const char *cname = 0) { string pakname, mapname, mcfgname; getmapfilenames(fname, cname, pakname, mapname, mcfgname); formatstring(ogzname)("packages/%s.ogz", mapname); if(savebak==1) formatstring(bakname)("packages/%s.BAK", mapname); else formatstring(bakname)("packages/%s_%d.BAK", mapname, totalmillis); formatstring(cfgname)("packages/%s/%s.cfg", pakname, mcfgname); formatstring(picname)("packages/%s.jpg", mapname); path(ogzname); path(bakname); path(cfgname); path(picname); } void mapcfgname() { const char *mname = game::getclientmap(); if(!*mname) mname = "untitled"; string pakname, mapname, mcfgname; getmapfilenames(mname, NULL, pakname, mapname, mcfgname); defformatstring(cfgname)("packages/%s/%s.cfg", pakname, mcfgname); path(cfgname); result(cfgname); } COMMAND(mapcfgname, ""); void backup(char *name, char *backupname) { string backupfile; copystring(backupfile, findfile(backupname, "wb")); remove(backupfile); rename(findfile(name, "wb"), backupfile); } enum { OCTSAV_CHILDREN = 0, OCTSAV_EMPTY, OCTSAV_SOLID, OCTSAV_NORMAL, OCTSAV_LODCUBE }; static int savemapprogress = 0; void savec(cube *c, const ivec &o, int size, stream *f, bool nolms) { if((savemapprogress++&0xFFF)==0) renderprogress(float(savemapprogress)/allocnodes, "saving octree..."); loopi(8) { ivec co(i, o.x, o.y, o.z, size); if(c[i].children) { f->putchar(OCTSAV_CHILDREN); savec(c[i].children, co, size>>1, f, nolms); } else { int oflags = 0, surfmask = 0, totalverts = 0; if(c[i].material!=MAT_AIR) oflags |= 0x40; if(!nolms) { if(c[i].merged) oflags |= 0x80; if(c[i].ext) loopj(6) { const surfaceinfo &surf = c[i].ext->surfaces[j]; if(!surf.used()) continue; oflags |= 0x20; surfmask |= 1<putchar(oflags | OCTSAV_LODCUBE); else if(isempty(c[i])) f->putchar(oflags | OCTSAV_EMPTY); else if(isentirelysolid(c[i])) f->putchar(oflags | OCTSAV_SOLID); else { f->putchar(oflags | OCTSAV_NORMAL); f->write(c[i].edges, 12); } loopj(6) f->putlil(c[i].texture[j]); if(oflags&0x40) f->putlil(c[i].material); if(oflags&0x80) f->putchar(c[i].merged); if(oflags&0x20) { f->putchar(surfmask); f->putchar(totalverts); loopj(6) if(surfmask&(1<surfaces[j]; vertinfo *verts = c[i].ext->verts() + surf.verts; int layerverts = surf.numverts&MAXFACEVERTS, numverts = surf.totalverts(), vertmask = 0, vertorder = 0, uvorder = 0, dim = dimension(j), vc = C[dim], vr = R[dim]; if(numverts) { if(c[i].merged&(1<write(&surf, sizeof(surfaceinfo)); bool hasxyz = (vertmask&0x04)!=0, hasuv = (vertmask&0x40)!=0, hasnorm = (vertmask&0x80)!=0; if(layerverts == 4) { if(hasxyz && vertmask&0x01) { ivec v0 = verts[vertorder].getxyz(), v2 = verts[(vertorder+2)&3].getxyz(); f->putlil(v0[vc]); f->putlil(v0[vr]); f->putlil(v2[vc]); f->putlil(v2[vr]); hasxyz = false; } if(hasuv && vertmask&0x02) { const vertinfo &v0 = verts[uvorder], &v2 = verts[(uvorder+2)&3]; f->putlil(v0.u); f->putlil(v0.v); f->putlil(v2.u); f->putlil(v2.v); if(surf.numverts&LAYER_DUP) { const vertinfo &b0 = verts[4+uvorder], &b2 = verts[4+((uvorder+2)&3)]; f->putlil(b0.u); f->putlil(b0.v); f->putlil(b2.u); f->putlil(b2.v); } hasuv = false; } } if(hasnorm && vertmask&0x08) { f->putlil(verts[0].norm); hasnorm = false; } if(hasxyz || hasuv || hasnorm) loopk(layerverts) { const vertinfo &v = verts[(k+vertorder)%layerverts]; if(hasxyz) { ivec xyz = v.getxyz(); f->putlil(xyz[vc]); f->putlil(xyz[vr]); } if(hasuv) { f->putlil(v.u); f->putlil(v.v); } if(hasnorm) f->putlil(v.norm); } if(surf.numverts&LAYER_DUP) loopk(layerverts) { const vertinfo &v = verts[layerverts + (k+vertorder)%layerverts]; if(hasuv) { f->putlil(v.u); f->putlil(v.v); } } } } if(c[i].children) savec(c[i].children, co, size>>1, f, nolms); } } } struct surfacecompat { uchar texcoords[8]; uchar w, h; ushort x, y; uchar lmid, layer; }; struct normalscompat { bvec normals[4]; }; struct mergecompat { ushort u1, u2, v1, v2; }; cube *loadchildren(stream *f, const ivec &co, int size, bool &failed); void convertoldsurfaces(cube &c, const ivec &co, int size, surfacecompat *srcsurfs, int hassurfs, normalscompat *normals, int hasnorms, mergecompat *merges, int hasmerges) { surfaceinfo dstsurfs[6]; vertinfo verts[6*2*MAXFACEVERTS]; int totalverts = 0, numsurfs = 6; memset(dstsurfs, 0, sizeof(dstsurfs)); loopi(6) if((hassurfs|hasnorms|hasmerges)&(1<layer&2) { blend = &srcsurfs[numsurfs++]; dst.lmid[0] = src->lmid; dst.lmid[1] = blend->lmid; dst.numverts |= LAYER_BLEND; if(blend->lmid >= LMID_RESERVED && (src->x != blend->x || src->y != blend->y || src->w != blend->w || src->h != blend->h || memcmp(src->texcoords, blend->texcoords, sizeof(src->texcoords)))) dst.numverts |= LAYER_DUP; } else if(src->layer == 1) { dst.lmid[1] = src->lmid; dst.numverts |= LAYER_BOTTOM; } else { dst.lmid[0] = src->lmid; dst.numverts |= LAYER_TOP; } } else dst.numverts |= LAYER_TOP; bool uselms = hassurfs&(1<= LMID_RESERVED || dst.lmid[1] >= LMID_RESERVED || dst.numverts&~LAYER_TOP), usemerges = hasmerges&(1< 0 && (pos[k] == pos[0] || pos[k] == pos[k-1])) continue; vertinfo &dv = curverts[numverts++]; dv.setxyz(pos[k]); if(uselms) { float u = src->x + (src->texcoords[k*2] / 255.0f) * (src->w - 1), v = src->y + (src->texcoords[k*2+1] / 255.0f) * (src->h - 1); dv.u = ushort(floor(clamp((u) * float(USHRT_MAX+1)/LM_PACKW + 0.5f, 0.0f, float(USHRT_MAX)))); dv.v = ushort(floor(clamp((v) * float(USHRT_MAX+1)/LM_PACKH + 0.5f, 0.0f, float(USHRT_MAX)))); } else dv.u = dv.v = 0; dv.norm = usenorms && normals[i].normals[k] != bvec(128, 128, 128) ? encodenormal(normals[i].normals[k].tovec().normalize()) : 0; } dst.verts = totalverts; dst.numverts |= numverts; totalverts += numverts; if(dst.numverts&LAYER_DUP) loopk(4) { if(k > 0 && (pos[k] == pos[0] || pos[k] == pos[k-1])) continue; vertinfo &bv = verts[totalverts++]; bv.setxyz(pos[k]); bv.u = ushort(floor(clamp((blend->x + (blend->texcoords[k*2] / 255.0f) * (blend->w - 1)) * float(USHRT_MAX+1)/LM_PACKW, 0.0f, float(USHRT_MAX)))); bv.v = ushort(floor(clamp((blend->y + (blend->texcoords[k*2+1] / 255.0f) * (blend->h - 1)) * float(USHRT_MAX+1)/LM_PACKH, 0.0f, float(USHRT_MAX)))); bv.norm = usenorms && normals[i].normals[k] != bvec(128, 128, 128) ? encodenormal(normals[i].normals[k].tovec().normalize()) : 0; } } } setsurfaces(c, dstsurfs, verts, totalverts); } static inline int convertoldmaterial(int mat) { return ((mat&7)<>3)&3)<>5)&7)<getchar(); switch(octsav&0x7) { case OCTSAV_CHILDREN: c.children = loadchildren(f, co, size>>1, failed); return; case OCTSAV_LODCUBE: haschildren = true; break; case OCTSAV_EMPTY: emptyfaces(c); break; case OCTSAV_SOLID: solidfaces(c); break; case OCTSAV_NORMAL: f->read(c.edges, 12); break; default: failed = true; return; } loopi(6) c.texture[i] = mapversion<14 ? f->getchar() : f->getlil(); if(mapversion < 7) f->seek(3, SEEK_CUR); else if(mapversion <= 31) { uchar mask = f->getchar(); if(mask & 0x80) { int mat = f->getchar(); if(mapversion < 27) { static const ushort matconv[] = { MAT_AIR, MAT_WATER, MAT_CLIP, MAT_GLASS|MAT_CLIP, MAT_NOCLIP, MAT_LAVA|MAT_DEATH, MAT_GAMECLIP, MAT_DEATH }; c.material = size_t(mat) < sizeof(matconv)/sizeof(matconv[0]) ? matconv[mat] : MAT_AIR; } else c.material = convertoldmaterial(mat); } surfacecompat surfaces[12]; normalscompat normals[6]; mergecompat merges[6]; int hassurfs = 0, hasnorms = 0, hasmerges = 0; if(mask & 0x3F) { int numsurfs = 6; loopi(numsurfs) { if(i >= 6 || mask & (1 << i)) { f->read(&surfaces[i], sizeof(surfacecompat)); lilswap(&surfaces[i].x, 2); if(mapversion < 10) ++surfaces[i].lmid; if(mapversion < 18) { if(surfaces[i].lmid >= LMID_AMBIENT1) ++surfaces[i].lmid; if(surfaces[i].lmid >= LMID_BRIGHT1) ++surfaces[i].lmid; } if(mapversion < 19) { if(surfaces[i].lmid >= LMID_DARK) surfaces[i].lmid += 2; } if(i < 6) { if(mask & 0x40) { hasnorms |= 1<read(&normals[i], sizeof(normalscompat)); } if(surfaces[i].layer != 0 || surfaces[i].lmid != LMID_AMBIENT) hassurfs |= 1<>4) | ((hassurfs&0x03)<<4); } } if(mapversion >= 20) { if(octsav&0x80) { int merged = f->getchar(); c.merged = merged&0x3F; if(merged&0x80) { int mask = f->getchar(); if(mask) { hasmerges = mask&0x3F; loopi(6) if(mask&(1<read(m, sizeof(mergecompat)); lilswap(&m->u1, 4); if(mapversion <= 25) { int uorigin = m->u1 & 0xE000, vorigin = m->v1 & 0xE000; m->u1 = (m->u1 - uorigin) << 2; m->u2 = (m->u2 - uorigin) << 2; m->v1 = (m->v1 - vorigin) << 2; m->v2 = (m->v2 - vorigin) << 2; } } } } } } if(hassurfs || hasnorms || hasmerges) convertoldsurfaces(c, co, size, surfaces, hassurfs, normals, hasnorms, merges, hasmerges); } else { if(octsav&0x40) { if(mapversion <= 32) { int mat = f->getchar(); c.material = convertoldmaterial(mat); } else c.material = f->getlil(); } if(octsav&0x80) c.merged = f->getchar(); if(octsav&0x20) { int surfmask, totalverts; surfmask = f->getchar(); totalverts = f->getchar(); newcubeext(c, totalverts, false); memset(c.ext->surfaces, 0, sizeof(c.ext->surfaces)); memset(c.ext->verts(), 0, totalverts*sizeof(vertinfo)); int offset = 0; loopi(6) if(surfmask&(1<surfaces[i]; f->read(&surf, sizeof(surfaceinfo)); int vertmask = surf.verts, numverts = surf.totalverts(); if(!numverts) { surf.verts = 0; continue; } surf.verts = offset; vertinfo *verts = c.ext->verts() + offset; offset += numverts; ivec v[4], n; int layerverts = surf.numverts&MAXFACEVERTS, dim = dimension(i), vc = C[dim], vr = R[dim], bias = 0; genfaceverts(c, i, v); bool hasxyz = (vertmask&0x04)!=0, hasuv = (vertmask&0x40)!=0, hasnorm = (vertmask&0x80)!=0; if(hasxyz) { ivec e1, e2, e3; n.cross((e1 = v[1]).sub(v[0]), (e2 = v[2]).sub(v[0])); if(n.iszero()) n.cross(e2, (e3 = v[3]).sub(v[0])); bias = -n.dot(ivec(v[0]).mul(size).add(ivec(co).mask(0xFFF).shl(3))); } else { int vis = layerverts < 4 ? (vertmask&0x02 ? 2 : 1) : 3, order = vertmask&0x01 ? 1 : 0, k = 0; ivec vo = ivec(co).mask(0xFFF).shl(3); verts[k++].setxyz(v[order].mul(size).add(vo)); if(vis&1) verts[k++].setxyz(v[order+1].mul(size).add(vo)); verts[k++].setxyz(v[order+2].mul(size).add(vo)); if(vis&2) verts[k++].setxyz(v[(order+3)&3].mul(size).add(vo)); } if(layerverts == 4) { if(hasxyz && vertmask&0x01) { ushort c1 = f->getlil(), r1 = f->getlil(), c2 = f->getlil(), r2 = f->getlil(); ivec xyz; xyz[vc] = c1; xyz[vr] = r1; xyz[dim] = -(bias + n[vc]*xyz[vc] + n[vr]*xyz[vr])/n[dim]; verts[0].setxyz(xyz); xyz[vc] = c1; xyz[vr] = r2; xyz[dim] = -(bias + n[vc]*xyz[vc] + n[vr]*xyz[vr])/n[dim]; verts[1].setxyz(xyz); xyz[vc] = c2; xyz[vr] = r2; xyz[dim] = -(bias + n[vc]*xyz[vc] + n[vr]*xyz[vr])/n[dim]; verts[2].setxyz(xyz); xyz[vc] = c2; xyz[vr] = r1; xyz[dim] = -(bias + n[vc]*xyz[vc] + n[vr]*xyz[vr])/n[dim]; verts[3].setxyz(xyz); hasxyz = false; } if(hasuv && vertmask&0x02) { int uvorder = (vertmask&0x30)>>4; vertinfo &v0 = verts[uvorder], &v1 = verts[(uvorder+1)&3], &v2 = verts[(uvorder+2)&3], &v3 = verts[(uvorder+3)&3]; v0.u = f->getlil(); v0.v = f->getlil(); v2.u = f->getlil(); v2.v = f->getlil(); v1.u = v0.u; v1.v = v2.v; v3.u = v2.u; v3.v = v0.v; if(surf.numverts&LAYER_DUP) { vertinfo &b0 = verts[4+uvorder], &b1 = verts[4+((uvorder+1)&3)], &b2 = verts[4+((uvorder+2)&3)], &b3 = verts[4+((uvorder+3)&3)]; b0.u = f->getlil(); b0.v = f->getlil(); b2.u = f->getlil(); b2.v = f->getlil(); b1.u = b0.u; b1.v = b2.v; b3.u = b2.u; b3.v = b0.v; } hasuv = false; } } if(hasnorm && vertmask&0x08) { ushort norm = f->getlil(); loopk(layerverts) verts[k].norm = norm; hasnorm = false; } if(hasxyz || hasuv || hasnorm) loopk(layerverts) { vertinfo &v = verts[k]; if(hasxyz) { ivec xyz; xyz[vc] = f->getlil(); xyz[vr] = f->getlil(); xyz[dim] = -(bias + n[vc]*xyz[vc] + n[vr]*xyz[vr])/n[dim]; v.setxyz(xyz); } if(hasuv) { v.u = f->getlil(); v.v = f->getlil(); } if(hasnorm) v.norm = f->getlil(); } if(surf.numverts&LAYER_DUP) loopk(layerverts) { vertinfo &v = verts[k+layerverts], &t = verts[k]; v.setxyz(t.x, t.y, t.z); if(hasuv) { v.u = f->getlil(); v.v = f->getlil(); } v.norm = t.norm; } } } } c.children = (haschildren ? loadchildren(f, co, size>>1, failed) : NULL); } cube *loadchildren(stream *f, const ivec &co, int size, bool &failed) { cube *c = newcubes(); loopi(8) { loadc(f, c[i], ivec(i, co.x, co.y, co.z, size), size, failed); if(failed) break; } return c; } VAR(dbgvars, 0, 0, 1); void savevslot(stream *f, VSlot &vs, int prev) { f->putlil(vs.changed); f->putlil(prev); if(vs.changed & (1<putlil(vs.params.length()); loopv(vs.params) { ShaderParam &p = vs.params[i]; f->putlil(strlen(p.name)); f->write(p.name, strlen(p.name)); loopk(4) f->putlil(p.val[k]); } } if(vs.changed & (1<putlil(vs.scale); if(vs.changed & (1<putlil(vs.rotation); if(vs.changed & (1<putlil(vs.xoffset); f->putlil(vs.yoffset); } if(vs.changed & (1<putlil(vs.scrollS); f->putlil(vs.scrollT); } if(vs.changed & (1<putlil(vs.layer); if(vs.changed & (1<putlil(vs.alphafront); f->putlil(vs.alphaback); } if(vs.changed & (1<putlil(vs.colorscale[k]); } } void savevslots(stream *f, int numvslots) { if(vslots.empty()) return; int *prev = new int[numvslots]; memset(prev, -1, numvslots*sizeof(int)); loopi(numvslots) { VSlot *vs = vslots[i]; if(vs->changed) continue; for(;;) { VSlot *cur = vs; do vs = vs->next; while(vs && vs->index >= numvslots); if(!vs) break; prev[vs->index] = cur->index; } } int lastroot = 0; loopi(numvslots) { VSlot &vs = *vslots[i]; if(!vs.changed) continue; if(lastroot < i) f->putlil(-(i - lastroot)); savevslot(f, vs, prev[i]); lastroot = i+1; } if(lastroot < numvslots) f->putlil(-(numvslots - lastroot)); delete[] prev; } void loadvslot(stream *f, VSlot &vs, int changed) { vs.changed = changed; if(vs.changed & (1<getlil(); string name; loopi(numparams) { ShaderParam &p = vs.params.add(); int nlen = f->getlil(); f->read(name, min(nlen, MAXSTRLEN-1)); name[min(nlen, MAXSTRLEN-1)] = '\0'; if(nlen >= MAXSTRLEN) f->seek(nlen - (MAXSTRLEN-1), SEEK_CUR); p.name = getshaderparamname(name); p.type = SHPARAM_LOOKUP; p.index = -1; p.loc = -1; loopk(4) p.val[k] = f->getlil(); } } if(vs.changed & (1<getlil(); if(vs.changed & (1<getlil(); if(vs.changed & (1<getlil(); vs.yoffset = f->getlil(); } if(vs.changed & (1<getlil(); vs.scrollT = f->getlil(); } if(vs.changed & (1<getlil(); if(vs.changed & (1<getlil(); vs.alphaback = f->getlil(); } if(vs.changed & (1<getlil(); } } void loadvslots(stream *f, int numvslots) { int *prev = new int[numvslots]; memset(prev, -1, numvslots*sizeof(int)); while(numvslots > 0) { int changed = f->getlil(); if(changed < 0) { loopi(-changed) vslots.add(new VSlot(NULL, vslots.length())); numvslots += changed; } else { prev[vslots.length()] = f->getlil(); loadvslot(f, *vslots.add(new VSlot(NULL, vslots.length())), changed); numvslots--; } } loopv(vslots) if(vslots.inrange(prev[i])) vslots[prev[i]]->next = vslots[i]; delete[] prev; } bool save_world(const char *mname, bool nolms) { if(!*mname) mname = game::getclientmap(); setmapfilenames(*mname ? mname : "untitled"); if(savebak) backup(ogzname, bakname); stream *f = opengzfile(ogzname, "wb"); if(!f) { conoutf(CON_WARN, "could not write map to %s", ogzname); return false; } int numvslots = vslots.length(); if(!nolms && !multiplayer(false)) { numvslots = compactvslots(); allchanged(); } savemapprogress = 0; renderprogress(0, "saving map..."); octaheader hdr; memcpy(hdr.magic, "OCTA", 4); hdr.version = MAPVERSION; hdr.headersize = sizeof(hdr); hdr.worldsize = worldsize; hdr.numents = 0; const vector &ents = entities::getents(); loopv(ents) if(ents[i]->type!=ET_EMPTY || nolms) hdr.numents++; hdr.numpvs = nolms ? 0 : getnumviewcells(); hdr.lightmaps = nolms ? 0 : lightmaps.length(); hdr.blendmap = shouldsaveblendmap(); hdr.numvars = 0; hdr.numvslots = numvslots; enumerate(idents, ident, id, { if((id.type == ID_VAR || id.type == ID_FVAR || id.type == ID_SVAR) && id.flags&IDF_OVERRIDE && !(id.flags&IDF_READONLY) && id.flags&IDF_OVERRIDDEN) hdr.numvars++; }); lilswap(&hdr.version, 9); f->write(&hdr, sizeof(hdr)); enumerate(idents, ident, id, { if((id.type!=ID_VAR && id.type!=ID_FVAR && id.type!=ID_SVAR) || !(id.flags&IDF_OVERRIDE) || id.flags&IDF_READONLY || !(id.flags&IDF_OVERRIDDEN)) continue; f->putchar(id.type); f->putlil(strlen(id.name)); f->write(id.name, strlen(id.name)); switch(id.type) { case ID_VAR: if(dbgvars) conoutf(CON_DEBUG, "wrote var %s: %d", id.name, *id.storage.i); f->putlil(*id.storage.i); break; case ID_FVAR: if(dbgvars) conoutf(CON_DEBUG, "wrote fvar %s: %f", id.name, *id.storage.f); f->putlil(*id.storage.f); break; case ID_SVAR: if(dbgvars) conoutf(CON_DEBUG, "wrote svar %s: %s", id.name, *id.storage.s); f->putlil(strlen(*id.storage.s)); f->write(*id.storage.s, strlen(*id.storage.s)); break; } }); if(dbgvars) conoutf(CON_DEBUG, "wrote %d vars", hdr.numvars); f->putchar((int)strlen(game::gameident())); f->write(game::gameident(), (int)strlen(game::gameident())+1); f->putlil(entities::extraentinfosize()); vector extras; game::writegamedata(extras); f->putlil(extras.length()); f->write(extras.getbuf(), extras.length()); f->putlil(texmru.length()); loopv(texmru) f->putlil(texmru[i]); char *ebuf = new char[entities::extraentinfosize()]; loopv(ents) { if(ents[i]->type!=ET_EMPTY || nolms) { entity tmp = *ents[i]; lilswap(&tmp.o.x, 3); lilswap(&tmp.attr1, 5); f->write(&tmp, sizeof(entity)); entities::writeent(*ents[i], ebuf); if(entities::extraentinfosize()) f->write(ebuf, entities::extraentinfosize()); } } delete[] ebuf; savevslots(f, numvslots); renderprogress(0, "saving octree..."); savec(worldroot, ivec(0, 0, 0), worldsize>>1, f, nolms); if(!nolms) { if(lightmaps.length()) renderprogress(0, "saving lightmaps..."); loopv(lightmaps) { LightMap &lm = lightmaps[i]; f->putchar(lm.type | (lm.unlitx>=0 ? 0x80 : 0)); if(lm.unlitx>=0) { f->putlil(ushort(lm.unlitx)); f->putlil(ushort(lm.unlity)); } f->write(lm.data, lm.bpp*LM_PACKW*LM_PACKH); renderprogress(float(i+1)/lightmaps.length(), "saving lightmaps..."); } if(getnumviewcells()>0) { renderprogress(0, "saving pvs..."); savepvs(f); } } if(shouldsaveblendmap()) { renderprogress(0, "saving blendmap..."); saveblendmap(f); } delete f; conoutf("wrote map file %s", ogzname); return true; } static uint mapcrc = 0; uint getmapcrc() { return mapcrc; } void clearmapcrc() { mapcrc = 0; } bool load_world(const char *mname, const char *cname) // still supports all map formats that have existed since the earliest cube betas! { int loadingstart = SDL_GetTicks(); setmapfilenames(mname, cname); stream *f = opengzfile(ogzname, "rb"); if(!f) { conoutf(CON_ERROR, "could not read map %s", ogzname); return false; } octaheader hdr; if(f->read(&hdr, 7*sizeof(int))!=int(7*sizeof(int))) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } lilswap(&hdr.version, 6); if(memcmp(hdr.magic, "OCTA", 4) || hdr.worldsize <= 0|| hdr.numents < 0) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } if(hdr.version>MAPVERSION) { conoutf(CON_ERROR, "map %s requires a newer version of Cube 2: Sauerbraten", ogzname); delete f; return false; } compatheader chdr; if(hdr.version <= 28) { if(f->read(&chdr.lightprecision, sizeof(chdr) - 7*sizeof(int)) != int(sizeof(chdr) - 7*sizeof(int))) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } } else { int extra = 0; if(hdr.version <= 29) extra++; if(f->read(&hdr.blendmap, sizeof(hdr) - (7+extra)*sizeof(int)) != int(sizeof(hdr) - (7+extra)*sizeof(int))) { conoutf(CON_ERROR, "map %s has malformatted header", ogzname); delete f; return false; } } resetmap(); Texture *mapshot = textureload(picname, 3, true, false); renderbackground("loading...", mapshot, mname, game::getmapinfo()); setvar("mapversion", hdr.version, true, false); if(hdr.version <= 28) { lilswap(&chdr.lightprecision, 3); if(chdr.lightprecision) setvar("lightprecision", chdr.lightprecision); if(chdr.lighterror) setvar("lighterror", chdr.lighterror); if(chdr.bumperror) setvar("bumperror", chdr.bumperror); setvar("lightlod", chdr.lightlod); if(chdr.ambient) setvar("ambient", chdr.ambient); setvar("skylight", (int(chdr.skylight[0])<<16) | (int(chdr.skylight[1])<<8) | int(chdr.skylight[2])); setvar("watercolour", (int(chdr.watercolour[0])<<16) | (int(chdr.watercolour[1])<<8) | int(chdr.watercolour[2]), true); setvar("waterfallcolour", (int(chdr.waterfallcolour[0])<<16) | (int(chdr.waterfallcolour[1])<<8) | int(chdr.waterfallcolour[2])); setvar("lavacolour", (int(chdr.lavacolour[0])<<16) | (int(chdr.lavacolour[1])<<8) | int(chdr.lavacolour[2])); setvar("fullbright", 0, true); if(chdr.lerpsubdivsize || chdr.lerpangle) setvar("lerpangle", chdr.lerpangle); if(chdr.lerpsubdivsize) { setvar("lerpsubdiv", chdr.lerpsubdiv); setvar("lerpsubdivsize", chdr.lerpsubdivsize); } setsvar("maptitle", chdr.maptitle); hdr.blendmap = chdr.blendmap; hdr.numvars = 0; hdr.numvslots = 0; } else { lilswap(&hdr.blendmap, 2); if(hdr.version <= 29) hdr.numvslots = 0; else lilswap(&hdr.numvslots, 1); } renderprogress(0, "clearing world..."); freeocta(worldroot); worldroot = NULL; setvar("mapsize", hdr.worldsize, true, false); int worldscale = 0; while(1<getchar(), ilen = f->getlil(); string name; f->read(name, min(ilen, MAXSTRLEN-1)); name[min(ilen, MAXSTRLEN-1)] = '\0'; if(ilen >= MAXSTRLEN) f->seek(ilen - (MAXSTRLEN-1), SEEK_CUR); ident *id = getident(name); bool exists = id && id->type == type && id->flags&IDF_OVERRIDE; switch(type) { case ID_VAR: { int val = f->getlil(); if(exists && id->minval <= id->maxval) setvar(name, val); if(dbgvars) conoutf(CON_DEBUG, "read var %s: %d", name, val); break; } case ID_FVAR: { float val = f->getlil(); if(exists && id->minvalf <= id->maxvalf) setfvar(name, val); if(dbgvars) conoutf(CON_DEBUG, "read fvar %s: %f", name, val); break; } case ID_SVAR: { int slen = f->getlil(); string val; f->read(val, min(slen, MAXSTRLEN-1)); val[min(slen, MAXSTRLEN-1)] = '\0'; if(slen >= MAXSTRLEN) f->seek(slen - (MAXSTRLEN-1), SEEK_CUR); if(exists) setsvar(name, val); if(dbgvars) conoutf(CON_DEBUG, "read svar %s: %s", name, val); break; } } } if(dbgvars) conoutf(CON_DEBUG, "read %d vars", hdr.numvars); string gametype; copystring(gametype, "fps"); bool samegame = true; int eif = 0; if(hdr.version>=16) { int len = f->getchar(); f->read(gametype, len+1); } if(strcmp(gametype, game::gameident())!=0) { samegame = false; conoutf(CON_WARN, "WARNING: loading map from %s game, ignoring entities except for lights/mapmodels", gametype); } if(hdr.version>=16) { eif = f->getlil(); int extrasize = f->getlil(); vector extras; f->read(extras.pad(extrasize), extrasize); if(samegame) game::readgamedata(extras); } texmru.shrink(0); if(hdr.version<14) { uchar oldtl[256]; f->read(oldtl, sizeof(oldtl)); loopi(256) texmru.add(oldtl[i]); } else { ushort nummru = f->getlil(); loopi(nummru) texmru.add(f->getlil()); } renderprogress(0, "loading entities..."); vector &ents = entities::getents(); int einfosize = entities::extraentinfosize(); char *ebuf = einfosize > 0 ? new char[einfosize] : NULL; loopi(min(hdr.numents, MAXENTS)) { extentity &e = *entities::newentity(); ents.add(&e); f->read(&e, sizeof(entity)); lilswap(&e.o.x, 3); lilswap(&e.attr1, 5); e.spawned = false; e.inoctanode = false; fixent(e, hdr.version); if(samegame) { if(einfosize > 0) f->read(ebuf, einfosize); entities::readent(e, ebuf, mapversion); } else { if(eif > 0) f->seek(eif, SEEK_CUR); if(e.type>=ET_GAMESPECIFIC || hdr.version<=14) { entities::deleteentity(ents.pop()); continue; } } if(!insideworld(e.o)) { if(e.type != ET_LIGHT && e.type != ET_SPOTLIGHT) { conoutf(CON_WARN, "warning: ent outside of world: enttype[%s] index %d (%f, %f, %f)", entities::entname(e.type), i, e.o.x, e.o.y, e.o.z); } } if(hdr.version <= 14 && e.type == ET_MAPMODEL) { e.o.z += e.attr3; if(e.attr4) conoutf(CON_WARN, "warning: mapmodel ent (index %d) uses texture slot %d", i, e.attr4); e.attr3 = e.attr4 = 0; } } if(ebuf) delete[] ebuf; if(hdr.numents > MAXENTS) { conoutf(CON_WARN, "warning: map has %d entities", hdr.numents); f->seek((hdr.numents-MAXENTS)*(samegame ? sizeof(entity) + einfosize : eif), SEEK_CUR); } renderprogress(0, "loading slots..."); loadvslots(f, hdr.numvslots); renderprogress(0, "loading octree..."); bool failed = false; worldroot = loadchildren(f, ivec(0, 0, 0), hdr.worldsize>>1, failed); if(failed) conoutf(CON_ERROR, "garbage in map"); renderprogress(0, "validating..."); validatec(worldroot, hdr.worldsize>>1); if(!failed) { if(hdr.version >= 7) loopi(hdr.lightmaps) { renderprogress(i/(float)hdr.lightmaps, "loading lightmaps..."); LightMap &lm = lightmaps.add(); if(hdr.version >= 17) { int type = f->getchar(); lm.type = type&0x7F; if(hdr.version >= 20 && type&0x80) { lm.unlitx = f->getlil(); lm.unlity = f->getlil(); } } if(lm.type&LM_ALPHA && (lm.type&LM_TYPE)!=LM_BUMPMAP1) lm.bpp = 4; lm.data = new uchar[lm.bpp*LM_PACKW*LM_PACKH]; f->read(lm.data, lm.bpp * LM_PACKW * LM_PACKH); lm.finalize(); } if(hdr.version >= 25 && hdr.numpvs > 0) loadpvs(f, hdr.numpvs); if(hdr.version >= 28 && hdr.blendmap) loadblendmap(f, hdr.blendmap); } mapcrc = f->getcrc(); delete f; conoutf("read map %s (%.1f seconds)", ogzname, (SDL_GetTicks()-loadingstart)/1000.0f); clearmainmenu(); identflags |= IDF_OVERRIDDEN; execfile("data/default_map_settings.cfg", false); execfile(cfgname, false); identflags &= ~IDF_OVERRIDDEN; extern void fixlightmapnormals(); if(hdr.version <= 25) fixlightmapnormals(); extern void fixrotatedlightmaps(); if(hdr.version <= 31) fixrotatedlightmaps(); preloadusedmapmodels(true); game::preload(); flushpreloadedmodels(); preloadmapsounds(); entitiesinoctanodes(); attachentities(); initlights(); allchanged(true); renderbackground("loading...", mapshot, mname, game::getmapinfo()); if(maptitle[0] && strcmp(maptitle, "Untitled Map by Unknown")) conoutf(CON_ECHO, "%s", maptitle); startmap(cname ? cname : mname); return true; } void savecurrentmap() { save_world(game::getclientmap()); } void savemap(char *mname) { save_world(mname); } COMMAND(savemap, "s"); COMMAND(savecurrentmap, ""); void writeobj(char *name) { defformatstring(fname)("%s.obj", name); stream *f = openfile(path(fname), "w"); if(!f) return; f->printf("# obj file of Cube 2 level\n\n"); defformatstring(mtlname)("%s.mtl", name); path(mtlname); f->printf("mtllib %s\n\n", mtlname); extern vector valist; vector verts; vector texcoords; hashtable shareverts(1<<16); hashtable sharetc(1<<16); hashtable > mtls(1<<8); vector usedmtl; vec bbmin(1e16f, 1e16f, 1e16f), bbmax(-1e16f, -1e16f, -1e16f); loopv(valist) { vtxarray &va = *valist[i]; ushort *edata = NULL; uchar *vdata = NULL; if(!readva(&va, edata, vdata)) continue; int vtxsize = VTXSIZE; ushort *idx = edata; loopj(va.texs) { elementset &es = va.eslist[j]; if(usedmtl.find(es.texture) < 0) usedmtl.add(es.texture); vector &keys = mtls[es.texture]; loopk(es.length[1]) { int n = idx[k] - va.voffset; const vec &pos = renderpath==R_FIXEDFUNCTION ? ((const vertexff *)&vdata[n*vtxsize])->pos : ((const vertex *)&vdata[n*vtxsize])->pos; vec2 tc(renderpath==R_FIXEDFUNCTION ? ((const vertexff *)&vdata[n*vtxsize])->u : ((const vertex *)&vdata[n*vtxsize])->u, renderpath==R_FIXEDFUNCTION ? ((const vertexff *)&vdata[n*vtxsize])->v : ((const vertex *)&vdata[n*vtxsize])->v); ivec &key = keys.add(); key.x = shareverts.access(pos, verts.length()); if(key.x == verts.length()) { verts.add(pos); loopl(3) { bbmin[l] = min(bbmin[l], pos[l]); bbmax[l] = max(bbmax[l], pos[l]); } } key.y = sharetc.access(tc, texcoords.length()); if(key.y == texcoords.length()) texcoords.add(tc); } idx += es.length[1]; } delete[] edata; delete[] vdata; } vec center(-(bbmax.x + bbmin.x)/2, -(bbmax.y + bbmin.y)/2, -bbmin.z); loopv(verts) { vec v = verts[i]; v.add(center); if(v.y != floor(v.y)) f->printf("v %.3f ", -v.y); else f->printf("v %d ", int(-v.y)); if(v.z != floor(v.z)) f->printf("%.3f ", v.z); else f->printf("%d ", int(v.z)); if(v.x != floor(v.x)) f->printf("%.3f\n", v.x); else f->printf("%d\n", int(v.x)); } f->printf("\n"); loopv(texcoords) { const vec2 &tc = texcoords[i]; f->printf("vt %.6f %.6f\n", tc.x, 1-tc.y); } f->printf("\n"); usedmtl.sort(); loopv(usedmtl) { vector &keys = mtls[usedmtl[i]]; f->printf("g slot%d\n", usedmtl[i]); f->printf("usemtl slot%d\n\n", usedmtl[i]); for(int i = 0; i < keys.length(); i += 3) { f->printf("f"); loopk(3) f->printf(" %d/%d", keys[i+2-k].x+1, keys[i+2-k].y+1); f->printf("\n"); } f->printf("\n"); } delete f; f = openfile(mtlname, "w"); if(!f) return; f->printf("# mtl file of Cube 2 level\n\n"); loopv(usedmtl) { VSlot &vslot = lookupvslot(usedmtl[i], false); f->printf("newmtl slot%d\n", usedmtl[i]); f->printf("map_Kd %s\n", vslot.slot->sts.empty() ? notexture->name : path(makerelpath("packages", vslot.slot->sts[0].name))); f->printf("\n"); } delete f; } COMMAND(writeobj, "s"); #endif sauerbraten-0.0.20130203.dfsg/engine/server.cpp0000644000175000017500000007426612103333554020672 0ustar vincentvincent// server.cpp: little more than enhanced multicaster // runs dedicated or as client coroutine #include "engine.h" #define LOGSTRLEN 512 static FILE *logfile = NULL; void closelogfile() { if(logfile) { fclose(logfile); logfile = NULL; } } FILE *getlogfile() { #ifdef WIN32 return logfile; #else return logfile ? logfile : stdout; #endif } void setlogfile(const char *fname) { closelogfile(); if(fname && fname[0]) { fname = findfile(fname, "w"); if(fname) logfile = fopen(fname, "w"); } FILE *f = getlogfile(); if(f) setvbuf(f, NULL, _IOLBF, BUFSIZ); } void logoutf(const char *fmt, ...) { va_list args; va_start(args, fmt); logoutfv(fmt, args); va_end(args); } static void writelog(FILE *file, const char *buf) { static uchar ubuf[512]; int len = strlen(buf), carry = 0; while(carry < len) { int numu = encodeutf8(ubuf, sizeof(ubuf)-1, &((const uchar *)buf)[carry], len - carry, &carry); if(carry >= len) ubuf[numu++] = '\n'; fwrite(ubuf, 1, numu, file); } } static void writelogv(FILE *file, const char *fmt, va_list args) { static char buf[LOGSTRLEN]; vformatstring(buf, fmt, args, sizeof(buf)); writelog(file, buf); } #ifdef STANDALONE void fatal(const char *fmt, ...) { void cleanupserver(); cleanupserver(); defvformatstring(msg,fmt,fmt); if(logfile) logoutf("%s", msg); #ifdef WIN32 MessageBox(NULL, msg, "Cube 2: Sauerbraten fatal error", MB_OK|MB_SYSTEMMODAL); #else fprintf(stderr, "server error: %s\n", msg); #endif closelogfile(); exit(EXIT_FAILURE); } void conoutfv(int type, const char *fmt, va_list args) { string sf, sp; vformatstring(sf, fmt, args); filtertext(sp, sf); logoutf("%s", sp); } void conoutf(const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(CON_INFO, fmt, args); va_end(args); } void conoutf(int type, const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(type, fmt, args); va_end(args); } #endif enum { ST_EMPTY, ST_LOCAL, ST_TCPIP }; struct client // server side version of "dynent" type { int type; int num; ENetPeer *peer; string hostname; void *info; }; vector clients; ENetHost *serverhost = NULL; int laststatus = 0; ENetSocket pongsock = ENET_SOCKET_NULL, lansock = ENET_SOCKET_NULL; int localclients = 0, nonlocalclients = 0; bool hasnonlocalclients() { return nonlocalclients!=0; } bool haslocalclients() { return localclients!=0; } client &addclient(int type) { client *c = NULL; loopv(clients) if(clients[i]->type==ST_EMPTY) { c = clients[i]; break; } if(!c) { c = new client; c->num = clients.length(); clients.add(c); } c->info = server::newclientinfo(); c->type = type; switch(type) { case ST_TCPIP: nonlocalclients++; break; case ST_LOCAL: localclients++; break; } return *c; } void delclient(client *c) { if(!c) return; switch(c->type) { case ST_TCPIP: nonlocalclients--; if(c->peer) c->peer->data = NULL; break; case ST_LOCAL: localclients--; break; case ST_EMPTY: return; } c->type = ST_EMPTY; c->peer = NULL; if(c->info) { server::deleteclientinfo(c->info); c->info = NULL; } } void cleanupserver() { if(serverhost) enet_host_destroy(serverhost); serverhost = NULL; if(pongsock != ENET_SOCKET_NULL) enet_socket_destroy(pongsock); if(lansock != ENET_SOCKET_NULL) enet_socket_destroy(lansock); pongsock = lansock = ENET_SOCKET_NULL; } void process(ENetPacket *packet, int sender, int chan); //void disconnect_client(int n, int reason); int getservermtu() { return serverhost ? serverhost->mtu : -1; } void *getclientinfo(int i) { return !clients.inrange(i) || clients[i]->type==ST_EMPTY ? NULL : clients[i]->info; } ENetPeer *getclientpeer(int i) { return clients.inrange(i) && clients[i]->type==ST_TCPIP ? clients[i]->peer : NULL; } int getnumclients() { return clients.length(); } uint getclientip(int n) { return clients.inrange(n) && clients[n]->type==ST_TCPIP ? clients[n]->peer->address.host : 0; } void sendpacket(int n, int chan, ENetPacket *packet, int exclude) { if(n<0) { server::recordpacket(chan, packet->data, packet->dataLength); loopv(clients) if(i!=exclude && server::allowbroadcast(i)) sendpacket(i, chan, packet); return; } switch(clients[n]->type) { case ST_TCPIP: { enet_peer_send(clients[n]->peer, chan, packet); break; } #ifndef STANDALONE case ST_LOCAL: localservertoclient(chan, packet); break; #endif } } ENetPacket *sendf(int cn, int chan, const char *format, ...) { int exclude = -1; bool reliable = false; if(*format=='r') { reliable = true; ++format; } packetbuf p(MAXTRANS, reliable ? ENET_PACKET_FLAG_RELIABLE : 0); va_list args; va_start(args, format); while(*format) switch(*format++) { case 'x': exclude = va_arg(args, int); break; case 'v': { int n = va_arg(args, int); int *v = va_arg(args, int *); loopi(n) putint(p, v[i]); break; } case 'i': { int n = isdigit(*format) ? *format++-'0' : 1; loopi(n) putint(p, va_arg(args, int)); break; } case 'f': { int n = isdigit(*format) ? *format++-'0' : 1; loopi(n) putfloat(p, (float)va_arg(args, double)); break; } case 's': sendstring(va_arg(args, const char *), p); break; case 'm': { int n = va_arg(args, int); p.put(va_arg(args, uchar *), n); break; } } va_end(args); ENetPacket *packet = p.finalize(); sendpacket(cn, chan, packet, exclude); return packet->referenceCount > 0 ? packet : NULL; } ENetPacket *sendfile(int cn, int chan, stream *file, const char *format, ...) { if(cn < 0) { #ifdef STANDALONE return NULL; #endif } else if(!clients.inrange(cn)) return NULL; int len = (int)min(file->size(), stream::offset(INT_MAX)); if(len <= 0 || len > 16<<20) return NULL; packetbuf p(MAXTRANS+len, ENET_PACKET_FLAG_RELIABLE); va_list args; va_start(args, format); while(*format) switch(*format++) { case 'i': { int n = isdigit(*format) ? *format++-'0' : 1; loopi(n) putint(p, va_arg(args, int)); break; } case 's': sendstring(va_arg(args, const char *), p); break; case 'l': putint(p, len); break; } va_end(args); file->seek(0, SEEK_SET); file->read(p.subbuf(len).buf, len); ENetPacket *packet = p.finalize(); if(cn >= 0) sendpacket(cn, chan, packet, -1); #ifndef STANDALONE else sendclientpacket(packet, chan); #endif return packet->referenceCount > 0 ? packet : NULL; } const char *disconnectreason(int reason) { switch(reason) { case DISC_EOP: return "end of packet"; case DISC_LOCAL: return "server is in local mode"; case DISC_KICK: return "kicked/banned"; case DISC_MSGERR: return "message error"; case DISC_IPBAN: return "ip is banned"; case DISC_PRIVATE: return "server is in private mode"; case DISC_MAXCLIENTS: return "server FULL"; case DISC_TIMEOUT: return "connection timed out"; case DISC_OVERFLOW: return "overflow"; case DISC_PASSWORD: return "invalid password"; default: return NULL; } } void disconnect_client(int n, int reason) { if(!clients.inrange(n) || clients[n]->type!=ST_TCPIP) return; enet_peer_disconnect(clients[n]->peer, reason); server::clientdisconnect(n); delclient(clients[n]); const char *msg = disconnectreason(reason); string s; if(msg) formatstring(s)("client (%s) disconnected because: %s", clients[n]->hostname, msg); else formatstring(s)("client (%s) disconnected", clients[n]->hostname); logoutf("%s", s); server::sendservmsg(s); } void kicknonlocalclients(int reason) { loopv(clients) if(clients[i]->type==ST_TCPIP) disconnect_client(i, reason); } void process(ENetPacket *packet, int sender, int chan) // sender may be -1 { packetbuf p(packet); server::parsepacket(sender, chan, p); if(p.overread()) { disconnect_client(sender, DISC_EOP); return; } } void localclienttoserver(int chan, ENetPacket *packet) { client *c = NULL; loopv(clients) if(clients[i]->type==ST_LOCAL) { c = clients[i]; break; } if(c) process(packet, c->num, chan); } #ifdef STANDALONE bool resolverwait(const char *name, ENetAddress *address) { return enet_address_set_host(address, name) >= 0; } int connectwithtimeout(ENetSocket sock, const char *hostname, const ENetAddress &remoteaddress) { int result = enet_socket_connect(sock, &remoteaddress); if(result<0) enet_socket_destroy(sock); return result; } #endif ENetSocket mastersock = ENET_SOCKET_NULL; ENetAddress masteraddress = { ENET_HOST_ANY, ENET_PORT_ANY }, serveraddress = { ENET_HOST_ANY, ENET_PORT_ANY }; int lastupdatemaster = 0; vector masterout, masterin; int masteroutpos = 0, masterinpos = 0; VARN(updatemaster, allowupdatemaster, 0, 1, 1); void disconnectmaster() { if(mastersock != ENET_SOCKET_NULL) { enet_socket_destroy(mastersock); mastersock = ENET_SOCKET_NULL; } masterout.setsize(0); masterin.setsize(0); masteroutpos = masterinpos = 0; masteraddress.host = ENET_HOST_ANY; masteraddress.port = ENET_PORT_ANY; lastupdatemaster = 0; } SVARF(mastername, server::defaultmaster(), disconnectmaster()); VARF(masterport, 1, server::masterport(), 0xFFFF, disconnectmaster()); ENetSocket connectmaster() { if(!mastername[0]) return ENET_SOCKET_NULL; if(masteraddress.host == ENET_HOST_ANY) { #ifdef STANDALONE logoutf("looking up %s...", mastername); #endif masteraddress.port = masterport; if(!resolverwait(mastername, &masteraddress)) return ENET_SOCKET_NULL; } ENetSocket sock = enet_socket_create(ENET_SOCKET_TYPE_STREAM); if(sock != ENET_SOCKET_NULL && serveraddress.host != ENET_HOST_ANY && enet_socket_bind(sock, &serveraddress) < 0) { enet_socket_destroy(sock); sock = ENET_SOCKET_NULL; } if(sock == ENET_SOCKET_NULL || connectwithtimeout(sock, mastername, masteraddress) < 0) { #ifdef STANDALONE logoutf(sock==ENET_SOCKET_NULL ? "could not open socket" : "could not connect"); #endif return ENET_SOCKET_NULL; } enet_socket_set_option(sock, ENET_SOCKOPT_NONBLOCK, 1); return sock; } bool requestmaster(const char *req) { if(mastersock == ENET_SOCKET_NULL) { mastersock = connectmaster(); if(mastersock == ENET_SOCKET_NULL) return false; } masterout.put(req, strlen(req)); return true; } bool requestmasterf(const char *fmt, ...) { defvformatstring(req, fmt, fmt); return requestmaster(req); } void processmasterinput() { if(masterinpos >= masterin.length()) return; char *input = &masterin[masterinpos], *end = (char *)memchr(input, '\n', masterin.length() - masterinpos); while(end) { *end++ = '\0'; const char *args = input; while(args < end && !iscubespace(*args)) args++; int cmdlen = args - input; while(args < end && iscubespace(*args)) args++; if(!strncmp(input, "failreg", cmdlen)) conoutf(CON_ERROR, "master server registration failed: %s", args); else if(!strncmp(input, "succreg", cmdlen)) conoutf("master server registration succeeded"); else server::processmasterinput(input, cmdlen, args); masterinpos = end - masterin.getbuf(); input = end; end = (char *)memchr(input, '\n', masterin.length() - masterinpos); } if(masterinpos >= masterin.length()) { masterin.setsize(0); masterinpos = 0; } } void flushmasteroutput() { if(masterout.empty()) return; ENetBuffer buf; buf.data = &masterout[masteroutpos]; buf.dataLength = masterout.length() - masteroutpos; int sent = enet_socket_send(mastersock, NULL, &buf, 1); if(sent >= 0) { masteroutpos += sent; if(masteroutpos >= masterout.length()) { masterout.setsize(0); masteroutpos = 0; } } else disconnectmaster(); } void flushmasterinput() { if(masterin.length() >= masterin.capacity()) masterin.reserve(4096); ENetBuffer buf; buf.data = masterin.getbuf() + masterin.length(); buf.dataLength = masterin.capacity() - masterin.length(); int recv = enet_socket_receive(mastersock, NULL, &buf, 1); if(recv > 0) { masterin.advance(recv); processmasterinput(); } else disconnectmaster(); } static ENetAddress pongaddr; void sendserverinforeply(ucharbuf &p) { ENetBuffer buf; buf.data = p.buf; buf.dataLength = p.length(); enet_socket_send(pongsock, &pongaddr, &buf, 1); } void checkserversockets() // reply all server info requests { static ENetSocketSet sockset; ENET_SOCKETSET_EMPTY(sockset); ENetSocket maxsock = pongsock; ENET_SOCKETSET_ADD(sockset, pongsock); if(mastersock != ENET_SOCKET_NULL) { maxsock = max(maxsock, mastersock); ENET_SOCKETSET_ADD(sockset, mastersock); } if(lansock != ENET_SOCKET_NULL) { maxsock = max(maxsock, lansock); ENET_SOCKETSET_ADD(sockset, lansock); } if(enet_socketset_select(maxsock, &sockset, NULL, 0) <= 0) return; ENetBuffer buf; uchar pong[MAXTRANS]; loopi(2) { ENetSocket sock = i ? lansock : pongsock; if(sock == ENET_SOCKET_NULL || !ENET_SOCKETSET_CHECK(sockset, sock)) continue; buf.data = pong; buf.dataLength = sizeof(pong); int len = enet_socket_receive(sock, &pongaddr, &buf, 1); if(len < 0) return; ucharbuf req(pong, len), p(pong, sizeof(pong)); p.len += len; server::serverinforeply(req, p); } if(mastersock != ENET_SOCKET_NULL && ENET_SOCKETSET_CHECK(sockset, mastersock)) flushmasterinput(); } #define DEFAULTCLIENTS 8 VARF(maxclients, 0, DEFAULTCLIENTS, MAXCLIENTS, { if(!maxclients) maxclients = DEFAULTCLIENTS; }); VAR(serveruprate, 0, 0, INT_MAX); SVAR(serverip, ""); VARF(serverport, 0, server::serverport(), 0xFFFF, { if(!serverport) serverport = server::serverport(); }); #ifdef STANDALONE int curtime = 0, lastmillis = 0, totalmillis = 0; #endif void updatemasterserver() { if(mastername[0] && allowupdatemaster) requestmasterf("regserv %d\n", serverport); lastupdatemaster = totalmillis ? totalmillis : 1; } uint totalsecs = 0; void updatetime() { static int lastsec = 0; if(totalmillis - lastsec >= 1000) { int cursecs = (totalmillis - lastsec) / 1000; totalsecs += cursecs; lastsec += cursecs * 1000; } } void serverslice(bool dedicated, uint timeout) // main server update, called from main loop in sp, or from below in dedicated server { if(!serverhost) { server::serverupdate(); server::sendpackets(); return; } // below is network only if(dedicated) { int millis = (int)enet_time_get(), elapsed = millis - totalmillis; static int timeerr = 0; int scaledtime = server::scaletime(elapsed) + timeerr; curtime = scaledtime/100; timeerr = scaledtime%100; if(server::ispaused()) curtime = 0; lastmillis += curtime; totalmillis = millis; updatetime(); } server::serverupdate(); flushmasteroutput(); checkserversockets(); if(!lastupdatemaster || totalmillis-lastupdatemaster>60*60*1000) // send alive signal to masterserver every hour of uptime updatemasterserver(); if(totalmillis-laststatus>60*1000) // display bandwidth stats, useful for server ops { laststatus = totalmillis; if(nonlocalclients || serverhost->totalSentData || serverhost->totalReceivedData) logoutf("status: %d remote clients, %.1f send, %.1f rec (K/sec)", nonlocalclients, serverhost->totalSentData/60.0f/1024, serverhost->totalReceivedData/60.0f/1024); serverhost->totalSentData = serverhost->totalReceivedData = 0; } ENetEvent event; bool serviced = false; while(!serviced) { if(enet_host_check_events(serverhost, &event) <= 0) { if(enet_host_service(serverhost, &event, timeout) <= 0) break; serviced = true; } switch(event.type) { case ENET_EVENT_TYPE_CONNECT: { client &c = addclient(ST_TCPIP); c.peer = event.peer; c.peer->data = &c; char hn[1024]; copystring(c.hostname, (enet_address_get_host_ip(&c.peer->address, hn, sizeof(hn))==0) ? hn : "unknown"); logoutf("client connected (%s)", c.hostname); int reason = server::clientconnect(c.num, c.peer->address.host); if(reason) disconnect_client(c.num, reason); break; } case ENET_EVENT_TYPE_RECEIVE: { client *c = (client *)event.peer->data; if(c) process(event.packet, c->num, event.channelID); if(event.packet->referenceCount==0) enet_packet_destroy(event.packet); break; } case ENET_EVENT_TYPE_DISCONNECT: { client *c = (client *)event.peer->data; if(!c) break; logoutf("disconnected client (%s)", c->hostname); server::clientdisconnect(c->num); delclient(c); break; } default: break; } } if(server::sendpackets()) enet_host_flush(serverhost); } void flushserver(bool force) { if(server::sendpackets(force) && serverhost) enet_host_flush(serverhost); } #ifndef STANDALONE void localdisconnect(bool cleanup) { bool disconnected = false; loopv(clients) if(clients[i]->type==ST_LOCAL) { server::localdisconnect(i); delclient(clients[i]); disconnected = true; } if(!disconnected) return; game::gamedisconnect(cleanup); mainmenu = 1; } void localconnect() { client &c = addclient(ST_LOCAL); copystring(c.hostname, "local"); game::gameconnect(false); server::localconnect(c.num); } #endif #ifdef WIN32 #include "shellapi.h" #define IDI_ICON1 1 static string apptip = ""; static HINSTANCE appinstance = NULL; static ATOM wndclass = 0; static HWND appwindow = NULL, conwindow = NULL; static HICON appicon = NULL; static HMENU appmenu = NULL; static HANDLE outhandle = NULL; static const int MAXLOGLINES = 200; struct logline { int len; char buf[LOGSTRLEN]; }; static ringbuf loglines; static void cleanupsystemtray() { NOTIFYICONDATA nid; memset(&nid, 0, sizeof(nid)); nid.cbSize = sizeof(nid); nid.hWnd = appwindow; nid.uID = IDI_ICON1; Shell_NotifyIcon(NIM_DELETE, &nid); } static bool setupsystemtray(UINT uCallbackMessage) { NOTIFYICONDATA nid; memset(&nid, 0, sizeof(nid)); nid.cbSize = sizeof(nid); nid.hWnd = appwindow; nid.uID = IDI_ICON1; nid.uCallbackMessage = uCallbackMessage; nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; nid.hIcon = appicon; strcpy(nid.szTip, apptip); if(Shell_NotifyIcon(NIM_ADD, &nid) != TRUE) return false; atexit(cleanupsystemtray); return true; } #if 0 static bool modifysystemtray() { NOTIFYICONDATA nid; memset(&nid, 0, sizeof(nid)); nid.cbSize = sizeof(nid); nid.hWnd = appwindow; nid.uID = IDI_ICON1; nid.uFlags = NIF_TIP; strcpy(nid.szTip, apptip); return Shell_NotifyIcon(NIM_MODIFY, &nid) == TRUE; } #endif static void cleanupwindow() { if(!appinstance) return; if(appmenu) { DestroyMenu(appmenu); appmenu = NULL; } if(wndclass) { UnregisterClass(MAKEINTATOM(wndclass), appinstance); wndclass = 0; } } static BOOL WINAPI consolehandler(DWORD dwCtrlType) { switch(dwCtrlType) { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: case CTRL_CLOSE_EVENT: exit(EXIT_SUCCESS); return TRUE; } return FALSE; } static void writeline(logline &line) { static uchar ubuf[512]; int len = strlen(line.buf), carry = 0; while(carry < len) { int numu = encodeutf8(ubuf, sizeof(ubuf), &((uchar *)line.buf)[carry], len - carry, &carry); DWORD written = 0; WriteConsole(outhandle, ubuf, numu, &written, NULL); } } static void setupconsole() { if(conwindow) return; if(!AllocConsole()) return; SetConsoleCtrlHandler(consolehandler, TRUE); conwindow = GetConsoleWindow(); SetConsoleTitle(apptip); //SendMessage(conwindow, WM_SETICON, ICON_SMALL, (LPARAM)appicon); SendMessage(conwindow, WM_SETICON, ICON_BIG, (LPARAM)appicon); outhandle = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO coninfo; GetConsoleScreenBufferInfo(outhandle, &coninfo); coninfo.dwSize.Y = MAXLOGLINES; SetConsoleScreenBufferSize(outhandle, coninfo.dwSize); SetConsoleCP(CP_UTF8); SetConsoleOutputCP(CP_UTF8); loopv(loglines) writeline(loglines[i]); } enum { MENU_OPENCONSOLE = 0, MENU_SHOWCONSOLE, MENU_HIDECONSOLE, MENU_EXIT }; static LRESULT CALLBACK handlemessages(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_APP: SetForegroundWindow(hWnd); switch(lParam) { //case WM_MOUSEMOVE: // break; case WM_LBUTTONUP: case WM_RBUTTONUP: { POINT pos; GetCursorPos(&pos); TrackPopupMenu(appmenu, TPM_CENTERALIGN|TPM_BOTTOMALIGN|TPM_RIGHTBUTTON, pos.x, pos.y, 0, hWnd, NULL); PostMessage(hWnd, WM_NULL, 0, 0); break; } } return 0; case WM_COMMAND: switch(LOWORD(wParam)) { case MENU_OPENCONSOLE: setupconsole(); if(conwindow) ModifyMenu(appmenu, 0, MF_BYPOSITION|MF_STRING, MENU_HIDECONSOLE, "Hide Console"); break; case MENU_SHOWCONSOLE: ShowWindow(conwindow, SW_SHOWNORMAL); ModifyMenu(appmenu, 0, MF_BYPOSITION|MF_STRING, MENU_HIDECONSOLE, "Hide Console"); break; case MENU_HIDECONSOLE: ShowWindow(conwindow, SW_HIDE); ModifyMenu(appmenu, 0, MF_BYPOSITION|MF_STRING, MENU_SHOWCONSOLE, "Show Console"); break; case MENU_EXIT: PostMessage(hWnd, WM_CLOSE, 0, 0); break; } return 0; case WM_CLOSE: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } static void setupwindow(const char *title) { copystring(apptip, title); //appinstance = GetModuleHandle(NULL); if(!appinstance) fatal("failed getting application instance"); appicon = LoadIcon(appinstance, MAKEINTRESOURCE(IDI_ICON1));//(HICON)LoadImage(appinstance, MAKEINTRESOURCE(IDI_ICON1), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE); if(!appicon) fatal("failed loading icon"); appmenu = CreatePopupMenu(); if(!appmenu) fatal("failed creating popup menu"); AppendMenu(appmenu, MF_STRING, MENU_OPENCONSOLE, "Open Console"); AppendMenu(appmenu, MF_SEPARATOR, 0, NULL); AppendMenu(appmenu, MF_STRING, MENU_EXIT, "Exit"); //SetMenuDefaultItem(appmenu, 0, FALSE); WNDCLASS wc; memset(&wc, 0, sizeof(wc)); wc.hCursor = NULL; //LoadCursor(NULL, IDC_ARROW); wc.hIcon = appicon; wc.lpszMenuName = NULL; wc.lpszClassName = title; wc.style = 0; wc.hInstance = appinstance; wc.lpfnWndProc = handlemessages; wc.cbWndExtra = 0; wc.cbClsExtra = 0; wndclass = RegisterClass(&wc); if(!wndclass) fatal("failed registering window class"); appwindow = CreateWindow(MAKEINTATOM(wndclass), title, 0, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, HWND_MESSAGE, NULL, appinstance, NULL); if(!appwindow) fatal("failed creating window"); atexit(cleanupwindow); if(!setupsystemtray(WM_APP)) fatal("failed adding to system tray"); } static char *parsecommandline(const char *src, vector &args) { char *buf = new char[strlen(src) + 1], *dst = buf; for(;;) { while(isspace(*src)) src++; if(!*src) break; args.add(dst); for(bool quoted = false; *src && (quoted || !isspace(*src)); src++) { if(*src != '"') *dst++ = *src; else if(dst > buf && src[-1] == '\\') dst[-1] = '"'; else quoted = !quoted; } *dst++ = '\0'; } args.add(NULL); return buf; } int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw) { vector args; char *buf = parsecommandline(GetCommandLine(), args); appinstance = hInst; #ifdef STANDALONE int standalonemain(int argc, char **argv); int status = standalonemain(args.length()-1, args.getbuf()); #define main standalonemain #else SDL_SetModuleHandle(hInst); int status = SDL_main(args.length()-1, args.getbuf()); #endif delete[] buf; exit(status); return 0; } void logoutfv(const char *fmt, va_list args) { if(appwindow) { logline &line = loglines.add(); vformatstring(line.buf, fmt, args, sizeof(line.buf)); if(logfile) writelog(logfile, line.buf); line.len = min(strlen(line.buf), sizeof(line.buf)-2); line.buf[line.len++] = '\n'; line.buf[line.len] = '\0'; if(outhandle) writeline(line); } else if(logfile) writelogv(logfile, fmt, args); } #else void logoutfv(const char *fmt, va_list args) { FILE *f = getlogfile(); if(f) writelogv(f, fmt, args); } #endif static bool dedicatedserver = false; bool isdedicatedserver() { return dedicatedserver; } void rundedicatedserver() { dedicatedserver = true; logoutf("dedicated server started, waiting for clients..."); #ifdef WIN32 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); for(;;) { MSG msg; while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if(msg.message == WM_QUIT) exit(EXIT_SUCCESS); TranslateMessage(&msg); DispatchMessage(&msg); } serverslice(true, 5); } #else for(;;) serverslice(true, 5); #endif dedicatedserver = false; } bool servererror(bool dedicated, const char *desc) { #ifndef STANDALONE if(!dedicated) { conoutf(CON_ERROR, "%s", desc); cleanupserver(); } else #endif fatal("%s", desc); return false; } bool setuplistenserver(bool dedicated) { ENetAddress address = { ENET_HOST_ANY, enet_uint16(serverport <= 0 ? server::serverport() : serverport) }; if(*serverip) { if(enet_address_set_host(&address, serverip)<0) conoutf(CON_WARN, "WARNING: server ip not resolved"); else serveraddress.host = address.host; } serverhost = enet_host_create(&address, min(maxclients + server::reserveclients(), MAXCLIENTS), server::numchannels(), 0, serveruprate); if(!serverhost) return servererror(dedicated, "could not create server host"); loopi(maxclients) serverhost->peers[i].data = NULL; address.port = server::serverinfoport(serverport > 0 ? serverport : -1); pongsock = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM); if(pongsock != ENET_SOCKET_NULL && enet_socket_bind(pongsock, &address) < 0) { enet_socket_destroy(pongsock); pongsock = ENET_SOCKET_NULL; } if(pongsock == ENET_SOCKET_NULL) return servererror(dedicated, "could not create server info socket"); else enet_socket_set_option(pongsock, ENET_SOCKOPT_NONBLOCK, 1); address.port = server::laninfoport(); lansock = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM); if(lansock != ENET_SOCKET_NULL && (enet_socket_set_option(lansock, ENET_SOCKOPT_REUSEADDR, 1) < 0 || enet_socket_bind(lansock, &address) < 0)) { enet_socket_destroy(lansock); lansock = ENET_SOCKET_NULL; } if(lansock == ENET_SOCKET_NULL) conoutf(CON_WARN, "WARNING: could not create LAN server info socket"); else enet_socket_set_option(lansock, ENET_SOCKOPT_NONBLOCK, 1); return true; } void initserver(bool listen, bool dedicated) { if(dedicated) { #ifdef WIN32 setupwindow("Cube 2: Sauerbraten server"); #endif } execfile("server-init.cfg", false); if(listen) setuplistenserver(dedicated); server::serverinit(); if(listen) { updatemasterserver(); if(dedicated) rundedicatedserver(); // never returns #ifndef STANDALONE else conoutf("listen server started"); #endif } } #ifndef STANDALONE void startlistenserver(int *usemaster) { if(serverhost) { conoutf(CON_ERROR, "listen server is already running"); return; } allowupdatemaster = *usemaster>0 ? 1 : 0; if(!setuplistenserver(false)) return; updatemasterserver(); conoutf("listen server started for %d clients%s", maxclients, allowupdatemaster ? " and listed with master server" : ""); } COMMAND(startlistenserver, "i"); void stoplistenserver() { if(!serverhost) { conoutf(CON_ERROR, "listen server is not running"); return; } kicknonlocalclients(); enet_host_flush(serverhost); cleanupserver(); conoutf("listen server stopped"); } COMMAND(stoplistenserver, ""); #endif bool serveroption(char *opt) { switch(opt[1]) { case 'u': setvar("serveruprate", atoi(opt+2)); return true; case 'c': setvar("maxclients", atoi(opt+2)); return true; case 'i': setsvar("serverip", opt+2); return true; case 'j': setvar("serverport", atoi(opt+2)); return true; case 'm': setsvar("mastername", opt+2); setvar("updatemaster", mastername[0] ? 1 : 0); return true; #ifdef STANDALONE case 'q': logoutf("Using home directory: %s", opt); sethomedir(opt+2); return true; case 'k': logoutf("Adding package directory: %s", opt); addpackagedir(opt+2); return true; case 'g': logoutf("Setting log file: %s", opt); setlogfile(opt+2); return true; #endif default: return false; } } vector gameargs; #ifdef STANDALONE int main(int argc, char **argv) { setlogfile(NULL); if(enet_initialize()<0) fatal("Unable to initialise network module"); atexit(enet_deinitialize); enet_time_set(0); for(int i = 1; i 0; } void dodebug(int w, int h) { if(numdepthfxranges > 0) { glColor3f(0, 1, 0); debugscissor(w, h, true); glColor3f(0, 0, 1); debugblurtiles(w, h, true); glColor3f(1, 1, 1); } } } depthfxtex; void cleanupdepthfx() { depthfxtex.cleanup(true); } void viewdepthfxtex() { if(!depthfx) return; depthfxtex.debug(); } bool depthfxing = false; bool binddepthfxtex() { if(renderpath!=R_FIXEDFUNCTION && !reflecting && !refracting && depthfx && depthfxtex.rendertex && numdepthfxranges>0) { glActiveTexture_(GL_TEXTURE2_ARB); glBindTexture(depthfxtex.target, depthfxtex.rendertex); glActiveTexture_(GL_TEXTURE0_ARB); if(depthfxtex.target==GL_TEXTURE_RECTANGLE_ARB) setenvparamf("depthfxview", SHPARAM_VERTEX, 6, 0.5f*depthfxtex.vieww, 0.5f*depthfxtex.viewh); else setenvparamf("depthfxview", SHPARAM_VERTEX, 6, 0.5f*float(depthfxtex.vieww)/depthfxtex.texw, 0.5f*float(depthfxtex.viewh)/depthfxtex.texh); return true; } return false; } void binddepthfxparams(float blend, float minblend = 0, bool allow = true, void *owner = NULL) { if(renderpath!=R_FIXEDFUNCTION && !reflecting && !refracting && depthfx && depthfxtex.rendertex && numdepthfxranges>0) { float scale = 0, offset = -1, texscale = 0; if(!depthfxtex.highprecision()) { float select[4] = { 0, 0, 0, 0 }; if(!depthfxtex.emulatehighprecision()) { loopi(numdepthfxranges) if(depthfxowners[i]==owner) { select[i] = float(depthfxscale)/blend; scale = 1.0f/blend; offset = -float(depthfxranges[i] - depthfxbias)/blend; break; } } else if(allow) { select[0] = float(depthfxfpscale)/blend; select[1] = select[0]/256; select[2] = select[1]/256; scale = 1.0f/blend; offset = 0; } setlocalparamfv("depthfxselect", SHPARAM_PIXEL, 6, select); } else if(allow) { scale = 1.0f/blend; offset = 0; texscale = float(depthfxfpscale)/blend; } setlocalparamf("depthfxparams", SHPARAM_VERTEX, 5, scale, offset, texscale, minblend); setlocalparamf("depthfxparams", SHPARAM_PIXEL, 5, scale, offset, texscale, minblend); } } void drawdepthfxtex() { if(!depthfx || renderpath==R_FIXEDFUNCTION) return; // Apple/ATI bug - fixed-function fog state can force software fallback even when fragment program is enabled glDisable(GL_FOG); depthfxtex.render(1<>16)&0xFF, (shadowmapambient>>8)&0xFF, shadowmapambient&0xFF); }); VARP(shadowmapintensity, 0, 40, 100); VARP(blurshadowmap, 0, 1, 3); VARP(blursmsigma, 1, 100, 200); #define SHADOWSKEW 0.7071068f vec shadowoffset(0, 0, 0), shadowfocus(0, 0, 0), shadowdir(0, SHADOWSKEW, 1); VAR(shadowmapcasters, 1, 0, 0); float shadowmapmaxz = 0; void setshadowdir(int angle) { shadowdir = vec(0, SHADOWSKEW, 1); shadowdir.rotate_around_z(angle*RAD); } VARFR(shadowmapangle, 0, 0, 360, setshadowdir(shadowmapangle)); void guessshadowdir() { if(shadowmapangle) return; vec dir; extern int sunlight; extern vec sunlightdir; if(sunlight) dir = sunlightdir; else { vec lightpos(0, 0, 0), casterpos(0, 0, 0); int numlights = 0, numcasters = 0; const vector &ents = entities::getents(); loopv(ents) { extentity &e = *ents[i]; switch(e.type) { case ET_LIGHT: if(!e.attr1) { lightpos.add(e.o); numlights++; } break; case ET_MAPMODEL: casterpos.add(e.o); numcasters++; break; default: if(e.typew-vieww, screen->h-viewh, vieww, viewh); } glClearColor(0, 0, 0, 0); glClear(GL_DEPTH_BUFFER_BIT | (renderpath!=R_FIXEDFUNCTION ? GL_COLOR_BUFFER_BIT : 0)); if(!hasFBO && rtscissor) glDisable(GL_SCISSOR_TEST); } bool dorender() { // nvidia bug, must push modelview here, then switch to projection, then back to modelview before can safely modify it glPushMatrix(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(-shadowmapradius, shadowmapradius, -shadowmapradius, shadowmapradius, renderpath==R_FIXEDFUNCTION ? 0 : -shadowmapdist, renderpath==R_FIXEDFUNCTION ? ffshadowmapdist : shadowmapdist); glMatrixMode(GL_MODELVIEW); vec skewdir(shadowdir); skewdir.rotate_around_z(-camera1->yaw*RAD); vec dir; vecfromyawpitch(camera1->yaw, camera1->pitch, 1, 0, dir); dir.z = 0; dir.mul(shadowmapradius); vec dirx, diry; vecfromyawpitch(camera1->yaw, 0, 0, 1, dirx); vecfromyawpitch(camera1->yaw, 0, 1, 0, diry); shadowoffset.x = -fmod(dirx.dot(camera1->o) - skewdir.x*camera1->o.z, 2.0f*shadowmapradius/vieww); shadowoffset.y = -fmod(diry.dot(camera1->o) - skewdir.y*camera1->o.z, 2.0f*shadowmapradius/viewh); GLfloat skew[] = { 1, 0, 0, 0, 0, 1, 0, 0, skewdir.x, skewdir.y, 1, 0, 0, 0, 0, 1 }; glLoadMatrixf(skew); glTranslatef(skewdir.x*shadowmapheight + shadowoffset.x, skewdir.y*shadowmapheight + shadowoffset.y + dir.magnitude(), -shadowmapheight); glRotatef(camera1->yaw+180, 0, 0, -1); glTranslatef(-camera1->o.x, -camera1->o.y, -camera1->o.z); shadowfocus = camera1->o; shadowfocus.add(dir); shadowfocus.add(vec(shadowdir).mul(shadowmapheight)); shadowfocus.add(dirx.mul(shadowoffset.x)); shadowfocus.add(diry.mul(shadowoffset.y)); glmatrixf proj, mv; glGetFloatv(GL_PROJECTION_MATRIX, proj.v); glGetFloatv(GL_MODELVIEW_MATRIX, mv.v); shadowmapmatrix.mul(proj, mv); if(renderpath==R_FIXEDFUNCTION) shadowmapmatrix.projective(); else shadowmapmatrix.projective(-1, 1-shadowmapbias/float(shadowmapdist)); glColor3f(0, 0, 0); glDisable(GL_TEXTURE_2D); if(renderpath!=R_FIXEDFUNCTION) setenvparamf("shadowmapbias", SHPARAM_VERTEX, 0, -shadowmapbias/float(shadowmapdist), 1 - (shadowmapbias + (smoothshadowmappeel ? 0 : shadowmappeelbias))/float(shadowmapdist)); else glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); shadowmapcasters = 0; shadowmapmaxz = shadowfocus.z - shadowmapdist; shadowmapping = true; rendergame(); shadowmapping = false; shadowmapmaxz = min(shadowmapmaxz, shadowfocus.z); glEnable(GL_TEXTURE_2D); if(renderpath==R_FIXEDFUNCTION) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); else if(shadowmapcasters && smdepthpeel) { int sx, sy, sw, sh; bool scissoring = rtscissor && scissorblur(sx, sy, sw, sh) && sw > 0 && sh > 0; if(scissoring) { if(!hasFBO) { sx += screen->w-vieww; sy += screen->h-viewh; } glScissor(sx, sy, sw, sh); } if(!rtscissor || scissoring) rendershadowmapreceivers(); } glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); return shadowmapcasters>0; } bool flipdebug() const { return false; } void dodebug(int w, int h) { if(shadowmapcasters) { glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE); debugscissor(w, h); glColorMask(GL_FALSE, GL_FALSE, GL_TRUE, GL_FALSE); debugblurtiles(w, h); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); } } } shadowmaptex; void cleanshadowmap() { shadowmaptex.cleanup(true); } VAR(ffsmscissor, 0, 1, 1); static void calcscissorbox() { int smx, smy, smw, smh; shadowmaptex.scissorblur(smx, smy, smw, smh); vec forward, right; vecfromyawpitch(camera1->yaw, 0, -1, 0, forward); vecfromyawpitch(camera1->yaw, 0, 0, -1, right); forward.mul(shadowmapradius*2.0f/shadowmaptex.viewh); right.mul(shadowmapradius*2.0f/shadowmaptex.vieww); vec bottom(shadowfocus); bottom.sub(vec(shadowdir).mul(shadowmapdist)); bottom.add(vec(forward).mul(smy - shadowmaptex.viewh/2)).add(vec(right).mul(smx - shadowmaptex.vieww/2)); vec top(bottom); top.add(vec(shadowdir).mul(shadowmapmaxz - (shadowfocus.z - shadowmapdist))); vec4 v[8]; float sx1 = 1, sy1 = 1, sx2 = -1, sy2 = -1; loopi(8) { vec c = i&4 ? top : bottom; if(i&1) c.add(vec(right).mul(smw)); if(i&2) c.add(vec(forward).mul(smh)); if(reflecting) c.z = 2*reflectz - c.z; vec4 &p = v[i]; mvpmatrix.transform(c, p); if(p.z >= -p.w) { float x = p.x / p.w, y = p.y / p.w; sx1 = min(sx1, x); sy1 = min(sy1, y); sx2 = max(sx2, x); sy2 = max(sy2, y); } } if(sx1 >= sx2 || sy1 >= sy2) return; loopi(8) { const vec4 &p = v[i]; if(p.z >= -p.w) continue; loopj(3) { const vec4 &o = v[i^(1<yaw*RAD); vec ro(o); ro.sub(camera1->o); ro.rotate_around_z(-(camera1->yaw+180)*RAD); ro.x += ro.z * skewdir.x + shadowoffset.x; ro.y += ro.z * skewdir.y + shadowmapradius * cosf(camera1->pitch*RAD) + shadowoffset.y; vec high(ro), low(ro); high.x += zrad * skewdir.x; high.y += zrad * skewdir.y; low.x -= zrad * skewdir.x; low.y -= zrad * skewdir.y; x1 = (min(high.x, low.x) - xyrad) / shadowmapradius; y1 = (min(high.y, low.y) - xyrad) / shadowmapradius; x2 = (max(high.x, low.x) + xyrad) / shadowmapradius; y2 = (max(high.y, low.y) + xyrad) / shadowmapradius; } bool addshadowmapcaster(const vec &o, float xyrad, float zrad) { if(o.z + zrad <= shadowfocus.z - shadowmapdist || o.z - zrad >= shadowfocus.z) return false; shadowmapmaxz = max(shadowmapmaxz, o.z + zrad); float x1, y1, x2, y2; calcshadowmapbb(o, xyrad, zrad, x1, y1, x2, y2); if(!shadowmaptex.addblurtiles(x1, y1, x2, y2, 2)) return false; shadowmapcasters++; return true; } bool isshadowmapreceiver(vtxarray *va) { if(!shadowmap || !shadowmapcasters) return false; if(va->shadowmapmax.z <= shadowfocus.z - shadowmapdist || va->shadowmapmin.z >= shadowmapmaxz) return false; float xyrad = SQRT2*0.5f*max(va->shadowmapmax.x-va->shadowmapmin.x, va->shadowmapmax.y-va->shadowmapmin.y), zrad = 0.5f*(va->shadowmapmax.z-va->shadowmapmin.z), x1, y1, x2, y2; if(xyrad<0 || zrad<0) return false; vec center(va->shadowmapmin.tovec()); center.add(va->shadowmapmax.tovec()).mul(0.5f); calcshadowmapbb(center, xyrad, zrad, x1, y1, x2, y2); return shadowmaptex.checkblurtiles(x1, y1, x2, y2, 2); #if 0 // cheaper inexact test float dz = va->o.z + va->size/2 - shadowfocus.z; float cx = shadowfocus.x + dz*shadowdir.x, cy = shadowfocus.y + dz*shadowdir.y; float skew = va->size/2*SHADOWSKEW; if(!shadowmap || !shadowmaptex || va->o.z + va->size <= shadowfocus.z - shadowmapdist || va->o.z >= shadowmapmaxz || va->o.x + va->size <= cx - shadowmapradius-skew || va->o.x >= cx + shadowmapradius+skew || va->o.y + va->size <= cy - shadowmapradius-skew || va->o.y >= cy + shadowmapradius+skew) return false; return true; #endif } bool isshadowmapcaster(const vec &o, float rad) { // cheaper inexact test float dz = o.z - shadowfocus.z; float cx = shadowfocus.x + dz*shadowdir.x, cy = shadowfocus.y + dz*shadowdir.y; float skew = rad*SHADOWSKEW; if(!shadowmapping || o.z + rad <= shadowfocus.z - shadowmapdist || o.z - rad >= shadowfocus.z || o.x + rad <= cx - shadowmapradius-skew || o.x - rad >= cx + shadowmapradius+skew || o.y + rad <= cy - shadowmapradius-skew || o.y - rad >= cy + shadowmapradius+skew) return false; return true; } void pushshadowmap() { if(!shadowmap || !shadowmaptex.rendertex) return; if(renderpath==R_FIXEDFUNCTION) { glBindTexture(GL_TEXTURE_2D, shadowmaptex.rendertex); const GLfloat *v = shadowmapmatrix.v; GLfloat texgenS[4] = { v[0], v[4], v[8], v[12] }, texgenT[4] = { v[1], v[5], v[9], v[13] }, texgenR[4] = { v[2], v[6], v[10], v[14] }; glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_S, GL_OBJECT_PLANE, texgenS); glEnable(GL_TEXTURE_GEN_S); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_T, GL_OBJECT_PLANE, texgenT); glEnable(GL_TEXTURE_GEN_T); glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_R, GL_OBJECT_PLANE, texgenR); glEnable(GL_TEXTURE_GEN_R); // intel driver bug workaround: when R texgen is enabled, it uses the value of Q, even if not enabled! // MUST set Q with glTexCoord4f, glTexCoord3f does not work glTexCoord4f(0, 0, 0, 1); glColor3f(shadowmapintensity/100.0f, shadowmapintensity/100.0f, shadowmapintensity/100.0f); if(ffsmscissor) calcscissorbox(); return; } glActiveTexture_(GL_TEXTURE7_ARB); glBindTexture(GL_TEXTURE_2D, shadowmaptex.rendertex); glActiveTexture_(GL_TEXTURE2_ARB); glMatrixMode(GL_TEXTURE); glLoadMatrixf(shadowmapmatrix.v); glMatrixMode(GL_MODELVIEW); glActiveTexture_(GL_TEXTURE0_ARB); glClientActiveTexture_(GL_TEXTURE0_ARB); float r, g, b; if(!shadowmapambient) { if(skylightcolor[0] || skylightcolor[1] || skylightcolor[2]) { r = max(25.0f, 0.4f*ambientcolor[0] + 0.6f*max(ambientcolor[0], skylightcolor[0])); g = max(25.0f, 0.4f*ambientcolor[1] + 0.6f*max(ambientcolor[1], skylightcolor[1])); b = max(25.0f, 0.4f*ambientcolor[2] + 0.6f*max(ambientcolor[2], skylightcolor[2])); } else { r = max(25.0f, 2.0f*ambientcolor[0]); g = max(25.0f, 2.0f*ambientcolor[1]); b = max(25.0f, 2.0f*ambientcolor[2]); } } else { r = shadowmapambientcolor[0]; g = shadowmapambientcolor[1]; b = shadowmapambientcolor[2]; } setenvparamf("shadowmapambient", SHPARAM_PIXEL, 7, r/255.0f, g/255.0f, b/255.0f); } void popshadowmap() { if(!shadowmap || !shadowmaptex.rendertex) return; if(renderpath==R_FIXEDFUNCTION) { popscissor(); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_R); } } void rendershadowmap() { if(!shadowmap || (renderpath==R_FIXEDFUNCTION && (!hasSGIDT || !hasSGISH))) return; // Apple/ATI bug - fixed-function fog state can force software fallback even when fragment program is enabled glDisable(GL_FOG); shadowmaptex.render(1< 0, *local != 0) ? 1 : 0)); const ENetAddress *connectedpeer() { return curpeer ? &curpeer->address : NULL; } ICOMMAND(connectedip, "", (), { const ENetAddress *address = connectedpeer(); string hostname; result(address && enet_address_get_host_ip(address, hostname, sizeof(hostname)) >= 0 ? hostname : ""); }); ICOMMAND(connectedport, "", (), { const ENetAddress *address = connectedpeer(); intret(address ? address->port : -1); }); void abortconnect() { if(!connpeer) return; game::connectfail(); if(connpeer->state!=ENET_PEER_STATE_DISCONNECTED) enet_peer_reset(connpeer); connpeer = NULL; if(curpeer) return; enet_host_destroy(clienthost); clienthost = NULL; } SVARP(connectname, ""); VARP(connectport, 0, 0, 0xFFFF); void connectserv(const char *servername, int serverport, const char *serverpassword) { if(connpeer) { conoutf("aborting connection attempt"); abortconnect(); } if(serverport <= 0) serverport = server::serverport(); ENetAddress address; address.port = serverport; if(servername) { if(strcmp(servername, connectname)) setsvar("connectname", servername); if(serverport != connectport) setvar("connectport", serverport); addserver(servername, serverport, serverpassword && serverpassword[0] ? serverpassword : NULL); conoutf("attempting to connect to %s:%d", servername, serverport); if(!resolverwait(servername, &address)) { conoutf("\f3could not resolve server %s", servername); return; } } else { setsvar("connectname", ""); setvar("connectport", 0); conoutf("attempting to connect over LAN"); address.host = ENET_HOST_BROADCAST; } if(!clienthost) clienthost = enet_host_create(NULL, 2, server::numchannels(), rate*1024, rate*1024); if(clienthost) { connpeer = enet_host_connect(clienthost, &address, server::numchannels(), 0); enet_host_flush(clienthost); connmillis = totalmillis; connattempts = 0; game::connectattempt(servername ? servername : "", serverpassword ? serverpassword : "", address); } else conoutf("\f3could not connect to server"); } void reconnect(const char *serverpassword) { if(!connectname[0] || connectport <= 0) { conoutf(CON_ERROR, "no previous connection"); return; } connectserv(connectname, connectport, serverpassword); } void disconnect(bool async, bool cleanup) { if(curpeer) { if(!discmillis) { enet_peer_disconnect(curpeer, DISC_NONE); enet_host_flush(clienthost); discmillis = totalmillis; } if(curpeer->state!=ENET_PEER_STATE_DISCONNECTED) { if(async) return; enet_peer_reset(curpeer); } curpeer = NULL; discmillis = 0; conoutf("disconnected"); game::gamedisconnect(cleanup); mainmenu = 1; } if(!connpeer && clienthost) { enet_host_destroy(clienthost); clienthost = NULL; } } void trydisconnect(bool local) { if(connpeer) { conoutf("aborting connection attempt"); abortconnect(); } else if(curpeer) { conoutf("attempting to disconnect..."); disconnect(!discmillis); } else if(local && haslocalclients()) localdisconnect(); else conoutf("not connected"); } ICOMMAND(connect, "sis", (char *name, int *port, char *pw), connectserv(name, *port, pw)); ICOMMAND(lanconnect, "is", (int *port, char *pw), connectserv(NULL, *port, pw)); COMMAND(reconnect, "s"); ICOMMAND(disconnect, "b", (int *local), trydisconnect(*local != 0)); ICOMMAND(localconnect, "", (), { if(!isconnected()) localconnect(); }); ICOMMAND(localdisconnect, "", (), { if(haslocalclients()) localdisconnect(); }); void sendclientpacket(ENetPacket *packet, int chan) { if(curpeer) enet_peer_send(curpeer, chan, packet); else localclienttoserver(chan, packet); } void flushclient() { if(clienthost) enet_host_flush(clienthost); } void neterr(const char *s, bool disc) { conoutf(CON_ERROR, "\f3illegal network message (%s)", s); if(disc) disconnect(); } void localservertoclient(int chan, ENetPacket *packet) // processes any updates from the server { packetbuf p(packet); game::parsepacketclient(chan, p); } void clientkeepalive() { if(clienthost) enet_host_service(clienthost, NULL, 0); } void gets2c() // get updates from the server { ENetEvent event; if(!clienthost) return; if(connpeer && totalmillis/3000 > connmillis/3000) { conoutf("attempting to connect..."); connmillis = totalmillis; ++connattempts; if(connattempts > 3) { conoutf("\f3could not connect to server"); abortconnect(); return; } } while(clienthost && enet_host_service(clienthost, &event, 0)>0) switch(event.type) { case ENET_EVENT_TYPE_CONNECT: disconnect(false, false); localdisconnect(false); curpeer = connpeer; connpeer = NULL; conoutf("connected to server"); throttle(); if(rate) setrate(rate); game::gameconnect(true); break; case ENET_EVENT_TYPE_RECEIVE: if(discmillis) conoutf("attempting to disconnect..."); else localservertoclient(event.channelID, event.packet); enet_packet_destroy(event.packet); break; case ENET_EVENT_TYPE_DISCONNECT: if(event.data>=DISC_NUM) event.data = DISC_NONE; if(event.peer==connpeer) { conoutf("\f3could not connect to server"); abortconnect(); } else { if(!discmillis || event.data) { const char *msg = disconnectreason(event.data); if(msg) conoutf("\f3server network error, disconnecting (%s) ...", msg); else conoutf("\f3server network error, disconnecting..."); } disconnect(); } return; default: break; } } sauerbraten-0.0.20130203.dfsg/engine/pch.cpp0000644000175000017500000000002511164573771020131 0ustar vincentvincent#include "engine.h" sauerbraten-0.0.20130203.dfsg/engine/texture.h0000644000175000017500000006060012050706254020516 0ustar vincentvincent// GL_ARB_vertex_program, GL_ARB_fragment_program extern PFNGLGENPROGRAMSARBPROC glGenProgramsARB_; extern PFNGLDELETEPROGRAMSARBPROC glDeleteProgramsARB_; extern PFNGLBINDPROGRAMARBPROC glBindProgramARB_; extern PFNGLPROGRAMSTRINGARBPROC glProgramStringARB_; extern PFNGLGETPROGRAMIVARBPROC glGetProgramivARB_; extern PFNGLPROGRAMENVPARAMETER4FARBPROC glProgramEnvParameter4fARB_; extern PFNGLPROGRAMENVPARAMETER4FVARBPROC glProgramEnvParameter4fvARB_; // GL_EXT_gpu_program_parameters #ifndef GL_EXT_gpu_program_parameters #define GL_EXT_gpu_program_parameters 1 typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params); typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params); #endif extern PFNGLPROGRAMENVPARAMETERS4FVEXTPROC glProgramEnvParameters4fv_; extern PFNGLPROGRAMLOCALPARAMETERS4FVEXTPROC glProgramLocalParameters4fv_; #ifndef GL_VERSION_2_1 #define GL_VERSION_2_1 1 #define GL_FLOAT_MAT2x3 0x8B65 #define GL_FLOAT_MAT2x4 0x8B66 #define GL_FLOAT_MAT3x2 0x8B67 #define GL_FLOAT_MAT3x4 0x8B68 #define GL_FLOAT_MAT4x2 0x8B69 #define GL_FLOAT_MAT4x3 0x8B6A typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); #endif // OpenGL 2.0: GL_ARB_shading_language_100, GL_ARB_shader_objects, GL_ARB_fragment_shader, GL_ARB_vertex_shader #ifdef __APPLE__ #define glCreateProgram_ glCreateProgram #define glDeleteProgram_ glDeleteProgram #define glUseProgram_ glUseProgram #define glCreateShader_ glCreateShader #define glDeleteShader_ glDeleteShader #define glShaderSource_ glShaderSource #define glCompileShader_ glCompileShader #define glGetShaderiv_ glGetShaderiv #define glGetProgramiv_ glGetProgramiv #define glAttachShader_ glAttachShader #define glGetProgramInfoLog_ glGetProgramInfoLog #define glGetShaderInfoLog_ glGetShaderInfoLog #define glLinkProgram_ glLinkProgram #define glGetUniformLocation_ glGetUniformLocation #define glUniform1f_ glUniform1f #define glUniform2f_ glUniform2f #define glUniform3f_ glUniform3f #define glUniform4f_ glUniform4f #define glUniform1fv_ glUniform1fv #define glUniform2fv_ glUniform2fv #define glUniform3fv_ glUniform3fv #define glUniform4fv_ glUniform4fv #define glUniform1i_ glUniform1i #define glUniformMatrix2fv_ glUniformMatrix2fv #define glUniformMatrix3fv_ glUniformMatrix3fv #define glUniformMatrix4fv_ glUniformMatrix4fv #define glBindAttribLocation_ glBindAttribLocation #define glGetActiveUniform_ glGetActiveUniform #define glEnableVertexAttribArray_ glEnableVertexAttribArray #define glDisableVertexAttribArray_ glDisableVertexAttribArray #define glVertexAttribPointer_ glVertexAttribPointer #define glUniformMatrix2x3fv_ glUniformMatrix2x3fv #define glUniformMatrix3x2fv_ glUniformMatrix3x2fv #define glUniformMatrix2x4fv_ glUniformMatrix2x4fv #define glUniformMatrix4x2fv_ glUniformMatrix4x2fv #define glUniformMatrix3x4fv_ glUniformMatrix3x4fv #define glUniformMatrix4x3fv_ glUniformMatrix4x3fv #else extern PFNGLCREATEPROGRAMPROC glCreateProgram_; extern PFNGLDELETEPROGRAMPROC glDeleteProgram_; extern PFNGLUSEPROGRAMPROC glUseProgram_; extern PFNGLCREATESHADERPROC glCreateShader_; extern PFNGLDELETESHADERPROC glDeleteShader_; extern PFNGLSHADERSOURCEPROC glShaderSource_; extern PFNGLCOMPILESHADERPROC glCompileShader_; extern PFNGLGETSHADERIVPROC glGetShaderiv_; extern PFNGLGETPROGRAMIVPROC glGetProgramiv_; extern PFNGLATTACHSHADERPROC glAttachShader_; extern PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog_; extern PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog_; extern PFNGLLINKPROGRAMPROC glLinkProgram_; extern PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation_; extern PFNGLUNIFORM1FPROC glUniform1f_; extern PFNGLUNIFORM2FPROC glUniform2f_; extern PFNGLUNIFORM3FPROC glUniform3f_; extern PFNGLUNIFORM4FPROC glUniform4f_; extern PFNGLUNIFORM1FVPROC glUniform1fv_; extern PFNGLUNIFORM2FVPROC glUniform2fv_; extern PFNGLUNIFORM3FVPROC glUniform3fv_; extern PFNGLUNIFORM4FVPROC glUniform4fv_; extern PFNGLUNIFORM1IPROC glUniform1i_; extern PFNGLBINDATTRIBLOCATIONPROC glBindAttribLocation_; extern PFNGLGETACTIVEUNIFORMPROC glGetActiveUniform_; extern PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray_; extern PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray_; extern PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer_; extern PFNGLUNIFORMMATRIX2X3FVPROC glUniformMatrix2x3fv_; extern PFNGLUNIFORMMATRIX3X2FVPROC glUniformMatrix3x2fv_; extern PFNGLUNIFORMMATRIX2X4FVPROC glUniformMatrix2x4fv_; extern PFNGLUNIFORMMATRIX4X2FVPROC glUniformMatrix4x2fv_; extern PFNGLUNIFORMMATRIX3X4FVPROC glUniformMatrix3x4fv_; extern PFNGLUNIFORMMATRIX4X3FVPROC glUniformMatrix4x3fv_; #endif #ifndef GL_ARB_uniform_buffer_object #define GL_ARB_uniform_buffer_object 1 #define GL_UNIFORM_BUFFER 0x8A11 #define GL_UNIFORM_BUFFER_BINDING 0x8A28 #define GL_UNIFORM_BUFFER_START 0x8A29 #define GL_UNIFORM_BUFFER_SIZE 0x8A2A #define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B #define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C #define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D #define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E #define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F #define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 #define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 #define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 #define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 #define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 #define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 #define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 #define GL_UNIFORM_TYPE 0x8A37 #define GL_UNIFORM_SIZE 0x8A38 #define GL_UNIFORM_NAME_LENGTH 0x8A39 #define GL_UNIFORM_BLOCK_INDEX 0x8A3A #define GL_UNIFORM_OFFSET 0x8A3B #define GL_UNIFORM_ARRAY_STRIDE 0x8A3C #define GL_UNIFORM_MATRIX_STRIDE 0x8A3D #define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E #define GL_UNIFORM_BLOCK_BINDING 0x8A3F #define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 #define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 #define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 #define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 #define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 #define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 #define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 #define GL_INVALID_INDEX 0xFFFFFFFFu typedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC) (GLuint program, GLsizei uniformCount, const GLchar* *uniformNames, GLuint *uniformIndices); typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC) (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); typedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC) (GLuint program, const GLchar *uniformBlockName); typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC) (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC) (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); #endif #ifndef GL_INVALID_INDEX #define GL_INVALID_INDEX 0xFFFFFFFFu #endif #ifndef GL_VERSION_3_0 #define GL_VERSION_3_0 1 typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer); #elif GL_GLEXT_VERSION < 43 typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer); #endif // GL_ARB_uniform_buffer_object extern PFNGLGETUNIFORMINDICESPROC glGetUniformIndices_; extern PFNGLGETACTIVEUNIFORMSIVPROC glGetActiveUniformsiv_; extern PFNGLGETUNIFORMBLOCKINDEXPROC glGetUniformBlockIndex_; extern PFNGLGETACTIVEUNIFORMBLOCKIVPROC glGetActiveUniformBlockiv_; extern PFNGLUNIFORMBLOCKBINDINGPROC glUniformBlockBinding_; extern PFNGLBINDBUFFERBASEPROC glBindBufferBase_; extern PFNGLBINDBUFFERRANGEPROC glBindBufferRange_; #ifndef GL_EXT_bindable_uniform #define GL_EXT_bindable_uniform 1 #define GL_MAX_VERTEX_BINDABLE_UNIFORMS_EXT 0x8DE2 #define GL_MAX_FRAGMENT_BINDABLE_UNIFORMS_EXT 0x8DE3 #define GL_MAX_GEOMETRY_BINDABLE_UNIFORMS_EXT 0x8DE4 #define GL_MAX_BINDABLE_UNIFORM_SIZE_EXT 0x8DED #define GL_UNIFORM_BUFFER_EXT 0x8DEE #define GL_UNIFORM_BUFFER_BINDING_EXT 0x8DEF typedef void (APIENTRYP PFNGLUNIFORMBUFFEREXTPROC) (GLuint program, GLint location, GLuint buffer); typedef GLint (APIENTRYP PFNGLGETUNIFORMBUFFERSIZEEXTPROC) (GLuint program, GLint location); typedef GLintptr (APIENTRYP PFNGLGETUNIFORMOFFSETEXTPROC) (GLuint program, GLint location); #endif // GL_EXT_bindable_uniform extern PFNGLUNIFORMBUFFEREXTPROC glUniformBuffer_; extern PFNGLGETUNIFORMBUFFERSIZEEXTPROC glGetUniformBufferSize_; extern PFNGLGETUNIFORMOFFSETEXTPROC glGetUniformOffset_; extern int renderpath; enum { R_FIXEDFUNCTION = 0, R_ASMSHADER, R_GLSLANG, R_ASMGLSLANG }; enum { SHPARAM_LOOKUP = 0, SHPARAM_VERTEX, SHPARAM_PIXEL, SHPARAM_UNIFORM }; #define RESERVEDSHADERPARAMS 16 #define MAXSHADERPARAMS 8 struct ShaderParam { const char *name; int type, index, loc; float val[4]; }; struct LocalShaderParamState : ShaderParam { float curval[4]; GLenum format; LocalShaderParamState() : format(GL_FLOAT_VEC4_ARB) { memset(curval, -1, sizeof(curval)); } LocalShaderParamState(const ShaderParam &p) : ShaderParam(p), format(GL_FLOAT_VEC4_ARB) { memset(curval, -1, sizeof(curval)); } }; struct ShaderParamState { enum { CLEAN = 0, INVALID, DIRTY }; const char *name; float val[4]; bool local; int dirty; ShaderParamState() : name(NULL), local(false), dirty(INVALID) { memset(val, -1, sizeof(val)); } }; enum { SHADER_DEFAULT = 0, SHADER_NORMALSLMS = 1<<0, SHADER_ENVMAP = 1<<1, SHADER_GLSLANG = 1<<2, SHADER_OPTION = 1<<3, SHADER_INVALID = 1<<8, SHADER_DEFERRED = 1<<9 }; #define MAXSHADERDETAIL 3 #define MAXVARIANTROWS 5 extern int shaderdetail; struct Slot; struct VSlot; struct UniformLoc { const char *name, *blockname; int loc, version, binding, stride, offset, size; void *data; UniformLoc(const char *name = NULL, const char *blockname = NULL, int binding = -1, int stride = -1) : name(name), blockname(blockname), loc(-1), version(-1), binding(binding), stride(stride), offset(-1), size(-1), data(NULL) {} }; struct AttribLoc { const char *name; int loc; AttribLoc(const char *name = NULL, int loc = -1) : name(name), loc(loc) {} }; struct Shader { static Shader *lastshader; char *name, *vsstr, *psstr, *defer; int type; GLuint vs, ps; GLuint program, vsobj, psobj; vector defaultparams; Shader *detailshader, *variantshader, *altshader, *fastshader[MAXSHADERDETAIL]; vector variants[MAXVARIANTROWS]; bool standard, forced, used, native; Shader *reusevs, *reuseps; int numextparams; LocalShaderParamState *extparams; uchar *extvertparams, *extpixparams; vector uniformlocs; vector attriblocs; Shader() : name(NULL), vsstr(NULL), psstr(NULL), defer(NULL), type(SHADER_DEFAULT), vs(0), ps(0), program(0), vsobj(0), psobj(0), detailshader(NULL), variantshader(NULL), altshader(NULL), standard(false), forced(false), used(false), native(true), reusevs(NULL), reuseps(NULL), numextparams(0), extparams(NULL), extvertparams(NULL), extpixparams(NULL) { loopi(MAXSHADERDETAIL) fastshader[i] = this; } ~Shader() { DELETEA(name); DELETEA(vsstr); DELETEA(psstr); DELETEA(defer); DELETEA(extparams); DELETEA(extvertparams); extpixparams = NULL; } void fixdetailshader(bool force = true, bool recurse = true); void allocenvparams(Slot *slot = NULL); void flushenvparams(Slot *slot = NULL); void setslotparams(Slot &slot, VSlot &vslot); void bindprograms(); bool hasoption(int row) { if(!detailshader || detailshader->variants[row].empty()) return false; return (detailshader->variants[row][0]->type&SHADER_OPTION)!=0; } void setvariant_(int col, int row, Shader *fallbackshader) { Shader *s = fallbackshader; for(col = min(col, detailshader->variants[row].length()-1); col >= 0; col--) if(!(detailshader->variants[row][col]->type&SHADER_INVALID)) { s = detailshader->variants[row][col]; break; } if(lastshader!=s) s->bindprograms(); } void setvariant(int col, int row, Shader *fallbackshader) { if(!this || !detailshader || renderpath==R_FIXEDFUNCTION) return; setvariant_(col, row, fallbackshader); lastshader->flushenvparams(); } void setvariant(int col, int row) { if(!this || !detailshader || renderpath==R_FIXEDFUNCTION) return; setvariant_(col, row, detailshader); lastshader->flushenvparams(); } void setvariant(int col, int row, Slot &slot, VSlot &vslot, Shader *fallbackshader) { if(!this || !detailshader || renderpath==R_FIXEDFUNCTION) return; setvariant_(col, row, fallbackshader); lastshader->flushenvparams(&slot); lastshader->setslotparams(slot, vslot); } void setvariant(int col, int row, Slot &slot, VSlot &vslot) { if(!this || !detailshader || renderpath==R_FIXEDFUNCTION) return; setvariant_(col, row, detailshader); lastshader->flushenvparams(&slot); lastshader->setslotparams(slot, vslot); } void set_() { if(lastshader!=detailshader) detailshader->bindprograms(); } void set() { if(!this || !detailshader || renderpath==R_FIXEDFUNCTION) return; set_(); lastshader->flushenvparams(); } void set(Slot &slot, VSlot &vslot) { if(!this || !detailshader || renderpath==R_FIXEDFUNCTION) return; set_(); lastshader->flushenvparams(&slot); lastshader->setslotparams(slot, vslot); } bool compile(); void cleanup(bool invalid = false); static int uniformlocversion(); }; #define SETSHADER(name) \ do { \ static Shader *name##shader = NULL; \ if(!name##shader) name##shader = lookupshaderbyname(#name); \ name##shader->set(); \ } while(0) struct ImageData { int w, h, bpp, levels, align, pitch; GLenum compressed; uchar *data; void *owner; void (*freefunc)(void *); ImageData() : data(NULL), owner(NULL), freefunc(NULL) {} ImageData(int nw, int nh, int nbpp, int nlevels = 1, int nalign = 0, GLenum ncompressed = GL_FALSE) { setdata(NULL, nw, nh, nbpp, nlevels, nalign, ncompressed); } ImageData(int nw, int nh, int nbpp, uchar *data) : owner(NULL), freefunc(NULL) { setdata(data, nw, nh, nbpp); } ImageData(SDL_Surface *s) { wrap(s); } ~ImageData() { cleanup(); } void setdata(uchar *ndata, int nw, int nh, int nbpp, int nlevels = 1, int nalign = 0, GLenum ncompressed = GL_FALSE) { w = nw; h = nh; bpp = nbpp; levels = nlevels; align = nalign; pitch = align ? 0 : w*bpp; compressed = ncompressed; data = ndata ? ndata : new uchar[calcsize()]; if(!ndata) { owner = this; freefunc = NULL; } } int calclevelsize(int level) const { return ((max(w>>level, 1)+align-1)/align)*((max(h>>level, 1)+align-1)/align)*bpp; } int calcsize() const { if(!align) return w*h*bpp; int lw = w, lh = h, size = 0; loopi(levels) { if(lw<=0) lw = 1; if(lh<=0) lh = 1; size += ((lw+align-1)/align)*((lh+align-1)/align)*bpp; if(lw*lh==1) break; lw >>= 1; lh >>= 1; } return size; } void disown() { data = NULL; owner = NULL; freefunc = NULL; } void cleanup() { if(owner==this) delete[] data; else if(freefunc) (*freefunc)(owner); disown(); } void replace(ImageData &d) { cleanup(); *this = d; if(owner == &d) owner = this; d.disown(); } void wrap(SDL_Surface *s) { setdata((uchar *)s->pixels, s->w, s->h, s->format->BytesPerPixel); pitch = s->pitch; owner = s; freefunc = (void (*)(void *))SDL_FreeSurface; } }; // management of texture slots // each texture slot can have multiple texture frames, of which currently only the first is used // additional frames can be used for various shaders struct Texture { enum { IMAGE = 0, CUBEMAP = 1, TYPE = 0xFF, STUB = 1<<8, TRANSIENT = 1<<9, COMPRESSED = 1<<10, ALPHA = 1<<11, FLAGS = 0xFF00 }; char *name; int type, w, h, xs, ys, bpp, clamp; bool mipmap, canreduce; GLuint id; uchar *alphamask; Texture() : alphamask(NULL) {} }; enum { TEX_DIFFUSE = 0, TEX_UNKNOWN, TEX_DECAL, TEX_NORMAL, TEX_GLOW, TEX_SPEC, TEX_DEPTH, TEX_ENVMAP }; enum { VSLOT_SHPARAM = 0, VSLOT_SCALE, VSLOT_ROTATION, VSLOT_OFFSET, VSLOT_SCROLL, VSLOT_LAYER, VSLOT_ALPHA, VSLOT_COLOR, VSLOT_NUM }; struct VSlot { Slot *slot; VSlot *next; int index, changed; vector params; bool linked; float scale; int rotation, xoffset, yoffset; float scrollS, scrollT; int layer; float alphafront, alphaback; vec colorscale; vec glowcolor, pulseglowcolor; float pulseglowspeed; vec envscale; int skipped; VSlot(Slot *slot = NULL, int index = -1) : slot(slot), next(NULL), index(index), changed(0), skipped(0) { reset(); if(slot) addvariant(slot); } void addvariant(Slot *slot); void reset() { params.shrink(0); linked = false; scale = 1; rotation = xoffset = yoffset = 0; scrollS = scrollT = 0; layer = 0; alphafront = 0.5f; alphaback = 0; colorscale = vec(1, 1, 1); glowcolor = vec(1, 1, 1); pulseglowcolor = vec(0, 0, 0); pulseglowspeed = 0; envscale = vec(0, 0, 0); } void cleanup() { linked = false; } }; struct Slot { struct Tex { int type; Texture *t; string name; int combined; }; int index; vector sts; Shader *shader; vector params; VSlot *variants; bool loaded; uint texmask; char *autograss; Texture *grasstex, *thumbnail; char *layermaskname; int layermaskmode; float layermaskscale; ImageData *layermask; bool ffenv; Slot(int index = -1) : index(index), variants(NULL), autograss(NULL), layermaskname(NULL), layermask(NULL) { reset(); } void reset() { sts.shrink(0); shader = NULL; params.shrink(0); loaded = false; texmask = 0; DELETEA(autograss); grasstex = NULL; thumbnail = NULL; DELETEA(layermaskname); layermaskmode = 0; layermaskscale = 1; if(layermask) DELETEP(layermask); ffenv = false; } void cleanup() { loaded = false; grasstex = NULL; thumbnail = NULL; loopv(sts) { Tex &t = sts[i]; t.t = NULL; t.combined = -1; } } }; inline void VSlot::addvariant(Slot *slot) { if(!slot->variants) slot->variants = this; else { VSlot *prev = slot->variants; while(prev->next) prev = prev->next; prev->next = this; } } struct MSlot : Slot, VSlot { MSlot() : VSlot(this) {} void reset() { Slot::reset(); VSlot::reset(); } void cleanup() { Slot::cleanup(); VSlot::cleanup(); } }; struct cubemapside { GLenum target; const char *name; bool flipx, flipy, swapxy; }; extern cubemapside cubemapsides[6]; extern Texture *notexture; extern Shader *defaultshader, *rectshader, *cubemapshader, *notextureshader, *nocolorshader, *nocolorglslshader, *foggedshader, *foggednotextureshader, *stdworldshader, *lineshader, *foggedlineshader; extern int reservevpparams, maxvpenvparams, maxvplocalparams, maxfpenvparams, maxfplocalparams, maxvsuniforms, maxfsuniforms; extern Shader *lookupshaderbyname(const char *name); extern Shader *useshaderbyname(const char *name); extern Texture *loadthumbnail(Slot &slot); extern void resetslotshader(); extern void setslotshader(Slot &s); extern void linkslotshader(Slot &s, bool load = true); extern void linkvslotshader(VSlot &s, bool load = true); extern void linkslotshaders(); extern void setenvparamf(const char *name, int type, int index, float x = 0, float y = 0, float z = 0, float w = 0); extern void setenvparamfv(const char *name, int type, int index, const float *v); extern void flushenvparamf(const char *name, int type, int index, float x = 0, float y = 0, float z = 0, float w = 0); extern void flushenvparamfv(const char *name, int type, int index, const float *v); extern void setlocalparamf(const char *name, int type, int index, float x = 0, float y = 0, float z = 0, float w = 0); extern void setlocalparamfv(const char *name, int type, int index, const float *v); extern void invalidateenvparams(int type, int start, int count); extern ShaderParam *findshaderparam(Slot &s, const char *name, int type, int index); extern ShaderParam *findshaderparam(VSlot &s, const char *name, int type, int index); extern const char *getshaderparamname(const char *name); extern int maxtmus, nolights, nowater, nomasks; extern void inittmus(); extern void resettmu(int n); extern void scaletmu(int n, int rgbscale, int alphascale = 0); extern void colortmu(int n, float r = 0, float g = 0, float b = 0, float a = 0); extern void setuptmu(int n, const char *rgbfunc = NULL, const char *alphafunc = NULL); #define MAXDYNLIGHTS 5 #define DYNLIGHTBITS 6 #define DYNLIGHTMASK ((1< slots; extern vector vslots; sauerbraten-0.0.20130203.dfsg/engine/md5.h0000644000175000017500000003771712072642735017527 0ustar vincentvincentstruct md5; struct md5joint { vec pos; quat orient; }; struct md5weight { int joint; float bias; vec pos; }; struct md5vert { float u, v; ushort start, count; }; struct md5hierarchy { string name; int parent, flags, start; }; struct md5 : skelmodel, skelloader { md5(const char *name) : skelmodel(name) {} static const char *formatname() { return "md5"; } int type() const { return MDL_MD5; } struct md5mesh : skelmesh { md5weight *weightinfo; int numweights; md5vert *vertinfo; md5mesh() : weightinfo(NULL), numweights(0), vertinfo(NULL) { } ~md5mesh() { cleanup(); } void cleanup() { DELETEA(weightinfo); DELETEA(vertinfo); } void buildverts(vector &joints) { loopi(numverts) { md5vert &v = vertinfo[i]; vec pos(0, 0, 0); loopk(v.count) { md5weight &w = weightinfo[v.start+k]; md5joint &j = joints[w.joint]; vec wpos = j.orient.rotate(w.pos); wpos.add(j.pos); wpos.mul(w.bias); pos.add(wpos); } vert &vv = verts[i]; vv.pos = pos; vv.u = v.u; vv.v = v.v; blendcombo c; int sorted = 0; loopj(v.count) { md5weight &w = weightinfo[v.start+j]; sorted = c.addweight(sorted, w.bias, w.joint); } c.finalize(sorted); vv.blend = addblendcombo(c); } } void load(stream *f, char *buf, size_t bufsize) { md5weight w; md5vert v; tri t; int index; while(f->getline(buf, bufsize) && buf[0]!='}') { if(strstr(buf, "// meshes:")) { char *start = strchr(buf, ':')+1; if(*start==' ') start++; char *end = start + strlen(start)-1; while(end >= start && isspace(*end)) end--; name = newstring(start, end+1-start); } else if(strstr(buf, "shader")) { char *start = strchr(buf, '"'), *end = start ? strchr(start+1, '"') : NULL; if(start && end) { char *texname = newstring(start+1, end-(start+1)); part *p = loading->parts.last(); p->initskins(notexture, notexture, group->meshes.length()); skin &s = p->skins.last(); s.tex = textureload(makerelpath(dir, texname), 0, true, false); delete[] texname; } } else if(sscanf(buf, " numverts %d", &numverts)==1) { numverts = max(numverts, 0); if(numverts) { vertinfo = new md5vert[numverts]; verts = new vert[numverts]; } } else if(sscanf(buf, " numtris %d", &numtris)==1) { numtris = max(numtris, 0); if(numtris) tris = new tri[numtris]; } else if(sscanf(buf, " numweights %d", &numweights)==1) { numweights = max(numweights, 0); if(numweights) weightinfo = new md5weight[numweights]; } else if(sscanf(buf, " vert %d ( %f %f ) %hu %hu", &index, &v.u, &v.v, &v.start, &v.count)==5) { if(index>=0 && index=0 && index=0 && index basejoints; while(f->getline(buf, sizeof(buf))) { int tmp; if(sscanf(buf, " MD5Version %d", &tmp)==1) { if(tmp!=10) { delete f; return false; } } else if(sscanf(buf, " numJoints %d", &tmp)==1) { if(tmp<1) { delete f; return false; } if(skel->numbones>0) continue; skel->numbones = tmp; skel->bones = new boneinfo[skel->numbones]; } else if(sscanf(buf, " numMeshes %d", &tmp)==1) { if(tmp<1) { delete f; return false; } } else if(strstr(buf, "joints {")) { string name; int parent; md5joint j; while(f->getline(buf, sizeof(buf)) && buf[0]!='}') { char *curbuf = buf, *curname = name; bool allowspace = false; while(*curbuf && isspace(*curbuf)) curbuf++; if(*curbuf == '"') { curbuf++; allowspace = true; } while(*curbuf && curname < &name[sizeof(name)-1]) { char c = *curbuf++; if(c == '"') break; if(isspace(c) && !allowspace) break; *curname++ = c; } *curname = '\0'; if(sscanf(curbuf, " %d ( %f %f %f ) ( %f %f %f )", &parent, &j.pos.x, &j.pos.y, &j.pos.z, &j.orient.x, &j.orient.y, &j.orient.z)==7) { j.pos.y = -j.pos.y; j.orient.x = -j.orient.x; j.orient.z = -j.orient.z; if(basejoints.length()numbones) { if(!skel->bones[basejoints.length()].name) skel->bones[basejoints.length()].name = newstring(name); skel->bones[basejoints.length()].parent = parent; } j.orient.restorew(); basejoints.add(j); } } if(basejoints.length()!=skel->numbones) { delete f; return false; } } else if(strstr(buf, "mesh {")) { md5mesh *m = new md5mesh; m->group = this; meshes.add(m); m->load(f, buf, sizeof(buf)); if(!m->numtris || !m->numverts) { conoutf("empty mesh in %s", filename); meshes.removeobj(m); delete m; } } } if(skel->shared <= 1) { skel->linkchildren(); loopv(basejoints) { boneinfo &b = skel->bones[i]; b.base = dualquat(basejoints[i].orient, basejoints[i].pos); (b.invbase = b.base).invert(); } } loopv(meshes) { md5mesh &m = *(md5mesh *)meshes[i]; m.buildverts(basejoints); if(smooth <= 1) m.smoothnorms(smooth); else m.buildnorms(); m.cleanup(); } sortblendcombos(); delete f; return true; } skelanimspec *loadanim(const char *filename) { skelanimspec *sa = skel->findskelanim(filename); if(sa) return sa; stream *f = openfile(filename, "r"); if(!f) return NULL; vector hierarchy; vector basejoints; int animdatalen = 0, animframes = 0; float *animdata = NULL; dualquat *animbones = NULL; char buf[512]; while(f->getline(buf, sizeof(buf))) { int tmp; if(sscanf(buf, " MD5Version %d", &tmp)==1) { if(tmp!=10) { delete f; return NULL; } } else if(sscanf(buf, " numJoints %d", &tmp)==1) { if(tmp!=skel->numbones) { delete f; return NULL; } } else if(sscanf(buf, " numFrames %d", &animframes)==1) { if(animframes<1) { delete f; return NULL; } } else if(sscanf(buf, " frameRate %d", &tmp)==1); else if(sscanf(buf, " numAnimatedComponents %d", &animdatalen)==1) { if(animdatalen>0) animdata = new float[animdatalen]; } else if(strstr(buf, "bounds {")) { while(f->getline(buf, sizeof(buf)) && buf[0]!='}'); } else if(strstr(buf, "hierarchy {")) { while(f->getline(buf, sizeof(buf)) && buf[0]!='}') { md5hierarchy h; if(sscanf(buf, " %100s %d %d %d", h.name, &h.parent, &h.flags, &h.start)==4) hierarchy.add(h); } } else if(strstr(buf, "baseframe {")) { while(f->getline(buf, sizeof(buf)) && buf[0]!='}') { md5joint j; if(sscanf(buf, " ( %f %f %f ) ( %f %f %f )", &j.pos.x, &j.pos.y, &j.pos.z, &j.orient.x, &j.orient.y, &j.orient.z)==6) { j.pos.y = -j.pos.y; j.orient.x = -j.orient.x; j.orient.z = -j.orient.z; j.orient.restorew(); basejoints.add(j); } } if(basejoints.length()!=skel->numbones) { delete f; return NULL; } animbones = new dualquat[(skel->numframes+animframes)*skel->numbones]; if(skel->framebones) { memcpy(animbones, skel->framebones, skel->numframes*skel->numbones*sizeof(dualquat)); delete[] skel->framebones; } skel->framebones = animbones; animbones += skel->numframes*skel->numbones; sa = &skel->addskelanim(filename); sa->frame = skel->numframes; sa->range = animframes; skel->numframes += animframes; } else if(sscanf(buf, " frame %d", &tmp)==1) { for(int numdata = 0; f->getline(buf, sizeof(buf)) && buf[0]!='}';) { for(char *src = buf, *next = src; numdata < animdatalen; numdata++, src = next) { animdata[numdata] = strtod(src, &next); if(next <= src) break; } } dualquat *frame = &animbones[tmp*skel->numbones]; loopv(basejoints) { md5hierarchy &h = hierarchy[i]; md5joint j = basejoints[i]; if(h.start < animdatalen && h.flags) { float *jdata = &animdata[h.start]; if(h.flags&1) j.pos.x = *jdata++; if(h.flags&2) j.pos.y = -*jdata++; if(h.flags&4) j.pos.z = *jdata++; if(h.flags&8) j.orient.x = -*jdata++; if(h.flags&16) j.orient.y = *jdata++; if(h.flags&32) j.orient.z = -*jdata++; j.orient.restorew(); } frame[i] = dualquat(j.orient, j.pos); if(adjustments.inrange(i)) adjustments[i].adjust(frame[i]); frame[i].mul(skel->bones[i].invbase); if(h.parent >= 0) frame[i].mul(skel->bones[h.parent].base, dualquat(frame[i])); frame[i].fixantipodal(skel->framebones[i]); } } } DELETEA(animdata); delete f; return sa; } bool load(const char *meshfile, float smooth) { name = newstring(meshfile); if(!loadmesh(meshfile, smooth)) return false; return true; } }; meshgroup *loadmeshes(const char *name, va_list args) { md5meshgroup *group = new md5meshgroup; group->shareskeleton(va_arg(args, char *)); if(!group->load(name, va_arg(args, double))) { delete group; return NULL; } return group; } bool loaddefaultparts() { skelpart &mdl = *new skelpart; parts.add(&mdl); mdl.model = this; mdl.index = 0; mdl.pitchscale = mdl.pitchoffset = mdl.pitchmin = mdl.pitchmax = 0; adjustments.setsize(0); const char *fname = loadname + strlen(loadname); do --fname; while(fname >= loadname && *fname!='/' && *fname!='\\'); fname++; defformatstring(meshname)("packages/models/%s/%s.md5mesh", loadname, fname); mdl.meshes = sharemeshes(path(meshname), NULL, 2.0); if(!mdl.meshes) return false; mdl.initanimparts(); mdl.initskins(); defformatstring(animname)("packages/models/%s/%s.md5anim", loadname, fname); ((md5meshgroup *)mdl.meshes)->loadanim(path(animname)); return true; } bool load() { if(loaded) return true; formatstring(dir)("packages/models/%s", loadname); defformatstring(cfgname)("packages/models/%s/md5.cfg", loadname); loading = this; identflags &= ~IDF_PERSIST; if(execfile(cfgname, false) && parts.length()) // configured md5, will call the md5* commands below { identflags |= IDF_PERSIST; loading = NULL; loopv(parts) if(!parts[i]->meshes) return false; } else // md5 without configuration, try default tris and skin { identflags |= IDF_PERSIST; if(!loaddefaultparts()) { loading = NULL; return false; } loading = NULL; } scale /= 4; parts[0]->translate = translate; loopv(parts) { skelpart *p = (skelpart *)parts[i]; p->endanimparts(); p->meshes->shared++; } return loaded = true; } }; skelcommands md5commands; sauerbraten-0.0.20130203.dfsg/engine/explosion.h0000644000175000017500000004121112067647457021054 0ustar vincentvincent//cache our unit hemisphere static GLushort *hemiindices = NULL; static vec *hemiverts = NULL; static int heminumverts = 0, heminumindices = 0; static GLuint hemivbuf = 0, hemiebuf = 0; static void subdivide(int depth, int face); static void genface(int depth, int i1, int i2, int i3) { int face = heminumindices; heminumindices += 3; hemiindices[face] = i1; hemiindices[face+1] = i2; hemiindices[face+2] = i3; subdivide(depth, face); } static void subdivide(int depth, int face) { if(depth-- <= 0) return; int idx[6]; loopi(3) idx[i] = hemiindices[face+i]; loopi(3) { int vert = heminumverts++; hemiverts[vert] = vec(hemiverts[idx[i]]).add(hemiverts[idx[(i+1)%3]]).normalize(); //push on to unit sphere idx[3+i] = vert; hemiindices[face+i] = vert; } subdivide(depth, face); loopi(3) genface(depth, idx[i], idx[3+i], idx[3+(i+2)%3]); } //subdiv version wobble much more nicely than a lat/longitude version static void inithemisphere(int hres, int depth) { const int tris = hres << (2*depth); heminumverts = heminumindices = 0; DELETEA(hemiverts); DELETEA(hemiindices); hemiverts = new vec[tris+1]; hemiindices = new GLushort[tris*3]; hemiverts[heminumverts++] = vec(0.0f, 0.0f, 1.0f); //build initial 'hres' sided pyramid loopi(hres) hemiverts[heminumverts++] = vec(sincos360[(360*i)/hres], 0.0f); loopi(hres) genface(depth, 0, i+1, 1+(i+1)%hres); if(hasVBO) { if(renderpath!=R_FIXEDFUNCTION) { if(!hemivbuf) glGenBuffers_(1, &hemivbuf); glBindBuffer_(GL_ARRAY_BUFFER_ARB, hemivbuf); glBufferData_(GL_ARRAY_BUFFER_ARB, heminumverts*sizeof(vec), hemiverts, GL_STATIC_DRAW_ARB); DELETEA(hemiverts); } if(!hemiebuf) glGenBuffers_(1, &hemiebuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, hemiebuf); glBufferData_(GL_ELEMENT_ARRAY_BUFFER_ARB, heminumindices*sizeof(GLushort), hemiindices, GL_STATIC_DRAW_ARB); DELETEA(hemiindices); } } static GLuint expmodtex[2] = {0, 0}; static GLuint lastexpmodtex = 0; static GLuint createexpmodtex(int size, float minval) { uchar *data = new uchar[size*size], *dst = data; loop(y, size) loop(x, size) { float dx = 2*float(x)/(size-1) - 1, dy = 2*float(y)/(size-1) - 1; float z = max(0.0f, 1.0f - dx*dx - dy*dy); if(minval) z = sqrtf(z); else loopk(2) z *= z; *dst++ = uchar(max(z, minval)*255); } GLuint tex = 0; glGenTextures(1, &tex); createtexture(tex, size, size, data, 3, 2, GL_ALPHA); delete[] data; return tex; } static struct expvert { vec pos; float u, v, s, t; } *expverts = NULL; static GLuint expvbuf = 0; static void animateexplosion() { static int lastexpmillis = 0; if(expverts && lastexpmillis == lastmillis) { if(hasVBO) glBindBuffer_(GL_ARRAY_BUFFER_ARB, expvbuf); return; } lastexpmillis = lastmillis; vec center = vec(13.0f, 2.3f, 7.1f); //only update once per frame! - so use the same center for all... if(!expverts) expverts = new expvert[heminumverts]; loopi(heminumverts) { expvert &e = expverts[i]; vec &v = hemiverts[i]; //texgen - scrolling billboard e.u = v.x*0.5f + 0.0004f*lastmillis; e.v = v.y*0.5f + 0.0004f*lastmillis; //ensure the mod texture is wobbled e.s = v.x*0.5f + 0.5f; e.t = v.y*0.5f + 0.5f; //wobble - similar to shader code float wobble = v.dot(center) + 0.002f*lastmillis; wobble -= floor(wobble); wobble = 1.0f + fabs(wobble - 0.5f)*0.5f; e.pos = vec(v).mul(wobble); } if(hasVBO) { if(!expvbuf) glGenBuffers_(1, &expvbuf); glBindBuffer_(GL_ARRAY_BUFFER_ARB, expvbuf); glBufferData_(GL_ARRAY_BUFFER_ARB, heminumverts*sizeof(expvert), expverts, GL_STREAM_DRAW_ARB); } } static struct spherevert { vec pos; float s, t; } *sphereverts = NULL; static GLushort *sphereindices = NULL; static int spherenumverts = 0, spherenumindices = 0; static GLuint spherevbuf = 0, sphereebuf = 0; static void initsphere(int slices, int stacks) { DELETEA(sphereverts); spherenumverts = (stacks+1)*(slices+1); sphereverts = new spherevert[spherenumverts]; float ds = 1.0f/slices, dt = 1.0f/stacks, t = 1.0f; loopi(stacks+1) { float rho = M_PI*(1-t), s = 0.0f; loopj(slices+1) { float theta = j==slices ? 0 : 2*M_PI*s; spherevert &v = sphereverts[i*(slices+1) + j]; v.pos = vec(-sin(theta)*sin(rho), cos(theta)*sin(rho), cos(rho)); v.s = s; v.t = t; s += ds; } t -= dt; } DELETEA(sphereindices); spherenumindices = stacks*slices*3*2; sphereindices = new ushort[spherenumindices]; GLushort *curindex = sphereindices; loopi(stacks) { loopk(slices) { int j = i%2 ? slices-k-1 : k; *curindex++ = i*(slices+1)+j; *curindex++ = (i+1)*(slices+1)+j; *curindex++ = i*(slices+1)+j+1; *curindex++ = i*(slices+1)+j+1; *curindex++ = (i+1)*(slices+1)+j; *curindex++ = (i+1)*(slices+1)+j+1; } } if(hasVBO) { if(!spherevbuf) glGenBuffers_(1, &spherevbuf); glBindBuffer_(GL_ARRAY_BUFFER_ARB, spherevbuf); glBufferData_(GL_ARRAY_BUFFER_ARB, spherenumverts*sizeof(spherevert), sphereverts, GL_STATIC_DRAW_ARB); DELETEA(sphereverts); if(!sphereebuf) glGenBuffers_(1, &sphereebuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, sphereebuf); glBufferData_(GL_ELEMENT_ARRAY_BUFFER_ARB, spherenumindices*sizeof(GLushort), sphereindices, GL_STATIC_DRAW_ARB); DELETEA(sphereindices); } } VARP(explosion2d, 0, 0, 1); static void setupexplosion() { if(renderpath!=R_FIXEDFUNCTION || maxtmus>=2) { if(!expmodtex[0]) expmodtex[0] = createexpmodtex(64, 0); if(!expmodtex[1]) expmodtex[1] = createexpmodtex(64, 0.25f); lastexpmodtex = 0; } if(renderpath!=R_FIXEDFUNCTION) { if(glaring) { if(explosion2d) SETSHADER(explosion2dglare); else SETSHADER(explosion3dglare); } else if(!reflecting && !refracting && depthfx && depthfxtex.rendertex && numdepthfxranges>0) { if(depthfxtex.target==GL_TEXTURE_RECTANGLE_ARB) { if(!depthfxtex.highprecision()) { if(explosion2d) SETSHADER(explosion2dsoft8rect); else SETSHADER(explosion3dsoft8rect); } else if(explosion2d) SETSHADER(explosion2dsoftrect); else SETSHADER(explosion3dsoftrect); } else { if(!depthfxtex.highprecision()) { if(explosion2d) SETSHADER(explosion2dsoft8); else SETSHADER(explosion3dsoft8); } else if(explosion2d) SETSHADER(explosion2dsoft); else SETSHADER(explosion3dsoft); } } else if(explosion2d) SETSHADER(explosion2d); else SETSHADER(explosion3d); } if(renderpath==R_FIXEDFUNCTION || explosion2d) { if(!hemiverts && !hemivbuf) inithemisphere(5, 2); if(renderpath==R_FIXEDFUNCTION) animateexplosion(); if(hasVBO) { if(renderpath!=R_FIXEDFUNCTION) glBindBuffer_(GL_ARRAY_BUFFER_ARB, hemivbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, hemiebuf); } expvert *verts = renderpath==R_FIXEDFUNCTION ? (hasVBO ? 0 : expverts) : (expvert *)hemiverts; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, renderpath==R_FIXEDFUNCTION ? sizeof(expvert) : sizeof(vec), verts); if(renderpath==R_FIXEDFUNCTION) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(expvert), &verts->u); if(maxtmus>=2) { setuptmu(0, "C * T", "= Ca"); glActiveTexture_(GL_TEXTURE1_ARB); glClientActiveTexture_(GL_TEXTURE1_ARB); glEnable(GL_TEXTURE_2D); setuptmu(1, "P * Ta x 4", "Pa * Ta x 4"); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(expvert), &verts->s); glActiveTexture_(GL_TEXTURE0_ARB); glClientActiveTexture_(GL_TEXTURE0_ARB); } } } else { if(!sphereverts && !spherevbuf) initsphere(12, 6); if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, spherevbuf); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, sphereebuf); } glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(spherevert), &sphereverts->pos); glTexCoordPointer(2, GL_FLOAT, sizeof(spherevert), &sphereverts->s); } } static void drawexpverts(int numverts, int numindices, GLushort *indices) { if(hasDRE) glDrawRangeElements_(GL_TRIANGLES, 0, numverts-1, numindices, GL_UNSIGNED_SHORT, indices); else glDrawElements(GL_TRIANGLES, numindices, GL_UNSIGNED_SHORT, indices); xtraverts += numindices; glde++; } static void drawexplosion(bool inside, uchar r, uchar g, uchar b, uchar a) { if((renderpath!=R_FIXEDFUNCTION || maxtmus>=2) && lastexpmodtex != expmodtex[inside ? 1 : 0]) { glActiveTexture_(GL_TEXTURE1_ARB); lastexpmodtex = expmodtex[inside ? 1 :0]; glBindTexture(GL_TEXTURE_2D, lastexpmodtex); glActiveTexture_(GL_TEXTURE0_ARB); } int passes = !reflecting && !refracting && inside ? 2 : 1; if(renderpath!=R_FIXEDFUNCTION && !explosion2d) { if(inside) glScalef(1, 1, -1); loopi(passes) { glColor4ub(r, g, b, i ? a/2 : a); if(i) glDepthFunc(GL_GEQUAL); drawexpverts(spherenumverts, spherenumindices, sphereindices); if(i) glDepthFunc(GL_LESS); } return; } loopi(passes) { glColor4ub(r, g, b, i ? a/2 : a); if(i) { glScalef(1, 1, -1); glDepthFunc(GL_GEQUAL); } if(inside) { if(passes >= 2) { glCullFace(GL_FRONT); drawexpverts(heminumverts, heminumindices, hemiindices); glCullFace(GL_BACK); } glScalef(1, 1, -1); } drawexpverts(heminumverts, heminumindices, hemiindices); if(i) glDepthFunc(GL_LESS); } } static void cleanupexplosion() { glDisableClientState(GL_VERTEX_ARRAY); if(renderpath==R_FIXEDFUNCTION) { glDisableClientState(GL_TEXTURE_COORD_ARRAY); if(maxtmus>=2) { resettmu(0); glActiveTexture_(GL_TEXTURE1_ARB); glClientActiveTexture_(GL_TEXTURE1_ARB); glDisable(GL_TEXTURE_2D); resettmu(1); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glActiveTexture_(GL_TEXTURE0_ARB); glClientActiveTexture_(GL_TEXTURE0_ARB); } } else { if(!explosion2d) glDisableClientState(GL_TEXTURE_COORD_ARRAY); } if(hasVBO) { glBindBuffer_(GL_ARRAY_BUFFER_ARB, 0); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); } } static void deleteexplosions() { loopi(2) if(expmodtex[i]) { glDeleteTextures(1, &expmodtex[i]); expmodtex[i] = 0; } if(hemivbuf) { glDeleteBuffers_(1, &hemivbuf); hemivbuf = 0; } if(hemiebuf) { glDeleteBuffers_(1, &hemiebuf); hemiebuf = 0; } DELETEA(hemiverts); DELETEA(hemiindices); if(expvbuf) { glDeleteBuffers_(1, &expvbuf); expvbuf = 0; } DELETEA(expverts); if(spherevbuf) { glDeleteBuffers_(1, &spherevbuf); spherevbuf = 0; } if(sphereebuf) { glDeleteBuffers_(1, &sphereebuf); sphereebuf = 0; } DELETEA(sphereverts); DELETEA(sphereindices); } static const float WOBBLE = 1.25f; struct fireballrenderer : listrenderer { fireballrenderer(const char *texname) : listrenderer(texname, 0, PT_FIREBALL|PT_GLARE) {} void startrender() { setupexplosion(); } void endrender() { cleanupexplosion(); particleshader->set(); } void cleanup() { deleteexplosions(); } int finddepthfxranges(void **owners, float *ranges, int numranges, int maxranges, vec &bbmin, vec &bbmax) { static struct fireballent : physent { fireballent() { type = ENT_CAMERA; collidetype = COLLIDE_AABB; } } e; for(listparticle *p = list; p; p = p->next) { int ts = p->fade <= 5 ? 1 : lastmillis-p->millis; float pmax = p->val, size = p->fade ? float(ts)/p->fade : 1, psize = (p->size + pmax * size)*WOBBLE; if(2*(p->size + pmax)*WOBBLE < depthfxblend || (!depthfxtex.highprecision() && !depthfxtex.emulatehighprecision() && psize > depthfxscale - depthfxbias) || isfoggedsphere(psize, p->o)) continue; e.o = p->o; e.radius = e.xradius = e.yradius = e.eyeheight = e.aboveeye = psize; if(::collide(&e, vec(0, 0, 0), 0, false)) continue; if(depthfxscissor==2 && !depthfxtex.addscissorbox(p->o, psize)) continue; vec dir = camera1->o; dir.sub(p->o); float dist = dir.magnitude(); dir.mul(psize/dist).add(p->o); float depth = depthfxtex.eyedepth(dir); loopk(3) { bbmin[k] = min(bbmin[k], p->o[k] - psize); bbmax[k] = max(bbmax[k], p->o[k] + psize); } int pos = numranges; loopi(numranges) if(depth < ranges[i]) { pos = i; break; } if(pos >= maxranges) continue; if(numranges > pos) { int moved = min(numranges-pos, maxranges-(pos+1)); memmove(&ranges[pos+1], &ranges[pos], moved*sizeof(float)); memmove(&owners[pos+1], &owners[pos], moved*sizeof(void *)); } if(numranges < maxranges) numranges++; ranges[pos] = depth; owners[pos] = p; } return numranges; } void seedemitter(particleemitter &pe, const vec &o, const vec &d, int fade, float size, int gravity) { pe.maxfade = max(pe.maxfade, fade); pe.extendbb(o, (size+1+pe.ent->attr2)*WOBBLE); } void renderpart(listparticle *p, const vec &o, const vec &d, int blend, int ts, uchar *color) { float pmax = p->val, size = p->fade ? float(ts)/p->fade : 1, psize = p->size + pmax * size; if(isfoggedsphere(psize*WOBBLE, p->o)) return; glPushMatrix(); glTranslatef(o.x, o.y, o.z); bool inside = o.dist(camera1->o) <= psize*WOBBLE; vec oc(o); oc.sub(camera1->o); if(reflecting) oc.z = o.z - reflectz; float yaw = inside ? camera1->yaw : atan2(oc.y, oc.x)/RAD - 90, pitch = (inside ? camera1->pitch : asin(oc.z/oc.magnitude())/RAD) - 90; vec rotdir; if(renderpath==R_FIXEDFUNCTION || explosion2d) { glRotatef(yaw, 0, 0, 1); glRotatef(pitch, 1, 0, 0); rotdir = vec(0, 0, 1); } else { vec s(1, 0, 0), t(0, 1, 0); s.rotate(pitch*RAD, vec(-1, 0, 0)); s.rotate(yaw*RAD, vec(0, 0, -1)); t.rotate(pitch*RAD, vec(-1, 0, 0)); t.rotate(yaw*RAD, vec(0, 0, -1)); rotdir = vec(-1, 1, -1).normalize(); s.rotate(-lastmillis/7.0f*RAD, rotdir); t.rotate(-lastmillis/7.0f*RAD, rotdir); setlocalparamf("texgenS", SHPARAM_VERTEX, 2, 0.5f*s.x, 0.5f*s.y, 0.5f*s.z, 0.5f); setlocalparamf("texgenT", SHPARAM_VERTEX, 3, 0.5f*t.x, 0.5f*t.y, 0.5f*t.z, 0.5f); } if(renderpath!=R_FIXEDFUNCTION) { setlocalparamf("center", SHPARAM_VERTEX, 0, o.x, o.y, o.z); setlocalparamf("animstate", SHPARAM_VERTEX, 1, size, psize, pmax, float(lastmillis)); binddepthfxparams(depthfxblend, inside ? blend/(2*255.0f) : 0, 2*(p->size + pmax)*WOBBLE >= depthfxblend, p); } glRotatef(lastmillis/7.0f, -rotdir.x, rotdir.y, -rotdir.z); glScalef(-psize, psize, -psize); drawexplosion(inside, color[0], color[1], color[2], blend); glPopMatrix(); } }; static fireballrenderer fireballs("packages/particles/explosion.png"), bluefireballs("packages/particles/plasma.png"); sauerbraten-0.0.20130203.dfsg/engine/rendermodel.cpp0000644000175000017500000007545512077043321021665 0ustar vincentvincent#include "engine.h" VARP(oqdynent, 0, 1, 1); VARP(animationinterpolationtime, 0, 150, 1000); model *loadingmodel = NULL; #include "ragdoll.h" #include "animmodel.h" #include "vertmodel.h" #include "skelmodel.h" static model *(__cdecl *modeltypes[NUMMODELTYPES])(const char *); static int addmodeltype(int type, model *(__cdecl *loader)(const char *)) { modeltypes[type] = loader; return type; } #define MODELTYPE(modeltype, modelclass) \ static model *__loadmodel__##modelclass(const char *filename) \ { \ return new modelclass(filename); \ } \ static int __dummy__##modelclass = addmodeltype((modeltype), __loadmodel__##modelclass); #include "md2.h" #include "md3.h" #include "md5.h" #include "obj.h" #include "smd.h" #include "iqm.h" MODELTYPE(MDL_MD2, md2); MODELTYPE(MDL_MD3, md3); MODELTYPE(MDL_MD5, md5); MODELTYPE(MDL_OBJ, obj); MODELTYPE(MDL_SMD, smd); MODELTYPE(MDL_IQM, iqm); #define checkmdl if(!loadingmodel) { conoutf(CON_ERROR, "not loading a model"); return; } void mdlcullface(int *cullface) { checkmdl; loadingmodel->setcullface(*cullface!=0); } COMMAND(mdlcullface, "i"); void mdlcollide(int *collide) { checkmdl; loadingmodel->collide = *collide!=0; } COMMAND(mdlcollide, "i"); void mdlellipsecollide(int *collide) { checkmdl; loadingmodel->ellipsecollide = *collide!=0; } COMMAND(mdlellipsecollide, "i"); void mdlspec(int *percent) { checkmdl; float spec = 1.0f; if(*percent>0) spec = *percent/100.0f; else if(*percent<0) spec = 0.0f; loadingmodel->setspec(spec); } COMMAND(mdlspec, "i"); void mdlambient(int *percent) { checkmdl; float ambient = 0.3f; if(*percent>0) ambient = *percent/100.0f; else if(*percent<0) ambient = 0.0f; loadingmodel->setambient(ambient); } COMMAND(mdlambient, "i"); void mdlalphatest(float *cutoff) { checkmdl; loadingmodel->setalphatest(max(0.0f, min(1.0f, *cutoff))); } COMMAND(mdlalphatest, "f"); void mdlalphablend(int *blend) { checkmdl; loadingmodel->setalphablend(*blend!=0); } COMMAND(mdlalphablend, "i"); void mdlalphadepth(int *depth) { checkmdl; loadingmodel->alphadepth = *depth!=0; } COMMAND(mdlalphadepth, "i"); void mdldepthoffset(int *offset) { checkmdl; loadingmodel->depthoffset = *offset!=0; } COMMAND(mdldepthoffset, "i"); void mdlglow(int *percent, int *delta, float *pulse) { checkmdl; float glow = 3.0f, glowdelta = *delta/100.0f, glowpulse = *pulse > 0 ? *pulse/1000.0f : 0; if(*percent>0) glow = *percent/100.0f; else if(*percent<0) glow = 0.0f; glowdelta -= glow; loadingmodel->setglow(glow, glowdelta, glowpulse); } COMMAND(mdlglow, "iif"); void mdlglare(float *specglare, float *glowglare) { checkmdl; loadingmodel->setglare(*specglare, *glowglare); } COMMAND(mdlglare, "ff"); void mdlenvmap(float *envmapmax, float *envmapmin, char *envmap) { checkmdl; loadingmodel->setenvmap(*envmapmin, *envmapmax, envmap[0] ? cubemapload(envmap) : NULL); } COMMAND(mdlenvmap, "ffs"); void mdlfullbright(float *fullbright) { checkmdl; loadingmodel->setfullbright(*fullbright); } COMMAND(mdlfullbright, "f"); void mdlshader(char *shader) { checkmdl; loadingmodel->setshader(lookupshaderbyname(shader)); } COMMAND(mdlshader, "s"); void mdlspin(float *yaw, float *pitch) { checkmdl; loadingmodel->spinyaw = *yaw; loadingmodel->spinpitch = *pitch; } COMMAND(mdlspin, "ff"); void mdlscale(int *percent) { checkmdl; float scale = 0.3f; if(*percent>0) scale = *percent/100.0f; else if(*percent<0) scale = 0.0f; loadingmodel->scale = scale; } COMMAND(mdlscale, "i"); void mdltrans(float *x, float *y, float *z) { checkmdl; loadingmodel->translate = vec(*x, *y, *z); } COMMAND(mdltrans, "fff"); void mdlyaw(float *angle) { checkmdl; loadingmodel->offsetyaw = *angle; } COMMAND(mdlyaw, "f"); void mdlpitch(float *angle) { checkmdl; loadingmodel->offsetpitch = *angle; } COMMAND(mdlpitch, "f"); void mdlshadow(int *shadow) { checkmdl; loadingmodel->shadow = *shadow!=0; } COMMAND(mdlshadow, "i"); void mdlbb(float *rad, float *h, float *eyeheight) { checkmdl; loadingmodel->collideradius = *rad; loadingmodel->collideheight = *h; loadingmodel->eyeheight = *eyeheight; } COMMAND(mdlbb, "fff"); void mdlextendbb(float *x, float *y, float *z) { checkmdl; loadingmodel->bbextend = vec(*x, *y, *z); } COMMAND(mdlextendbb, "fff"); void mdlname() { checkmdl; result(loadingmodel->name()); } COMMAND(mdlname, ""); #define checkragdoll \ if(!loadingmodel->skeletal()) { conoutf(CON_ERROR, "not loading a skeletal model"); return; } \ skelmodel *m = (skelmodel *)loadingmodel; \ skelmodel::skelmeshgroup *meshes = (skelmodel::skelmeshgroup *)m->parts.last()->meshes; \ if(!meshes) return; \ skelmodel::skeleton *skel = meshes->skel; \ if(!skel->ragdoll) skel->ragdoll = new ragdollskel; \ ragdollskel *ragdoll = skel->ragdoll; \ if(ragdoll->loaded) return; void rdvert(float *x, float *y, float *z, float *radius) { checkragdoll; ragdollskel::vert &v = ragdoll->verts.add(); v.pos = vec(*x, *y, *z); v.radius = *radius > 0 ? *radius : 1; } COMMAND(rdvert, "ffff"); void rdeye(int *v) { checkragdoll; ragdoll->eye = *v; } COMMAND(rdeye, "i"); void rdtri(int *v1, int *v2, int *v3) { checkragdoll; ragdollskel::tri &t = ragdoll->tris.add(); t.vert[0] = *v1; t.vert[1] = *v2; t.vert[2] = *v3; } COMMAND(rdtri, "iii"); void rdjoint(int *n, int *t, int *v1, int *v2, int *v3) { checkragdoll; if(*n < 0 || *n >= skel->numbones) return; ragdollskel::joint &j = ragdoll->joints.add(); j.bone = *n; j.tri = *t; j.vert[0] = *v1; j.vert[1] = *v2; j.vert[2] = *v3; } COMMAND(rdjoint, "iibbb"); void rdlimitdist(int *v1, int *v2, float *mindist, float *maxdist) { checkragdoll; ragdollskel::distlimit &d = ragdoll->distlimits.add(); d.vert[0] = *v1; d.vert[1] = *v2; d.mindist = *mindist; d.maxdist = max(*maxdist, *mindist); } COMMAND(rdlimitdist, "iiff"); void rdlimitrot(int *t1, int *t2, float *maxangle, float *qx, float *qy, float *qz, float *qw) { checkragdoll; ragdollskel::rotlimit &r = ragdoll->rotlimits.add(); r.tri[0] = *t1; r.tri[1] = *t2; r.maxangle = *maxangle * RAD; r.middle = matrix3x3(quat(*qx, *qy, *qz, *qw)); } COMMAND(rdlimitrot, "iifffff"); void rdanimjoints(int *on) { checkragdoll; ragdoll->animjoints = *on!=0; } COMMAND(rdanimjoints, "i"); // mapmodels vector mapmodels; void mmodel(char *name) { mapmodelinfo &mmi = mapmodels.add(); copystring(mmi.name, name); mmi.m = NULL; } void mapmodelcompat(int *rad, int *h, int *tex, char *name, char *shadow) { mmodel(name); } void mapmodelreset(int *n) { if(!(identflags&IDF_OVERRIDDEN) && !game::allowedittoggle()) return; mapmodels.shrink(clamp(*n, 0, mapmodels.length())); } mapmodelinfo *getmminfo(int i) { return mapmodels.inrange(i) ? &mapmodels[i] : 0; } const char *mapmodelname(int i) { return mapmodels.inrange(i) ? mapmodels[i].name : NULL; } COMMAND(mmodel, "s"); COMMANDN(mapmodel, mapmodelcompat, "iiiss"); COMMAND(mapmodelreset, "i"); ICOMMAND(mapmodelname, "i", (int *index), { result(mapmodels.inrange(*index) ? mapmodels[*index].name : ""); }); ICOMMAND(nummapmodels, "", (), { intret(mapmodels.length()); }); // model registry hashtable mdllookup; vector preloadmodels; void preloadmodel(const char *name) { if(!name || !name[0] || mdllookup.access(name)) return; preloadmodels.add(newstring(name)); } void flushpreloadedmodels(bool msg) { loopv(preloadmodels) { loadprogress = float(i+1)/preloadmodels.length(); model *m = loadmodel(preloadmodels[i], -1, msg); if(!m) { if(msg) conoutf(CON_WARN, "could not load model: %s", preloadmodels[i]); } else { m->preloadmeshes(); } } preloadmodels.deletearrays(); loadprogress = 0; } void preloadusedmapmodels(bool msg, bool bih) { vector &ents = entities::getents(); vector mapmodels; loopv(ents) { extentity &e = *ents[i]; if(e.type==ET_MAPMODEL && e.attr2 >= 0 && mapmodels.find(e.attr2) < 0) mapmodels.add(e.attr2); } loopv(mapmodels) { loadprogress = float(i+1)/mapmodels.length(); int mmindex = mapmodels[i]; mapmodelinfo *mmi = getmminfo(mmindex); if(!mmi) { if(msg) conoutf(CON_WARN, "could not find map model: %d", mmindex); } else if(mmi->name[0] && !loadmodel(NULL, mmindex, msg)) { if(msg) conoutf(CON_WARN, "could not load model: %s", mmi->name); } else if(mmi->m) { if(bih) mmi->m->preloadBIH(); mmi->m->preloadmeshes(); } } loadprogress = 0; } model *loadmodel(const char *name, int i, bool msg) { if(!name) { if(!mapmodels.inrange(i)) return NULL; mapmodelinfo &mmi = mapmodels[i]; if(mmi.m) return mmi.m; name = mmi.name; } model **mm = mdllookup.access(name); model *m; if(mm) m = *mm; else { if(!name[0] || loadingmodel || lightmapping > 1) return NULL; if(msg) { defformatstring(filename)("packages/models/%s", name); renderprogress(loadprogress, filename); } loopi(NUMMODELTYPES) { m = modeltypes[i](name); if(!m) continue; loadingmodel = m; if(m->load()) break; DELETEP(m); } loadingmodel = NULL; if(!m) return NULL; mdllookup.access(m->name(), m); m->preloadshaders(); } if(mapmodels.inrange(i) && !mapmodels[i].m) mapmodels[i].m = m; return m; } void preloadmodelshaders() { if(initing) return; enumerate(mdllookup, model *, m, m->preloadshaders()); } void clear_mdls() { enumerate(mdllookup, model *, m, delete m); } void cleanupmodels() { enumerate(mdllookup, model *, m, m->cleanup()); } void clearmodel(char *name) { model **m = mdllookup.access(name); if(!m) { conoutf("model %s is not loaded", name); return; } loopv(mapmodels) if(mapmodels[i].m==*m) mapmodels[i].m = NULL; mdllookup.remove(name); (*m)->cleanup(); delete *m; conoutf("cleared model %s", name); } COMMAND(clearmodel, "s"); bool modeloccluded(const vec ¢er, float radius) { int br = int(radius*2)+1; return pvsoccluded(ivec(int(center.x-radius), int(center.y-radius), int(center.z-radius)), ivec(br, br, br)) || bboccluded(ivec(int(center.x-radius), int(center.y-radius), int(center.z-radius)), ivec(br, br, br)); } VAR(showboundingbox, 0, 0, 2); void render2dbox(vec &o, float x, float y, float z) { glBegin(GL_LINE_LOOP); glVertex3f(o.x, o.y, o.z); glVertex3f(o.x, o.y, o.z+z); glVertex3f(o.x+x, o.y+y, o.z+z); glVertex3f(o.x+x, o.y+y, o.z); glEnd(); } void render3dbox(vec &o, float tofloor, float toceil, float xradius, float yradius) { if(yradius<=0) yradius = xradius; vec c = o; c.sub(vec(xradius, yradius, tofloor)); float xsz = xradius*2, ysz = yradius*2; float h = tofloor+toceil; lineshader->set(); glDisable(GL_TEXTURE_2D); glColor3f(1, 1, 1); render2dbox(c, xsz, 0, h); render2dbox(c, 0, ysz, h); c.add(vec(xsz, ysz, 0)); render2dbox(c, -xsz, 0, h); render2dbox(c, 0, -ysz, h); xtraverts += 16; glEnable(GL_TEXTURE_2D); } void renderellipse(vec &o, float xradius, float yradius, float yaw) { lineshader->set(); glDisable(GL_TEXTURE_2D); glColor3f(0.5f, 0.5f, 0.5f); glBegin(GL_LINE_LOOP); loopi(15) { const vec2 &sc = sincos360[i*(360/15)]; vec p(xradius*sc.x, yradius*sc.y, 0); p.rotate_around_z((yaw+90)*RAD); p.add(o); glVertex3fv(p.v); } glEnd(); glEnable(GL_TEXTURE_2D); } struct batchedmodel { vec pos, color, dir; int anim; float yaw, pitch, transparent; int basetime, basetime2, flags; dynent *d; int attached; occludequery *query; }; struct modelbatch { model *m; int flags; vector batched; }; static vector batches; static vector modelattached; static int numbatches = -1; static occludequery *modelquery = NULL; void startmodelbatches() { numbatches = 0; modelattached.setsize(0); } modelbatch &addbatchedmodel(model *m) { modelbatch *b = NULL; if(m->batch>=0 && m->batchbatch]->m==m) b = batches[m->batch]; else { if(numbatchesbatched.setsize(0); } else b = batches.add(new modelbatch); b->m = m; b->flags = 0; m->batch = numbatches++; } return *b; } void renderbatchedmodel(model *m, batchedmodel &b) { modelattach *a = NULL; if(b.attached>=0) a = &modelattached[b.attached]; int anim = b.anim; if(shadowmapping) { anim |= ANIM_NOSKIN; if(renderpath!=R_FIXEDFUNCTION) setenvparamf("shadowintensity", SHPARAM_VERTEX, 1, b.transparent); } else { if(b.flags&MDL_FULLBRIGHT) anim |= ANIM_FULLBRIGHT; if(b.flags&MDL_GHOST) anim |= ANIM_GHOST; } m->render(anim, b.basetime, b.basetime2, b.pos, b.yaw, b.pitch, b.d, a, b.color, b.dir, b.transparent); } struct transparentmodel { model *m; batchedmodel *batched; float dist; }; static inline bool sorttransparentmodels(const transparentmodel &x, const transparentmodel &y) { return x.dist < y.dist; } void endmodelbatches() { vector transparent; loopi(numbatches) { modelbatch &b = *batches[i]; if(b.batched.empty()) continue; if(b.flags&(MDL_SHADOW|MDL_DYNSHADOW)) { vec center, bbradius; b.m->boundbox(0/*frame*/, center, bbradius); // FIXME loopvj(b.batched) { batchedmodel &bm = b.batched[j]; if(bm.flags&(MDL_SHADOW|MDL_DYNSHADOW)) renderblob(bm.flags&MDL_DYNSHADOW ? BLOB_DYNAMIC : BLOB_STATIC, bm.d && bm.d->ragdoll ? bm.d->ragdoll->center : bm.pos, bm.d ? bm.d->radius : max(bbradius.x, bbradius.y), bm.transparent); } flushblobs(); } bool rendered = false; occludequery *query = NULL; if(b.flags&MDL_GHOST) { loopvj(b.batched) { batchedmodel &bm = b.batched[j]; if((bm.flags&(MDL_CULL_VFC|MDL_GHOST))!=MDL_GHOST || bm.query) continue; if(!rendered) { b.m->startrender(); rendered = true; } renderbatchedmodel(b.m, bm); } if(rendered) { b.m->endrender(); rendered = false; } } loopvj(b.batched) { batchedmodel &bm = b.batched[j]; if(bm.flags&(MDL_CULL_VFC|MDL_GHOST)) continue; if(bm.query!=query) { if(query) endquery(query); query = bm.query; if(query) startquery(query); } if(bm.transparent < 1 && (!query || query->owner==bm.d) && !shadowmapping) { transparentmodel &tm = transparent.add(); tm.m = b.m; tm.batched = &bm; tm.dist = camera1->o.dist(bm.d && bm.d->ragdoll ? bm.d->ragdoll->center : bm.pos); continue; } if(!rendered) { b.m->startrender(); rendered = true; } renderbatchedmodel(b.m, bm); } if(query) endquery(query); if(rendered) b.m->endrender(); } if(transparent.length()) { transparent.sort(sorttransparentmodels); model *lastmodel = NULL; occludequery *query = NULL; loopv(transparent) { transparentmodel &tm = transparent[i]; if(lastmodel!=tm.m) { if(lastmodel) lastmodel->endrender(); (lastmodel = tm.m)->startrender(); } if(query!=tm.batched->query) { if(query) endquery(query); query = tm.batched->query; if(query) startquery(query); } renderbatchedmodel(tm.m, *tm.batched); } if(query) endquery(query); if(lastmodel) lastmodel->endrender(); } numbatches = -1; } void startmodelquery(occludequery *query) { modelquery = query; } void endmodelquery() { int querybatches = 0; loopi(numbatches) { modelbatch &b = *batches[i]; if(b.batched.empty() || b.batched.last().query!=modelquery) continue; querybatches++; } if(querybatches<=1) { if(!querybatches) modelquery->fragments = 0; modelquery = NULL; return; } int minattached = modelattached.length(); startquery(modelquery); loopi(numbatches) { modelbatch &b = *batches[i]; if(b.batched.empty() || b.batched.last().query!=modelquery) continue; b.m->startrender(); do { batchedmodel &bm = b.batched.pop(); if(bm.attached>=0) minattached = min(minattached, bm.attached); renderbatchedmodel(b.m, bm); } while(b.batched.length() && b.batched.last().query==modelquery); b.m->endrender(); } endquery(modelquery); modelquery = NULL; modelattached.setsize(minattached); } VARP(maxmodelradiusdistance, 10, 200, 1000); void rendermodelquery(model *m, dynent *d, const vec ¢er, float radius) { if(fabs(camera1->o.x-center.x) < radius+1 && fabs(camera1->o.y-center.y) < radius+1 && fabs(camera1->o.z-center.z) < radius+1) { d->query = NULL; return; } d->query = newquery(d); if(!d->query) return; nocolorshader->set(); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDepthMask(GL_FALSE); startquery(d->query); int br = int(radius*2)+1; drawbb(ivec(int(center.x-radius), int(center.y-radius), int(center.z-radius)), ivec(br, br, br)); endquery(d->query); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, fading ? GL_FALSE : GL_TRUE); glDepthMask(GL_TRUE); } extern int oqfrags; void rendermodel(entitylight *light, const char *mdl, int anim, const vec &o, float yaw, float pitch, int flags, dynent *d, modelattach *a, int basetime, int basetime2, float trans) { if(shadowmapping && !(flags&(MDL_SHADOW|MDL_DYNSHADOW))) return; model *m = loadmodel(mdl); if(!m) return; vec center(0, 0, 0), bbradius(0, 0, 0); float radius = 0; bool shadow = !shadowmap && !glaring && (flags&(MDL_SHADOW|MDL_DYNSHADOW)) && showblobs, doOQ = flags&MDL_CULL_QUERY && hasOQ && oqfrags && oqdynent; if(flags&(MDL_CULL_VFC|MDL_CULL_DIST|MDL_CULL_OCCLUDED|MDL_CULL_QUERY|MDL_SHADOW|MDL_DYNSHADOW)) { m->boundbox(0/*frame*/, center, bbradius); // FIXME radius = bbradius.magnitude(); if(d && d->ragdoll) { radius = max(radius, d->ragdoll->radius); center = d->ragdoll->center; } else { center.rotate_around_z(yaw*RAD); center.add(o); } if(flags&MDL_CULL_DIST && center.dist(camera1->o)/radius>maxmodelradiusdistance) return; if(flags&MDL_CULL_VFC) { if(reflecting || refracting) { if(reflecting || refracting>0) { if(center.z+radius<=reflectz) return; } else { if(fogging && center.z+radius=reflectz) return; } if(center.dist(camera1->o)-radius>reflectdist) return; } if(isfoggedsphere(radius, center)) return; if(shadowmapping && !isshadowmapcaster(center, radius)) return; } if(shadowmapping) { if(d) { if(flags&MDL_CULL_OCCLUDED && d->occluded>=OCCLUDE_PARENT) return; if(doOQ && d->occluded+1>=OCCLUDE_BB && d->query && d->query->owner==d && checkquery(d->query)) return; } if(!addshadowmapcaster(center, radius, radius)) return; } else if(flags&MDL_CULL_OCCLUDED && modeloccluded(center, radius)) { if(!reflecting && !refracting && d) { d->occluded = OCCLUDE_PARENT; if(doOQ) rendermodelquery(m, d, center, radius); } return; } else if(doOQ && d && d->query && d->query->owner==d && checkquery(d->query)) { if(!reflecting && !refracting) { if(d->occludedoccluded++; rendermodelquery(m, d, center, radius); } return; } } if(flags&MDL_NORENDER) anim |= ANIM_NORENDER; else if(showboundingbox && !shadowmapping && !reflecting && !refracting && editmode) { if(d && showboundingbox==1) { render3dbox(d->o, d->eyeheight, d->aboveeye, d->radius); renderellipse(d->o, d->xradius, d->yradius, d->yaw); } else { vec center, radius; if(showboundingbox==1) m->collisionbox(0, center, radius); else m->boundbox(0, center, radius); rotatebb(center, radius, int(yaw)); center.add(o); render3dbox(center, radius.z, radius.z, radius.x, radius.y); } } vec lightcolor(1, 1, 1), lightdir(0, 0, 1); if(!shadowmapping) { vec pos = o; if(d) { if(!reflecting && !refracting) d->occluded = OCCLUDE_NOTHING; if(!light) light = &d->light; if(flags&MDL_LIGHT && light->millis!=lastmillis) { if(d->ragdoll) { pos = d->ragdoll->center; pos.z += radius/2; } else if(d->type < ENT_CAMERA) pos.z += 0.75f*(d->eyeheight + d->aboveeye); lightreaching(pos, light->color, light->dir, (flags&MDL_LIGHT_FAST)!=0); dynlightreaching(pos, light->color, light->dir, (flags&MDL_HUD)!=0); game::lighteffects(d, light->color, light->dir); light->millis = lastmillis; } } else if(flags&MDL_LIGHT) { if(!light) { lightreaching(pos, lightcolor, lightdir, (flags&MDL_LIGHT_FAST)!=0); dynlightreaching(pos, lightcolor, lightdir, (flags&MDL_HUD)!=0); } else if(light->millis!=lastmillis) { lightreaching(pos, light->color, light->dir, (flags&MDL_LIGHT_FAST)!=0); dynlightreaching(pos, light->color, light->dir, (flags&MDL_HUD)!=0); light->millis = lastmillis; } } if(light) { lightcolor = light->color; lightdir = light->dir; } if(flags&MDL_DYNLIGHT) dynlightreaching(pos, lightcolor, lightdir, (flags&MDL_HUD)!=0); } if(a) for(int i = 0; a[i].tag; i++) { if(a[i].name) a[i].m = loadmodel(a[i].name); //if(a[i].m && a[i].m->type()!=m->type()) a[i].m = NULL; } if(!d || reflecting || refracting || shadowmapping) doOQ = false; if(numbatches>=0) { modelbatch &mb = addbatchedmodel(m); batchedmodel &b = mb.batched.add(); b.query = modelquery; b.pos = o; b.color = lightcolor; b.dir = lightdir; b.anim = anim; b.yaw = yaw; b.pitch = pitch; b.basetime = basetime; b.basetime2 = basetime2; b.transparent = trans; b.flags = flags & ~(MDL_CULL_VFC | MDL_CULL_DIST | MDL_CULL_OCCLUDED); if(!shadow || reflecting || refracting>0) { b.flags &= ~(MDL_SHADOW|MDL_DYNSHADOW); if((flags&MDL_CULL_VFC) && refracting<0 && center.z-radius>=reflectz) b.flags |= MDL_CULL_VFC; } mb.flags |= b.flags; b.d = d; b.attached = a ? modelattached.length() : -1; if(a) for(int i = 0;; i++) { modelattached.add(a[i]); if(!a[i].tag) break; } if(doOQ) d->query = b.query = newquery(d); return; } if(shadow && !reflecting && refracting<=0) { renderblob(flags&MDL_DYNSHADOW ? BLOB_DYNAMIC : BLOB_STATIC, d && d->ragdoll ? center : o, d ? d->radius : max(bbradius.x, bbradius.y), trans); flushblobs(); if((flags&MDL_CULL_VFC) && refracting<0 && center.z-radius>=reflectz) return; } m->startrender(); if(shadowmapping) { anim |= ANIM_NOSKIN; if(renderpath!=R_FIXEDFUNCTION) setenvparamf("shadowintensity", SHPARAM_VERTEX, 1, trans); } else { if(flags&MDL_FULLBRIGHT) anim |= ANIM_FULLBRIGHT; if(flags&MDL_GHOST) anim |= ANIM_GHOST; } if(doOQ) { d->query = newquery(d); if(d->query) startquery(d->query); } m->render(anim, basetime, basetime2, o, yaw, pitch, d, a, lightcolor, lightdir, trans); if(doOQ && d->query) endquery(d->query); m->endrender(); } void abovemodel(vec &o, const char *mdl) { model *m = loadmodel(mdl); if(!m) return; o.z += m->above(0/*frame*/); } bool matchanim(const char *name, const char *pattern) { for(;; pattern++) { const char *s = name; char c; for(;; pattern++) { c = *pattern; if(!c || c=='|') break; else if(c=='*') { if(!*s || iscubespace(*s)) break; do s++; while(*s && !iscubespace(*s)); } else if(c!=*s) break; else s++; } if(!*s && (!c || c=='|')) return true; pattern = strchr(pattern, '|'); if(!pattern) break; } return false; } void findanims(const char *pattern, vector &anims) { loopi(sizeof(animnames)/sizeof(animnames[0])) if(matchanim(animnames[i], pattern)) anims.add(i); } ICOMMAND(findanims, "s", (char *name), { vector anims; findanims(name, anims); vector buf; string num; loopv(anims) { formatstring(num)("%d", anims[i]); if(i > 0) buf.add(' '); buf.put(num, strlen(num)); } buf.add('\0'); result(buf.getbuf()); }); void loadskin(const char *dir, const char *altdir, Texture *&skin, Texture *&masks) // model skin sharing { #define ifnoload(tex, path) if((tex = textureload(path, 0, true, false))==notexture) #define tryload(tex, prefix, cmd, name) \ ifnoload(tex, makerelpath(mdir, name ".jpg", prefix, cmd)) \ { \ ifnoload(tex, makerelpath(mdir, name ".png", prefix, cmd)) \ { \ ifnoload(tex, makerelpath(maltdir, name ".jpg", prefix, cmd)) \ { \ ifnoload(tex, makerelpath(maltdir, name ".png", prefix, cmd)) return; \ } \ } \ } defformatstring(mdir)("packages/models/%s", dir); defformatstring(maltdir)("packages/models/%s", altdir); masks = notexture; tryload(skin, NULL, NULL, "skin"); tryload(masks, "", NULL, "masks"); } // convenient function that covers the usual anims for players/monsters/npcs VAR(animoverride, -1, 0, NUMANIMS-1); VAR(testanims, 0, 0, 1); VAR(testpitch, -90, 0, 90); void renderclient(dynent *d, const char *mdlname, modelattach *attachments, int hold, int attack, int attackdelay, int lastaction, int lastpain, float fade, bool ragdoll) { int anim = hold ? hold : ANIM_IDLE|ANIM_LOOP; float yaw = testanims && d==player ? 0 : d->yaw+90, pitch = testpitch && d==player ? testpitch : d->pitch; vec o = d->feetpos(); int basetime = 0; if(animoverride) anim = (animoverride<0 ? ANIM_ALL : animoverride)|ANIM_LOOP; else if(d->state==CS_DEAD) { anim = ANIM_DYING|ANIM_NOPITCH; basetime = lastpain; if(ragdoll) { if(!d->ragdoll || d->ragdoll->millis < basetime) { DELETEP(d->ragdoll); anim |= ANIM_RAGDOLL; } } else if(lastmillis-basetime>1000) anim = ANIM_DEAD|ANIM_LOOP|ANIM_NOPITCH; } else if(d->state==CS_EDITING || d->state==CS_SPECTATOR) anim = ANIM_EDIT|ANIM_LOOP; else if(d->state==CS_LAGGED) anim = ANIM_LAG|ANIM_LOOP; else { if(lastmillis-lastpain < 300) { anim = ANIM_PAIN; basetime = lastpain; } else if(lastpain < lastaction && (attack < 0 || (d->type != ENT_AI && lastmillis-lastaction < attackdelay))) { anim = attack < 0 ? -attack : attack; basetime = lastaction; } if(d->inwater && d->physstate<=PHYS_FALL) anim |= (((game::allowmove(d) && (d->move || d->strafe)) || d->vel.z+d->falling.z>0 ? ANIM_SWIM : ANIM_SINK)|ANIM_LOOP)<timeinair>100) anim |= (ANIM_JUMP|ANIM_END)<move || d->strafe)) { if(d->move>0) anim |= (ANIM_FORWARD|ANIM_LOOP)<strafe) anim |= ((d->strafe>0 ? ANIM_LEFT : ANIM_RIGHT)|ANIM_LOOP)<move<0) anim |= (ANIM_BACKWARD|ANIM_LOOP)<>ANIM_SECONDARY)&ANIM_INDEX) anim >>= ANIM_SECONDARY; } if(d->ragdoll && (!ragdoll || (anim&ANIM_INDEX)!=ANIM_DYING)) DELETEP(d->ragdoll); if(!((anim>>ANIM_SECONDARY)&ANIM_INDEX)) anim |= (ANIM_IDLE|ANIM_LOOP)<type==ENT_PLAYER) flags |= MDL_FULLBRIGHT; else flags |= MDL_CULL_DIST; if(d->state==CS_LAGGED) fade = min(fade, 0.3f); else flags |= MDL_DYNSHADOW; if(modelpreviewing) flags &= ~(MDL_LIGHT | MDL_FULLBRIGHT | MDL_CULL_VFC | MDL_CULL_OCCLUDED | MDL_CULL_QUERY | MDL_CULL_DIST | MDL_DYNSHADOW); rendermodel(NULL, mdlname, anim, o, yaw, pitch, flags, d, attachments, basetime, 0, fade); } void setbbfrommodel(dynent *d, const char *mdl) { model *m = loadmodel(mdl); if(!m) return; vec center, radius; m->collisionbox(0, center, radius); if(d->type==ENT_INANIMATE && !m->ellipsecollide) { d->collidetype = COLLIDE_OBB; //d->collidetype = COLLIDE_AABB; //rotatebb(center, radius, int(d->yaw)); } d->xradius = radius.x + fabs(center.x); d->yradius = radius.y + fabs(center.y); d->radius = d->collidetype==COLLIDE_OBB ? sqrtf(d->xradius*d->xradius + d->yradius*d->yradius) : max(d->xradius, d->yradius); d->eyeheight = (center.z-radius.z) + radius.z*2*m->eyeheight; d->aboveeye = radius.z*2*(1.0f-m->eyeheight); } sauerbraten-0.0.20130203.dfsg/engine/ragdoll.h0000644000175000017500000003634312033123770020446 0ustar vincentvincentstruct ragdollskel { struct vert { vec pos; float radius, weight; }; struct tri { int vert[3]; bool shareverts(const tri &t) const { loopi(3) loopj(3) if(vert[i] == t.vert[j]) return true; return false; } }; struct distlimit { int vert[2]; float mindist, maxdist; }; struct rotlimit { int tri[2]; float maxangle; matrix3x3 middle; }; struct rotfriction { int tri[2]; matrix3x3 middle; }; struct joint { int bone, tri, vert[3]; float weight; matrix3x4 orient; }; struct reljoint { int bone, parent; }; bool loaded, animjoints; int eye; vector verts; vector tris; vector distlimits; vector rotlimits; vector rotfrictions; vector joints; vector reljoints; ragdollskel() : loaded(false), animjoints(false), eye(-1) {} void setupjoints() { loopv(verts) verts[i].weight = 0; loopv(joints) { joint &j = joints[i]; j.weight = 0; vec pos(0, 0, 0); loopk(3) if(j.vert[k]>=0) { pos.add(verts[j.vert[k]].pos); j.weight++; verts[j.vert[k]].weight++; } if(j.weight) j.weight = 1/j.weight; pos.mul(j.weight); tri &t = tris[j.tri]; matrix3x3 m; const vec &v1 = verts[t.vert[0]].pos, &v2 = verts[t.vert[1]].pos, &v3 = verts[t.vert[2]].pos; m.a = vec(v2).sub(v1).normalize(); m.c.cross(m.a, vec(v3).sub(v1)).normalize(); m.b.cross(m.c, m.a); j.orient = matrix3x4(m, m.transform(pos).neg()); } loopv(verts) if(verts[i].weight) verts[i].weight = 1/verts[i].weight; reljoints.shrink(0); } void setuprotfrictions() { rotfrictions.shrink(0); loopv(tris) for(int j = i+1; j < tris.length(); j++) if(tris[i].shareverts(tris[j])) { rotfriction &r = rotfrictions.add(); r.tri[0] = i; r.tri[1] = j; } } void setup() { setupjoints(); setuprotfrictions(); loaded = true; } void addreljoint(int bone, int parent) { reljoint &r = reljoints.add(); r.bone = bone; r.parent = parent; } }; struct ragdolldata { struct vert { vec oldpos, pos, newpos; float weight; bool collided, stuck; vert() : pos(0, 0, 0), newpos(0, 0, 0), weight(0), collided(false), stuck(true) {} }; ragdollskel *skel; int millis, collidemillis, collisions, floating, lastmove, unsticks; vec offset, center; float radius, timestep, scale; vert *verts; matrix3x3 *tris; matrix3x4 *animjoints, *reljoints; ragdolldata(ragdollskel *skel, float scale = 1) : skel(skel), millis(lastmillis), collidemillis(0), collisions(0), floating(0), lastmove(lastmillis), unsticks(INT_MAX), timestep(0), scale(scale), verts(new vert[skel->verts.length()]), tris(new matrix3x3[skel->tris.length()]), animjoints(!skel->animjoints || skel->joints.empty() ? NULL : new matrix3x4[skel->joints.length()]), reljoints(skel->reljoints.empty() ? NULL : new matrix3x4[skel->reljoints.length()]) { } ~ragdolldata() { delete[] verts; delete[] tris; if(animjoints) delete[] animjoints; if(reljoints) delete[] reljoints; } void calcanimjoint(int i, const matrix3x4 &anim) { if(!animjoints) return; ragdollskel::joint &j = skel->joints[i]; vec pos(0, 0, 0); loopk(3) if(j.vert[k]>=0) pos.add(verts[j.vert[k]].pos); pos.mul(j.weight); ragdollskel::tri &t = skel->tris[j.tri]; matrix3x3 m; const vec &v1 = verts[t.vert[0]].pos, &v2 = verts[t.vert[1]].pos, &v3 = verts[t.vert[2]].pos; m.a = vec(v2).sub(v1).normalize(); m.c.cross(m.a, vec(v3).sub(v1)).normalize(); m.b.cross(m.c, m.a); animjoints[i].mul(m, m.transform(pos).neg(), anim); } void calctris() { loopv(skel->tris) { ragdollskel::tri &t = skel->tris[i]; matrix3x3 &m = tris[i]; const vec &v1 = verts[t.vert[0]].pos, &v2 = verts[t.vert[1]].pos, &v3 = verts[t.vert[2]].pos; m.a = vec(v2).sub(v1).normalize(); m.c.cross(m.a, vec(v3).sub(v1)).normalize(); m.b.cross(m.c, m.a); } } void calcboundsphere() { center = vec(0, 0, 0); loopv(skel->verts) center.add(verts[i].pos); center.div(skel->verts.length()); radius = 0; loopv(skel->verts) radius = max(radius, verts[i].pos.dist(center)); } void init(dynent *d) { extern int ragdolltimestepmin; float ts = ragdolltimestepmin/1000.0f; loopv(skel->verts) (verts[i].oldpos = verts[i].pos).sub(vec(d->vel).add(d->falling).mul(ts)); timestep = ts; calctris(); calcboundsphere(); offset = d->o; offset.sub(skel->eye >= 0 ? verts[skel->eye].pos : center); offset.z += (d->eyeheight + d->aboveeye)/2; } void move(dynent *pl, float ts); void updatepos(); void constrain(); void constraindist(); void applyrotlimit(ragdollskel::tri &t1, ragdollskel::tri &t2, float angle, const vec &axis); void constrainrot(); void calcrotfriction(); void applyrotfriction(float ts); void tryunstick(float speed); static inline bool collidevert(const vec &pos, const vec &dir, float radius) { static struct vertent : physent { vertent() { type = ENT_BOUNCE; collidetype = COLLIDE_AABB; radius = xradius = yradius = eyeheight = aboveeye = 1; } } v; v.o = pos; if(v.radius != radius) v.radius = v.xradius = v.yradius = v.eyeheight = v.aboveeye = radius; return collide(&v, dir, 0, false); } }; /* seed particle position = avg(modelview * base2anim * spherepos) mapped transform = invert(curtri) * origtrig parented transform = parent{invert(curtri) * origtrig} * (invert(parent{base2anim}) * base2anim) */ void ragdolldata::constraindist() { float invscale = 1.0f/scale; loopv(skel->distlimits) { ragdollskel::distlimit &d = skel->distlimits[i]; vert &v1 = verts[d.vert[0]], &v2 = verts[d.vert[1]]; vec dir = vec(v2.pos).sub(v1.pos); float dist = dir.magnitude()*invscale, cdist; if(dist < d.mindist) cdist = d.mindist; else if(dist > d.maxdist) cdist = d.maxdist; else continue; if(dist > 1e-4f) dir.mul(cdist*0.5f/dist); else dir = vec(0, 0, cdist*0.5f/invscale); vec center = vec(v1.pos).add(v2.pos).mul(0.5f); v1.newpos.add(vec(center).sub(dir)); v1.weight++; v2.newpos.add(vec(center).add(dir)); v2.weight++; } } inline void ragdolldata::applyrotlimit(ragdollskel::tri &t1, ragdollskel::tri &t2, float angle, const vec &axis) { vert &v1a = verts[t1.vert[0]], &v1b = verts[t1.vert[1]], &v1c = verts[t1.vert[2]], &v2a = verts[t2.vert[0]], &v2b = verts[t2.vert[1]], &v2c = verts[t2.vert[2]]; vec m1 = vec(v1a.pos).add(v1b.pos).add(v1c.pos).div(3), m2 = vec(v2a.pos).add(v2b.pos).add(v2c.pos).div(3), q1a, q1b, q1c, q2a, q2b, q2c; float w1 = q1a.cross(axis, vec(v1a.pos).sub(m1)).magnitude() + q1b.cross(axis, vec(v1b.pos).sub(m1)).magnitude() + q1c.cross(axis, vec(v1c.pos).sub(m1)).magnitude(), w2 = q2a.cross(axis, vec(v2a.pos).sub(m2)).magnitude() + q2b.cross(axis, vec(v2b.pos).sub(m2)).magnitude() + q2c.cross(axis, vec(v2c.pos).sub(m2)).magnitude(); angle /= w1 + w2 + 1e-9f; float a1 = angle*w2, a2 = -angle*w1, s1 = sinf(a1), s2 = sinf(a2); vec c1 = vec(axis).mul(1 - cosf(a1)), c2 = vec(axis).mul(1 - cosf(a2)); v1a.newpos.add(vec().cross(c1, q1a).add(vec(q1a).mul(s1)).add(v1a.pos)); v1a.weight++; v1b.newpos.add(vec().cross(c1, q1b).add(vec(q1b).mul(s1)).add(v1b.pos)); v1b.weight++; v1c.newpos.add(vec().cross(c1, q1c).add(vec(q1c).mul(s1)).add(v1c.pos)); v1c.weight++; v2a.newpos.add(vec().cross(c2, q2a).add(vec(q2a).mul(s2)).add(v2a.pos)); v2a.weight++; v2b.newpos.add(vec().cross(c2, q2b).add(vec(q2b).mul(s2)).add(v2b.pos)); v2b.weight++; v2c.newpos.add(vec().cross(c2, q2c).add(vec(q2c).mul(s2)).add(v2c.pos)); v2c.weight++; } void ragdolldata::constrainrot() { loopv(skel->rotlimits) { ragdollskel::rotlimit &r = skel->rotlimits[i]; matrix3x3 rot; rot.transposemul(tris[r.tri[0]], r.middle); rot.mul(tris[r.tri[1]]); vec axis; float angle; if(!rot.calcangleaxis(angle, axis)) continue; angle = r.maxangle - fabs(angle); if(angle >= 0) continue; angle += 1e-3f; applyrotlimit(skel->tris[r.tri[0]], skel->tris[r.tri[1]], angle, axis); } } VAR(ragdolltimestepmin, 1, 5, 50); VAR(ragdolltimestepmax, 1, 10, 50); FVAR(ragdollrotfric, 0, 0.85f, 1); FVAR(ragdollrotfricstop, 0, 0.1f, 1); void ragdolldata::calcrotfriction() { loopv(skel->rotfrictions) { ragdollskel::rotfriction &r = skel->rotfrictions[i]; r.middle.multranspose(tris[r.tri[0]], tris[r.tri[1]]); } } void ragdolldata::applyrotfriction(float ts) { calctris(); float stopangle = 2*M_PI*ts*ragdollrotfricstop, rotfric = 1.0f - pow(ragdollrotfric, ts*1000.0f/ragdolltimestepmin); loopv(skel->rotfrictions) { ragdollskel::rotfriction &r = skel->rotfrictions[i]; matrix3x3 rot; rot.transposemul(tris[r.tri[0]], r.middle); rot.mul(tris[r.tri[1]]); vec axis; float angle; if(rot.calcangleaxis(angle, axis)) { angle *= -(fabs(angle) >= stopangle ? rotfric : 1.0f); applyrotlimit(skel->tris[r.tri[0]], skel->tris[r.tri[1]], angle, axis); } } loopv(skel->verts) { vert &v = verts[i]; if(v.weight) v.pos = v.newpos.div(v.weight); v.newpos = vec(0, 0, 0); v.weight = 0; } } void ragdolldata::tryunstick(float speed) { vec unstuck(0, 0, 0); int stuck = 0; loopv(skel->verts) { vert &v = verts[i]; if(v.stuck) { if(!collidevert(v.pos, vec(0, 0, 0), skel->verts[i].radius)) { stuck++; continue; } v.stuck = false; } unstuck.add(v.pos); } unsticks = 0; if(!stuck || stuck >= skel->verts.length()) return; unstuck.div(skel->verts.length() - stuck); loopv(skel->verts) { vert &v = verts[i]; if(v.stuck) { v.pos.add(vec(unstuck).sub(v.pos).rescale(speed)); unsticks++; } } } extern vec wall; void ragdolldata::updatepos() { loopv(skel->verts) { vert &v = verts[i]; if(v.weight) { v.newpos.div(v.weight); if(collidevert(v.newpos, vec(v.newpos).sub(v.pos), skel->verts[i].radius)) v.pos = v.newpos; else { vec dir = vec(v.newpos).sub(v.oldpos); if(dir.dot(wall) < 0) v.oldpos = vec(v.pos).sub(dir.reflect(wall)); v.collided = true; } } v.newpos = vec(0, 0, 0); v.weight = 0; } } VAR(ragdollconstrain, 1, 5, 100); void ragdolldata::constrain() { loopi(ragdollconstrain) { constraindist(); updatepos(); calctris(); constrainrot(); updatepos(); } } FVAR(ragdollbodyfric, 0, 0.95f, 1); FVAR(ragdollbodyfricscale, 0, 2, 10); FVAR(ragdollwaterfric, 0, 0.85f, 1); FVAR(ragdollgroundfric, 0, 0.8f, 1); FVAR(ragdollairfric, 0, 0.996f, 1); FVAR(ragdollunstick, 0, 10, 1e3f); VAR(ragdollexpireoffset, 0, 1500, 30000); VAR(ragdollwaterexpireoffset, 0, 3000, 30000); void ragdolldata::move(dynent *pl, float ts) { extern const float GRAVITY; if(collidemillis && lastmillis > collidemillis) return; int material = lookupmaterial(vec(center.x, center.y, center.z + radius/2)); bool water = isliquid(material&MATF_VOLUME); if(!pl->inwater && water) game::physicstrigger(pl, true, 0, -1, material&MATF_VOLUME); else if(pl->inwater && !water) { material = lookupmaterial(center); water = isliquid(material&MATF_VOLUME); if(!water) game::physicstrigger(pl, true, 0, 1, pl->inwater); } pl->inwater = water ? material&MATF_VOLUME : MAT_AIR; calcrotfriction(); float tsfric = timestep ? ts/timestep : 1, airfric = ragdollairfric + min((ragdollbodyfricscale*collisions)/skel->verts.length(), 1.0f)*(ragdollbodyfric - ragdollairfric); collisions = 0; loopv(skel->verts) { vert &v = verts[i]; vec dpos = vec(v.pos).sub(v.oldpos); dpos.z -= GRAVITY*ts*ts; if(water) dpos.z += 0.25f*sinf(detrnd(size_t(this)+i, 360)*RAD + lastmillis/10000.0f*M_PI)*ts; dpos.mul(pow((water ? ragdollwaterfric : 1.0f) * (v.collided ? ragdollgroundfric : airfric), ts*1000.0f/ragdolltimestepmin)*tsfric); v.oldpos = v.pos; v.pos.add(dpos); } applyrotfriction(ts); loopv(skel->verts) { vert &v = verts[i]; if(v.pos.z < 0) { v.pos.z = 0; v.oldpos = v.pos; collisions++; } vec dir = vec(v.pos).sub(v.oldpos); v.collided = !collidevert(v.pos, dir, skel->verts[i].radius); if(v.collided) { v.pos = v.oldpos; v.oldpos.sub(dir.reflect(wall)); collisions++; } } if(unsticks && ragdollunstick) tryunstick(ts*ragdollunstick); timestep = ts; if(collisions) { floating = 0; if(!collidemillis) collidemillis = lastmillis + (water ? ragdollwaterexpireoffset : ragdollexpireoffset); } else if(++floating > 1 && lastmillis < collidemillis) collidemillis = 0; constrain(); calctris(); calcboundsphere(); } FVAR(ragdolleyesmooth, 0, 0.5f, 1); VAR(ragdolleyesmoothmillis, 1, 250, 10000); void moveragdoll(dynent *d) { if(!curtime || !d->ragdoll) return; if(!d->ragdoll->collidemillis || lastmillis < d->ragdoll->collidemillis) { int lastmove = d->ragdoll->lastmove; while(d->ragdoll->lastmove + (lastmove == d->ragdoll->lastmove ? ragdolltimestepmin : ragdolltimestepmax) <= lastmillis) { int timestep = min(ragdolltimestepmax, lastmillis - d->ragdoll->lastmove); d->ragdoll->move(d, timestep/1000.0f); d->ragdoll->lastmove += timestep; } } vec eye = d->ragdoll->skel->eye >= 0 ? d->ragdoll->verts[d->ragdoll->skel->eye].pos : d->ragdoll->center; eye.add(d->ragdoll->offset); float k = pow(ragdolleyesmooth, float(curtime)/ragdolleyesmoothmillis); d->o.mul(k).add(eye.mul(1-k)); } void cleanragdoll(dynent *d) { DELETEP(d->ragdoll); } sauerbraten-0.0.20130203.dfsg/engine/console.cpp0000644000175000017500000006061712072672414021027 0ustar vincentvincent// console.cpp: the console buffer, its display, and command line control #include "engine.h" struct cline { char *line; int type, outtime; }; vector conlines; int commandmillis = -1; string commandbuf; char *commandaction = NULL, *commandprompt = NULL; enum { CF_COMPLETE = 1<<0, CF_EXECUTE = 1<<1 }; int commandflags = 0, commandpos = -1; VARFP(maxcon, 10, 200, 1000, { while(conlines.length() > maxcon) delete[] conlines.pop().line; }); #define CONSTRLEN 512 void conline(int type, const char *sf) // add a line to the console buffer { cline cl; cl.line = conlines.length()>maxcon ? conlines.pop().line : newstring("", CONSTRLEN-1); // constrain the buffer size cl.type = type; cl.outtime = totalmillis; // for how long to keep line on screen conlines.insert(0, cl); copystring(cl.line, sf, CONSTRLEN); } void conoutfv(int type, const char *fmt, va_list args) { static char buf[CONSTRLEN]; vformatstring(buf, fmt, args, sizeof(buf)); conline(type, buf); filtertext(buf, buf); logoutf("%s", buf); } void conoutf(const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(CON_INFO, fmt, args); va_end(args); } void conoutf(int type, const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(type, fmt, args); va_end(args); } VAR(fullconsole, 0, 0, 1); ICOMMAND(toggleconsole, "", (), { fullconsole ^= 1; }); int rendercommand(int x, int y, int w) { if(commandmillis < 0) return 0; defformatstring(s)("%s %s", commandprompt ? commandprompt : ">", commandbuf); int width, height; text_bounds(s, width, height, w); y -= height; draw_text(s, x, y, 0xFF, 0xFF, 0xFF, 0xFF, (commandpos>=0) ? (commandpos+1+(commandprompt?strlen(commandprompt):1)) : strlen(s), w); return height; } VARP(consize, 0, 5, 100); VARP(miniconsize, 0, 5, 100); VARP(miniconwidth, 0, 40, 100); VARP(confade, 0, 30, 60); VARP(miniconfade, 0, 30, 60); VARP(fullconsize, 0, 75, 100); HVARP(confilter, 0, 0x7FFFFFF, 0x7FFFFFF); HVARP(fullconfilter, 0, 0x7FFFFFF, 0x7FFFFFF); HVARP(miniconfilter, 0, 0, 0x7FFFFFF); int conskip = 0, miniconskip = 0; void setconskip(int &skip, int filter, int n) { int offset = abs(n), dir = n < 0 ? -1 : 1; skip = clamp(skip, 0, conlines.length()-1); while(offset) { skip += dir; if(!conlines.inrange(skip)) { skip = clamp(skip, 0, conlines.length()-1); return; } if(conlines[skip].type&filter) --offset; } } ICOMMAND(conskip, "i", (int *n), setconskip(conskip, fullconsole ? fullconfilter : confilter, *n)); ICOMMAND(miniconskip, "i", (int *n), setconskip(miniconskip, miniconfilter, *n)); ICOMMAND(clearconsole, "", (), { while(conlines.length()) delete[] conlines.pop().line; }); int drawconlines(int conskip, int confade, int conwidth, int conheight, int conoff, int filter, int y = 0, int dir = 1) { int numl = conlines.length(), offset = min(conskip, numl); if(confade) { if(!conskip) { numl = 0; loopvrev(conlines) if(totalmillis-conlines[i].outtime < confade*1000) { numl = i+1; break; } } else offset--; } int totalheight = 0; loopi(numl) //determine visible height { // shuffle backwards to fill if necessary int idx = offset+i < numl ? offset+i : --offset; if(!(conlines[idx].type&filter)) continue; char *line = conlines[idx].line; int width, height; text_bounds(line, width, height, conwidth); if(totalheight + height > conheight) { numl = i; if(offset == idx) ++offset; break; } totalheight += height; } if(dir > 0) y = conoff; loopi(numl) { int idx = offset + (dir > 0 ? numl-i-1 : i); if(!(conlines[idx].type&filter)) continue; char *line = conlines[idx].line; int width, height; text_bounds(line, width, height, conwidth); if(dir <= 0) y -= height; draw_text(line, conoff, y, 0xFF, 0xFF, 0xFF, 0xFF, -1, conwidth); if(dir > 0) y += height; } return y+conoff; } int renderconsole(int w, int h, int abovehud) // render buffer taking into account time & scrolling { int conpad = fullconsole ? 0 : FONTH/4, conoff = fullconsole ? FONTH : FONTH/3, conheight = min(fullconsole ? ((h*fullconsize/100)/FONTH)*FONTH : FONTH*consize, h - 2*(conpad + conoff)), conwidth = w - 2*(conpad + conoff) - (fullconsole ? 0 : game::clipconsole(w, h)); extern void consolebox(int x1, int y1, int x2, int y2); if(fullconsole) consolebox(conpad, conpad, conwidth+conpad+2*conoff, conheight+conpad+2*conoff); int y = drawconlines(conskip, fullconsole ? 0 : confade, conwidth, conheight, conpad+conoff, fullconsole ? fullconfilter : confilter); if(!fullconsole && (miniconsize && miniconwidth)) drawconlines(miniconskip, miniconfade, (miniconwidth*(w - 2*(conpad + conoff)))/100, min(FONTH*miniconsize, abovehud - y), conpad+conoff, miniconfilter, abovehud, -1); return fullconsole ? conheight + 2*(conpad + conoff) : y; } // keymap is defined externally in keymap.cfg struct keym { enum { ACTION_DEFAULT = 0, ACTION_SPECTATOR, ACTION_EDITING, NUMACTIONS }; int code; char *name; char *actions[NUMACTIONS]; bool pressed; keym() : code(-1), name(NULL), pressed(false) { loopi(NUMACTIONS) actions[i] = newstring(""); } ~keym() { DELETEA(name); loopi(NUMACTIONS) DELETEA(actions[i]); } }; hashtable keyms(128); void keymap(int *code, char *key) { if(identflags&IDF_OVERRIDDEN) { conoutf(CON_ERROR, "cannot override keymap %d", *code); return; } keym &km = keyms[*code]; km.code = *code; DELETEA(km.name); km.name = newstring(key); } COMMAND(keymap, "is"); keym *keypressed = NULL; char *keyaction = NULL; const char *getkeyname(int code) { keym *km = keyms.access(code); return km ? km->name : NULL; } void searchbinds(char *action, int type) { vector names; enumerate(keyms, keym, km, { if(!strcmp(km.actions[type], action)) { if(names.length()) names.add(' '); names.put(km.name, strlen(km.name)); } }); names.add('\0'); result(names.getbuf()); } keym *findbind(char *key) { enumerate(keyms, keym, km, { if(!strcasecmp(km.name, key)) return &km; }); return NULL; } void getbind(char *key, int type) { keym *km = findbind(key); result(km ? km->actions[type] : ""); } void bindkey(char *key, char *action, int state, const char *cmd) { if(identflags&IDF_OVERRIDDEN) { conoutf(CON_ERROR, "cannot override %s \"%s\"", cmd, key); return; } keym *km = findbind(key); if(!km) { conoutf(CON_ERROR, "unknown key \"%s\"", key); return; } char *&binding = km->actions[state]; if(!keypressed || keyaction!=binding) delete[] binding; // trim white-space to make searchbinds more reliable while(iscubespace(*action)) action++; int len = strlen(action); while(len>0 && iscubespace(action[len-1])) len--; binding = newstring(action, len); } ICOMMAND(bind, "ss", (char *key, char *action), bindkey(key, action, keym::ACTION_DEFAULT, "bind")); ICOMMAND(specbind, "ss", (char *key, char *action), bindkey(key, action, keym::ACTION_SPECTATOR, "specbind")); ICOMMAND(editbind, "ss", (char *key, char *action), bindkey(key, action, keym::ACTION_EDITING, "editbind")); ICOMMAND(getbind, "s", (char *key), getbind(key, keym::ACTION_DEFAULT)); ICOMMAND(getspecbind, "s", (char *key), getbind(key, keym::ACTION_SPECTATOR)); ICOMMAND(geteditbind, "s", (char *key), getbind(key, keym::ACTION_EDITING)); ICOMMAND(searchbinds, "s", (char *action), searchbinds(action, keym::ACTION_DEFAULT)); ICOMMAND(searchspecbinds, "s", (char *action), searchbinds(action, keym::ACTION_SPECTATOR)); ICOMMAND(searcheditbinds, "s", (char *action), searchbinds(action, keym::ACTION_EDITING)); void inputcommand(char *init, char *action = NULL, char *prompt = NULL, char *flags = NULL) // turns input to the command line on or off { commandmillis = init ? totalmillis : -1; SDL_EnableUNICODE(commandmillis >= 0 ? 1 : 0); if(!editmode) keyrepeat(commandmillis >= 0); copystring(commandbuf, init ? init : ""); DELETEA(commandaction); DELETEA(commandprompt); commandpos = -1; if(action && action[0]) commandaction = newstring(action); if(prompt && prompt[0]) commandprompt = newstring(prompt); commandflags = 0; if(flags) while(*flags) switch(*flags++) { case 'c': commandflags |= CF_COMPLETE; break; case 'x': commandflags |= CF_EXECUTE; break; case 's': commandflags |= CF_COMPLETE|CF_EXECUTE; break; } else if(init) commandflags |= CF_COMPLETE|CF_EXECUTE; } ICOMMAND(saycommand, "C", (char *init), inputcommand(init)); COMMAND(inputcommand, "ssss"); #if !defined(WIN32) && !defined(__APPLE__) #include #include #endif void pasteconsole() { #ifdef WIN32 UINT fmt = CF_UNICODETEXT; if(!IsClipboardFormatAvailable(fmt)) { fmt = CF_TEXT; if(!IsClipboardFormatAvailable(fmt)) return; } if(!OpenClipboard(NULL)) return; HANDLE h = GetClipboardData(fmt); size_t commandlen = strlen(commandbuf); int cblen = int(GlobalSize(h)), decoded = 0; ushort *cb = (ushort *)GlobalLock(h); switch(fmt) { case CF_UNICODETEXT: decoded = min(int(sizeof(commandbuf)-1-commandlen), cblen/2); loopi(decoded) commandbuf[commandlen++] = uni2cube(cb[i]); break; case CF_TEXT: decoded = min(int(sizeof(commandbuf)-1-commandlen), cblen); memcpy(&commandbuf[commandlen], cb, decoded); break; } commandbuf[commandlen + decoded] = '\0'; GlobalUnlock(cb); CloseClipboard(); #elif defined(__APPLE__) extern char *mac_pasteconsole(int *cblen); int cblen = 0; uchar *cb = (uchar *)mac_pasteconsole(&cblen); if(!cb) return; size_t commandlen = strlen(commandbuf); int decoded = decodeutf8((uchar *)&commandbuf[commandlen], int(sizeof(commandbuf)-1-commandlen), cb, cblen); commandbuf[commandlen + decoded] = '\0'; free(cb); #else SDL_SysWMinfo wminfo; SDL_VERSION(&wminfo.version); wminfo.subsystem = SDL_SYSWM_X11; if(!SDL_GetWMInfo(&wminfo)) return; int cbsize; uchar *cb = (uchar *)XFetchBytes(wminfo.info.x11.display, &cbsize); if(!cb || !cbsize) return; size_t commandlen = strlen(commandbuf); for(uchar *cbline = cb, *cbend; commandlen + 1 < sizeof(commandbuf) && cbline < &cb[cbsize]; cbline = cbend + 1) { cbend = (uchar *)memchr(cbline, '\0', &cb[cbsize] - cbline); if(!cbend) cbend = &cb[cbsize]; int cblen = int(cbend-cbline), commandmax = int(sizeof(commandbuf)-1-commandlen); loopi(cblen) if((cbline[i]&0xC0) == 0x80) { commandlen += decodeutf8((uchar *)&commandbuf[commandlen], commandmax, cbline, cblen); goto nextline; } cblen = min(cblen, commandmax); loopi(cblen) commandbuf[commandlen++] = uni2cube(*cbline++); nextline: commandbuf[commandlen] = '\n'; if(commandlen + 1 < sizeof(commandbuf) && cbend < &cb[cbsize]) ++commandlen; commandbuf[commandlen] = '\0'; } XFree(cb); #endif } struct hline { char *buf, *action, *prompt; int flags; hline() : buf(NULL), action(NULL), prompt(NULL), flags(0) {} ~hline() { DELETEA(buf); DELETEA(action); DELETEA(prompt); } void restore() { copystring(commandbuf, buf); if(commandpos >= (int)strlen(commandbuf)) commandpos = -1; DELETEA(commandaction); DELETEA(commandprompt); if(action) commandaction = newstring(action); if(prompt) commandprompt = newstring(prompt); commandflags = flags; } bool shouldsave() { return strcmp(commandbuf, buf) || (commandaction ? !action || strcmp(commandaction, action) : action!=NULL) || (commandprompt ? !prompt || strcmp(commandprompt, prompt) : prompt!=NULL) || commandflags != flags; } void save() { buf = newstring(commandbuf); if(commandaction) action = newstring(commandaction); if(commandprompt) prompt = newstring(commandprompt); flags = commandflags; } void run() { if(flags&CF_EXECUTE && buf[0]=='/') execute(buf+1); else if(action) { alias("commandbuf", buf); execute(action); } else game::toserver(buf); } }; vector history; int histpos = 0; VARP(maxhistory, 0, 1000, 10000); void history_(int *n) { static bool inhistory = false; if(!inhistory && history.inrange(*n)) { inhistory = true; history[history.length()-*n-1]->run(); inhistory = false; } } COMMANDN(history, history_, "i"); struct releaseaction { keym *key; char *action; }; vector releaseactions; const char *addreleaseaction(char *s) { if(!keypressed) return NULL; releaseaction &ra = releaseactions.add(); ra.key = keypressed; ra.action = s; return keypressed->name; } void onrelease(const char *s) { addreleaseaction(newstring(s)); } COMMAND(onrelease, "s"); void execbind(keym &k, bool isdown) { loopv(releaseactions) { releaseaction &ra = releaseactions[i]; if(ra.key==&k) { if(!isdown) execute(ra.action); delete[] ra.action; releaseactions.remove(i--); } } if(isdown) { int state = keym::ACTION_DEFAULT; if(!mainmenu) { if(editmode) state = keym::ACTION_EDITING; else if(player->state==CS_SPECTATOR) state = keym::ACTION_SPECTATOR; } char *&action = k.actions[state][0] ? k.actions[state] : k.actions[keym::ACTION_DEFAULT]; keyaction = action; keypressed = &k; execute(keyaction); keypressed = NULL; if(keyaction!=action) delete[] keyaction; } k.pressed = isdown; } void consolekey(int code, bool isdown, int cooked) { #ifdef __APPLE__ #define MOD_KEYS (KMOD_LMETA|KMOD_RMETA) #else #define MOD_KEYS (KMOD_LCTRL|KMOD_RCTRL) #endif if(isdown) { switch(code) { case SDLK_RETURN: case SDLK_KP_ENTER: break; case SDLK_HOME: if(strlen(commandbuf)) commandpos = 0; break; case SDLK_END: commandpos = -1; break; case SDLK_DELETE: { int len = (int)strlen(commandbuf); if(commandpos<0) break; memmove(&commandbuf[commandpos], &commandbuf[commandpos+1], len - commandpos); resetcomplete(); if(commandpos>=len-1) commandpos = -1; break; } case SDLK_BACKSPACE: { int len = (int)strlen(commandbuf), i = commandpos>=0 ? commandpos : len; if(i<1) break; memmove(&commandbuf[i-1], &commandbuf[i], len - i + 1); resetcomplete(); if(commandpos>0) commandpos--; else if(!commandpos && len<=1) commandpos = -1; break; } case SDLK_LEFT: if(commandpos>0) commandpos--; else if(commandpos<0) commandpos = (int)strlen(commandbuf)-1; break; case SDLK_RIGHT: if(commandpos>=0 && ++commandpos>=(int)strlen(commandbuf)) commandpos = -1; break; case SDLK_UP: if(histpos > history.length()) histpos = history.length(); if(histpos > 0) history[--histpos]->restore(); break; case SDLK_DOWN: if(histpos + 1 < history.length()) history[++histpos]->restore(); break; case SDLK_TAB: if(commandflags&CF_COMPLETE) { complete(commandbuf, commandflags&CF_EXECUTE ? "/" : NULL); if(commandpos>=0 && commandpos>=(int)strlen(commandbuf)) commandpos = -1; } break; case SDLK_v: if(SDL_GetModState()&MOD_KEYS) { pasteconsole(); return; } // fall through default: resetcomplete(); if(cooked) { size_t len = (int)strlen(commandbuf); if(len+1shouldsave()) { if(maxhistory && history.length() >= maxhistory) { loopi(history.length()-maxhistory+1) delete history[i]; history.remove(0, history.length()-maxhistory+1); } history.add(h = new hline)->save(); } else h = history.last(); } histpos = history.length(); inputcommand(NULL); if(h) h->run(); } else if(code==SDLK_ESCAPE) { histpos = history.length(); inputcommand(NULL); } } } extern bool menukey(int code, bool isdown, int cooked); void keypress(int code, bool isdown, int cooked) { keym *haskey = keyms.access(code); if(haskey && haskey->pressed) execbind(*haskey, isdown); // allow pressed keys to release else if(!menukey(code, isdown, cooked)) // 3D GUI mouse button intercept { if(commandmillis >= 0) consolekey(code, isdown, cooked); else if(haskey) execbind(*haskey, isdown); } } void clear_console() { keyms.clear(); } static inline bool sortbinds(keym *x, keym *y) { return strcmp(x->name, y->name) < 0; } void writebinds(stream *f) { static const char *cmds[3] = { "bind", "specbind", "editbind" }; vector binds; enumerate(keyms, keym, km, binds.add(&km)); binds.sort(sortbinds); loopj(3) { loopv(binds) { keym &km = *binds[i]; if(*km.actions[j]) { if(validateblock(km.actions[j])) f->printf("%s %s [%s]\n", cmds[j], escapestring(km.name), km.actions[j]); else f->printf("%s %s %s\n", cmds[j], escapestring(km.name), escapestring(km.actions[j])); } } } } // tab-completion of all idents and base maps enum { FILES_DIR = 0, FILES_LIST }; struct fileskey { int type; const char *dir, *ext; fileskey() {} fileskey(int type, const char *dir, const char *ext) : type(type), dir(dir), ext(ext) {} }; struct filesval { int type; char *dir, *ext; vector files; int millis; filesval(int type, const char *dir, const char *ext) : type(type), dir(newstring(dir)), ext(ext && ext[0] ? newstring(ext) : NULL), millis(-1) {} ~filesval() { DELETEA(dir); DELETEA(ext); files.deletearrays(); } static bool comparefiles(const char *x, const char *y) { return strcmp(x, y) < 0; } void update() { if(type!=FILES_DIR || millis >= commandmillis) return; files.deletearrays(); listfiles(dir, ext, files); files.sort(comparefiles); loopv(files) if(i && !strcmp(files[i], files[i-1])) delete[] files.remove(i--); millis = totalmillis; } }; static inline bool htcmp(const fileskey &x, const fileskey &y) { return x.type==y.type && !strcmp(x.dir, y.dir) && (x.ext == y.ext || (x.ext && y.ext && !strcmp(x.ext, y.ext))); } static inline uint hthash(const fileskey &k) { return hthash(k.dir); } static hashtable completefiles; static hashtable completions; int completesize = 0; string lastcomplete; void resetcomplete() { completesize = 0; } void addcomplete(char *command, int type, char *dir, char *ext) { if(identflags&IDF_OVERRIDDEN) { conoutf(CON_ERROR, "cannot override complete %s", command); return; } if(!dir[0]) { filesval **hasfiles = completions.access(command); if(hasfiles) *hasfiles = NULL; return; } if(type==FILES_DIR) { int dirlen = (int)strlen(dir); while(dirlen > 0 && (dir[dirlen-1] == '/' || dir[dirlen-1] == '\\')) dir[--dirlen] = '\0'; if(ext) { if(strchr(ext, '*')) ext[0] = '\0'; if(!ext[0]) ext = NULL; } } fileskey key(type, dir, ext); filesval **val = completefiles.access(key); if(!val) { filesval *f = new filesval(type, dir, ext); if(type==FILES_LIST) explodelist(dir, f->files); val = &completefiles[fileskey(type, f->dir, f->ext)]; *val = f; } filesval **hasfiles = completions.access(command); if(hasfiles) *hasfiles = *val; else completions[newstring(command)] = *val; } void addfilecomplete(char *command, char *dir, char *ext) { addcomplete(command, FILES_DIR, dir, ext); } void addlistcomplete(char *command, char *list) { addcomplete(command, FILES_LIST, list, NULL); } COMMANDN(complete, addfilecomplete, "sss"); COMMANDN(listcomplete, addlistcomplete, "ss"); void complete(char *s, const char *cmdprefix) { int cmdlen = 0; if(cmdprefix) { cmdlen = strlen(cmdprefix); if(strncmp(s, cmdprefix, cmdlen)) { defformatstring(cmd)("%s%s", cmdprefix, s); copystring(s, cmd); } } if(!s[cmdlen]) return; if(!completesize) { completesize = (int)strlen(&s[cmdlen]); lastcomplete[0] = '\0'; } filesval *f = NULL; if(completesize) { char *end = strchr(&s[cmdlen], ' '); if(end) { string command; copystring(command, &s[cmdlen], min(size_t(end-&s[cmdlen]+1), sizeof(command))); filesval **hasfiles = completions.access(command); if(hasfiles) f = *hasfiles; } } const char *nextcomplete = NULL; string prefix; if(f) // complete using filenames { int commandsize = strchr(&s[cmdlen], ' ')+1-s; copystring(prefix, s, min(size_t(commandsize+1), sizeof(prefix))); f->update(); loopv(f->files) { if(strncmp(f->files[i], &s[commandsize], completesize+cmdlen-commandsize)==0 && strcmp(f->files[i], lastcomplete) > 0 && (!nextcomplete || strcmp(f->files[i], nextcomplete) < 0)) nextcomplete = f->files[i]; } } else // complete using command names { if(cmdprefix) copystring(prefix, cmdprefix); else prefix[0] = '\0'; enumerate(idents, ident, id, if(strncmp(id.name, &s[cmdlen], completesize)==0 && strcmp(id.name, lastcomplete) > 0 && (!nextcomplete || strcmp(id.name, nextcomplete) < 0)) nextcomplete = id.name; ); } if(nextcomplete) { formatstring(s)("%s%s", prefix, nextcomplete); copystring(lastcomplete, nextcomplete); } else lastcomplete[0] = '\0'; } static inline bool sortcompletions(const char *x, const char *y) { return strcmp(x, y) < 0; } void writecompletions(stream *f) { vector cmds; enumeratekt(completions, char *, k, filesval *, v, { if(v) cmds.add(k); }); cmds.sort(sortcompletions); loopv(cmds) { char *k = cmds[i]; filesval *v = completions[k]; if(v->type==FILES_LIST) { if(validateblock(v->dir)) f->printf("listcomplete %s [%s]\n", escapeid(k), v->dir); else f->printf("listcomplete %s %s\n", escapeid(k), escapestring(v->dir)); } else f->printf("complete %s %s %s\n", escapeid(k), escapestring(v->dir), escapestring(v->ext ? v->ext : "*")); } } sauerbraten-0.0.20130203.dfsg/engine/water.cpp0000644000175000017500000013335212065160320020472 0ustar vincentvincent#include "engine.h" VARFP(waterreflect, 0, 1, 1, { cleanreflections(); preloadwatershaders(); }); VARFP(waterrefract, 0, 1, 1, { cleanreflections(); preloadwatershaders(); }); VARFP(waterenvmap, 0, 1, 1, { cleanreflections(); preloadwatershaders(); }); VARFP(waterfallrefract, 0, 0, 1, { cleanreflections(); preloadwatershaders(); }); /* vertex water */ VARP(watersubdiv, 0, 2, 3); VARP(waterlod, 0, 1, 3); static int wx1, wy1, wx2, wy2, wsize; static float whscale, whoffset; static uchar wcol[4]; #define VERTW(vertw, defbody, body) \ static inline void def##vertw() \ { \ varray::defattrib(varray::ATTRIB_VERTEX, 3, GL_FLOAT); \ defbody; \ } \ static inline void vertw(float v1, float v2, float v3) \ { \ float angle = float((v1-wx1)*(v2-wy1))*float((v1-wx2)*(v2-wy2))*whscale+whoffset; \ float s = angle - int(angle) - 0.5f; \ s *= 8 - fabs(s)*16; \ float h = WATER_AMPLITUDE*s-WATER_OFFSET; \ varray::attrib(v1, v2, v3+h); \ body; \ } #define VERTWN(vertw, defbody, body) \ static inline void def##vertw() \ { \ varray::defattrib(varray::ATTRIB_VERTEX, 3, GL_FLOAT); \ defbody; \ } \ static inline void vertw(float v1, float v2, float v3) \ { \ float h = -WATER_OFFSET; \ varray::attrib(v1, v2, v3+h); \ body; \ } #define VERTWT(vertwt, defbody, body) \ VERTW(vertwt, defbody, { \ float v = angle - int(angle+0.25) - 0.25; \ v *= 8 - fabs(v)*16; \ float duv = 0.5f*v; \ body; \ }) VERTW(vertwt, { varray::defattrib(varray::ATTRIB_TEXCOORD0, 2, GL_FLOAT); }, { varray::attrib(v1/8.0f, v2/8.0f); }) VERTWN(vertwtn, { varray::defattrib(varray::ATTRIB_TEXCOORD0, 2, GL_FLOAT); }, { varray::attrib(v1/8.0f, v2/8.0f); }) VERTW(vertwc, { varray::defattrib(varray::ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE); }, { varray::attrib(wcol[0], wcol[1], wcol[2], clamp(int(wcol[3] + fabs(s)*0x18), 0, 255)); }) VERTWN(vertwcn, { varray::defattrib(varray::ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE); }, { varray::attribv<4>(wcol); }) VERTWT(vertwtc, { varray::defattrib(varray::ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); }, { varray::attrib(wcol[0], wcol[1], wcol[2], int(0x33 + fabs(s)*0x18)); varray::attrib(v1+duv, v2+duv, v3+h); }) VERTWN(vertwtcn, { glColor4ub(wcol[0], wcol[1], wcol[2], 0x33); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); }, { varray::attrib(v1, v2, v3+h); }) VERTWT(vertwmtc, { varray::defattrib(varray::ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD1, 3, GL_FLOAT); }, { varray::attrib(wcol[0], wcol[1], wcol[2], int(0x33 + fabs(s)*0x18)); varray::attrib(v1-duv, v2+duv, v3+h); varray::attrib(v1+duv, v2+duv, v3+h); }) VERTWN(vertwmtcn, { glColor4ub(wcol[0], wcol[1], wcol[2], 0x33); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD1, 3, GL_FLOAT); }, { varray::attrib(v1, v2, v3+h); varray::attrib(v1, v2, v3+h); }) VERTWT(vertwetc, { varray::defattrib(varray::ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); }, { varray::attrib(wcol[0], wcol[1], wcol[2], int(0x33 + fabs(s)*0x18)); varray::attrib(v1+duv-camera1->o.x, v2+duv-camera1->o.y, camera1->o.z-(v3+h)); }) VERTWN(vertwetcn, { glColor4ub(wcol[0], wcol[1], wcol[2], 0x33); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); }, { varray::attrib(v1-camera1->o.x, v2-camera1->o.y, camera1->o.z-(v3+h)); }) VERTWT(vertwemtc, { varray::defattrib(varray::ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD1, 3, GL_FLOAT); }, { varray::attrib(wcol[0], wcol[1], wcol[2], int(0x33 + fabs(s)*0x18)); varray::attrib(v1-duv, v2+duv, v3+h); varray::attrib(v1+duv-camera1->o.x, v2+duv-camera1->o.y, camera1->o.z-(v3+h)); }) VERTWN(vertwemtcn, { glColor4ub(wcol[0], wcol[1], wcol[2], 0x33); varray::defattrib(varray::ATTRIB_TEXCOORD0, 3, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD1, 3, GL_FLOAT); }, { varray::attrib(v1, v2, v3+h); varray::attrib(v1-camera1->o.x, v2-camera1->o.y, camera1->o.z-(v3+h)); }) static float lavaxk = 1.0f, lavayk = 1.0f, lavascroll = 0.0f; VERTW(vertl, { varray::defattrib(varray::ATTRIB_TEXCOORD0, 2, GL_FLOAT); }, { varray::attrib(lavaxk*(v1+lavascroll), lavayk*(v2+lavascroll)); }) VERTWN(vertln, { varray::defattrib(varray::ATTRIB_TEXCOORD0, 2, GL_FLOAT); }, { varray::attrib(lavaxk*(v1+lavascroll), lavayk*(v2+lavascroll)); }) #define renderwaterstrips(vertw, z) { \ def##vertw(); \ for(int x = wx1; xo.z < z-WATER_OFFSET; if(nowater || minimapping) { renderwaterstrips(vertwc, z); } else if(waterrefract) { if(waterreflect && !below) { renderwaterstrips(vertwmtc, z); } else if(waterenvmap && hasCM && !below) { renderwaterstrips(vertwemtc, z); } else { renderwaterstrips(vertwtc, z); } } else if(waterreflect && !below) { renderwaterstrips(vertwtc, z); } else if(waterenvmap && hasCM && !below) { renderwaterstrips(vertwetc, z); } else { renderwaterstrips(vertwc, z); } } break; } case MAT_LAVA: { whoffset = fmod(float(lastmillis/2000.0f/(2*M_PI)), 1.0f); renderwaterstrips(vertl, z); break; } } } uint calcwatersubdiv(int x, int y, int z, uint size) { float dist; if(camera1->o.x >= x && camera1->o.x < x + size && camera1->o.y >= y && camera1->o.y < y + size) dist = fabs(camera1->o.z - float(z)); else { vec t(x + size/2, y + size/2, z + size/2); dist = t.dist(camera1->o) - size*1.42f/2; } uint subdiv = watersubdiv + int(dist) / (32 << waterlod); if(subdiv >= 8*sizeof(subdiv)) subdiv = ~0; else subdiv = 1 << subdiv; return subdiv; } uint renderwaterlod(int x, int y, int z, uint size, int mat) { if(size <= (uint)(32 << waterlod)) { uint subdiv = calcwatersubdiv(x, y, z, size); if(subdiv < size * 2) rendervertwater(min(subdiv, size), x, y, z, size, mat); return subdiv; } else { uint subdiv = calcwatersubdiv(x, y, z, size); if(subdiv >= size) { if(subdiv < size * 2) rendervertwater(size, x, y, z, size, mat); return subdiv; } uint childsize = size / 2, subdiv1 = renderwaterlod(x, y, z, childsize, mat), subdiv2 = renderwaterlod(x + childsize, y, z, childsize, mat), subdiv3 = renderwaterlod(x + childsize, y + childsize, z, childsize, mat), subdiv4 = renderwaterlod(x, y + childsize, z, childsize, mat), minsubdiv = subdiv1; minsubdiv = min(minsubdiv, subdiv2); minsubdiv = min(minsubdiv, subdiv3); minsubdiv = min(minsubdiv, subdiv4); if(minsubdiv < size * 2) { if(minsubdiv >= size) rendervertwater(size, x, y, z, size, mat); else { if(subdiv1 >= size) rendervertwater(childsize, x, y, z, childsize, mat); if(subdiv2 >= size) rendervertwater(childsize, x + childsize, y, z, childsize, mat); if(subdiv3 >= size) rendervertwater(childsize, x + childsize, y + childsize, z, childsize, mat); if(subdiv4 >= size) rendervertwater(childsize, x, y + childsize, z, childsize, mat); } } return minsubdiv; } } #define renderwaterquad(vertwn, z) \ { \ if(varray::data.empty()) { def##vertwn(); varray::begin(GL_QUADS); } \ vertwn(x, y, z); \ vertwn(x+rsize, y, z); \ vertwn(x+rsize, y+csize, z); \ vertwn(x, y+csize, z); \ xtraverts += 4; \ } void renderflatwater(int x, int y, int z, uint rsize, uint csize, int mat) { switch(mat) { case MAT_WATER: if(renderpath!=R_FIXEDFUNCTION) { renderwaterquad(vertwtn, z); } else { bool below = camera1->o.z < z-WATER_OFFSET; if(nowater || minimapping) { renderwaterquad(vertwcn, z); } else if(waterrefract) { if(waterreflect && !below) { renderwaterquad(vertwmtcn, z); } else if(waterenvmap && hasCM && !below) { renderwaterquad(vertwemtcn, z); } else { renderwaterquad(vertwtcn, z); } } else if(waterreflect && !below) { renderwaterquad(vertwtcn, z); } else if(waterenvmap && hasCM && !below) { renderwaterquad(vertwetcn, z); } else { renderwaterquad(vertwcn, z); } } break; case MAT_LAVA: renderwaterquad(vertln, z); break; } } VARFP(vertwater, 0, 1, 1, allchanged()); static inline void renderwater(const materialsurface &m, int mat = MAT_WATER) { if(!vertwater || minimapping) renderflatwater(m.o.x, m.o.y, m.o.z, m.rsize, m.csize, mat); else if(renderwaterlod(m.o.x, m.o.y, m.o.z, m.csize, mat) >= (uint)m.csize * 2) rendervertwater(m.csize, m.o.x, m.o.y, m.o.z, m.csize, mat); } void renderlava(const materialsurface &m, Texture *tex, float scale) { lavaxk = 8.0f/(tex->xs*scale); lavayk = 8.0f/(tex->ys*scale); lavascroll = lastmillis/1000.0f; renderwater(m, MAT_LAVA); } /* reflective/refractive water */ #define MAXREFLECTIONS 16 struct Reflection { GLuint tex, refracttex; int material, height, depth, lastupdate, lastused; glmatrixf projmat; occludequery *query, *prevquery; vector matsurfs; Reflection() : tex(0), refracttex(0), material(-1), height(-1), depth(0), lastused(0), query(NULL), prevquery(NULL) {} }; VARP(reflectdist, 0, 2000, 10000); #define WATERVARS(name) \ bvec name##color(0x14, 0x46, 0x50), name##fallcolor(0, 0, 0); \ HVARFR(name##colour, 0, 0x144650, 0xFFFFFF, \ { \ if(!name##colour) name##colour = 0x144650; \ name##color = bvec((name##colour>>16)&0xFF, (name##colour>>8)&0xFF, name##colour&0xFF); \ }); \ VARR(name##fog, 0, 150, 10000); \ VARR(name##spec, 0, 150, 1000); \ HVARFR(name##fallcolour, 0, 0, 0xFFFFFF, \ { \ name##fallcolor = bvec((name##fallcolour>>16)&0xFF, (name##fallcolour>>8)&0xFF, name##fallcolour&0xFF); \ }); WATERVARS(water) WATERVARS(water2) WATERVARS(water3) WATERVARS(water4) GETMATIDXVAR(water, colour, int) GETMATIDXVAR(water, color, const bvec &) GETMATIDXVAR(water, fallcolour, int) GETMATIDXVAR(water, fallcolor, const bvec &) GETMATIDXVAR(water, fog, int) GETMATIDXVAR(water, spec, int) #define LAVAVARS(name) \ bvec name##color(0xFF, 0x40, 0x00); \ HVARFR(name##colour, 0, 0xFF4000, 0xFFFFFF, \ { \ if(!name##colour) name##colour = 0xFF4000; \ name##color = bvec((name##colour>>16)&0xFF, (name##colour>>8)&0xFF, name##colour&0xFF); \ }); \ VARR(name##fog, 0, 50, 10000); LAVAVARS(lava) LAVAVARS(lava2) LAVAVARS(lava3) LAVAVARS(lava4) GETMATIDXVAR(lava, colour, int) GETMATIDXVAR(lava, color, const bvec &) GETMATIDXVAR(lava, fog, int) void setprojtexmatrix(Reflection &ref, bool init = true) { if(init && ref.lastupdate==totalmillis) (ref.projmat = mvpmatrix).projective(); glLoadMatrixf(ref.projmat.v); } void setuprefractTMUs() { setuptmu(0, "= T"); if(waterreflect || (waterenvmap && hasCM)) { glActiveTexture_(GL_TEXTURE1_ARB); glEnable(waterreflect ? GL_TEXTURE_2D : GL_TEXTURE_CUBE_MAP_ARB); if(!waterreflect) glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, lookupenvmap(lookupmaterialslot(MAT_WATER))); setuptmu(1, "T , P @ Ca"); glActiveTexture_(GL_TEXTURE0_ARB); } } void setupreflectTMUs() { setuptmu(0, "T , K @ Ca", "Ka * C~a"); glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_SRC_ALPHA); if(!waterreflect) { glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_CUBE_MAP_ARB); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, lookupenvmap(lookupmaterialslot(MAT_WATER))); } } void cleanupwaterTMUs(bool refract) { resettmu(0); if(refract) { if(waterrefract || (waterenvmap && hasCM)) { glActiveTexture_(GL_TEXTURE1_ARB); resettmu(1); glLoadIdentity(); glDisable(waterreflect ? GL_TEXTURE_2D : GL_TEXTURE_CUBE_MAP_ARB); glActiveTexture_(GL_TEXTURE0_ARB); } } else { glDisable(GL_BLEND); glDepthMask(GL_TRUE); } } Reflection reflections[MAXREFLECTIONS]; Reflection waterfallrefraction; GLuint reflectionfb = 0, reflectiondb = 0; GLuint getwaterfalltex() { return waterfallrefraction.refracttex ? waterfallrefraction.refracttex : notexture->id; } VAR(oqwater, 0, 2, 2); extern int oqfrags; void renderwaterff() { glDisable(GL_CULL_FACE); if(minimapping) glDisable(GL_TEXTURE_2D); else if(!nowater && (waterreflect || waterrefract || (waterenvmap && hasCM))) { if(waterrefract) setuprefractTMUs(); else setupreflectTMUs(); glMatrixMode(GL_TEXTURE); } else { glDisable(GL_TEXTURE_2D); glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } float offset = -WATER_OFFSET; varray::enable(); bool wasbelow = false; loopi(MAXREFLECTIONS) { Reflection &ref = reflections[i]; if(ref.height<0 || ref.lastusedo.z < ref.height + offset; if(!nowater && (waterrefract || waterreflect || (waterenvmap && hasCM)) && !minimapping) { if(hasOQ && oqfrags && oqwater && ref.query && ref.query->owner==&ref) { if(!ref.prevquery || ref.prevquery->owner!=&ref || checkquery(ref.prevquery)) { if(checkquery(ref.query)) continue; } } bool projtex = false; if(waterreflect || (waterenvmap && hasCM)) { bool tmu1 = waterrefract && (!below || !wasbelow); if(tmu1) glActiveTexture_(GL_TEXTURE1_ARB); if(!below) { if(wasbelow) { wasbelow = false; glEnable(waterreflect ? GL_TEXTURE_2D : GL_TEXTURE_CUBE_MAP_ARB); if(!waterrefract) glBlendFunc(GL_ONE, GL_SRC_ALPHA); } if(waterreflect) { glBindTexture(GL_TEXTURE_2D, ref.tex); setprojtexmatrix(ref); projtex = true; } else { glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, lookupenvmap(lookupmaterialslot(ref.material))); } } else if(!wasbelow) { wasbelow = true; glDisable(waterreflect ? GL_TEXTURE_2D : GL_TEXTURE_CUBE_MAP_ARB); if(!waterrefract) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } if(tmu1) glActiveTexture_(GL_TEXTURE0_ARB); } if(waterrefract) { glBindTexture(GL_TEXTURE_2D, ref.refracttex); setprojtexmatrix(ref, !projtex); } } memcpy(wcol, getwatercolor(ref.material).v, 3); int wfog = getwaterfog(ref.material); int lastdepth = -1; loopvj(ref.matsurfs) { materialsurface &m = *ref.matsurfs[j]; if(m.depth!=lastdepth) { float depth = !wfog ? 1.0f : min(0.75f*m.depth/wfog, 0.95f); if(nowater || !waterrefract) depth = max(depth, nowater || (!waterreflect && (!waterenvmap || !hasCM)) || below ? 0.6f : 0.3f); wcol[3] = int(depth*255); if(!nowater && !waterrefract && ((waterreflect || (waterenvmap && hasCM)) && !below)) { if(varray::data.length()) varray::end(); colortmu(0, depth*wcol[0]/255.0f, depth*wcol[1]/255.0f, depth*wcol[2]/255.0f, 1-depth); } lastdepth = m.depth; } renderwater(m); } if(varray::data.length()) varray::end(); } varray::disable(); if(minimapping) glEnable(GL_TEXTURE_2D); else if(!nowater && (waterrefract || waterreflect || (waterenvmap && hasCM))) { if(!waterrefract && (wasbelow || !waterreflect)) { if(!waterreflect && !wasbelow) glDisable(GL_TEXTURE_CUBE_MAP_ARB); glEnable(GL_TEXTURE_2D); } cleanupwaterTMUs(waterrefract!=0); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } else { glEnable(GL_TEXTURE_2D); glDepthMask(GL_TRUE); glDisable(GL_BLEND); } glEnable(GL_CULL_FACE); } VARFP(waterfade, 0, 1, 1, { cleanreflections(); preloadwatershaders(); }); void preloadwatershaders(bool force) { static bool needwater = false; if(force) needwater = true; if(!needwater) return; useshaderbyname("waterglare"); if(waterenvmap && !waterreflect && hasCM) useshaderbyname(waterrefract ? (waterfade && hasFBO ? "waterenvfade" : "waterenvrefract") : "waterenv"); else useshaderbyname(waterrefract ? (waterfade && hasFBO ? "waterfade" : "waterrefract") : (waterreflect ? "waterreflect" : "water")); useshaderbyname(waterrefract ? (waterfade && hasFBO ? "underwaterfade" : "underwaterrefract") : "underwater"); extern int waterfallenv; if(waterfallenv && hasCM) useshaderbyname("waterfallenv"); if(waterfallrefract) useshaderbyname(waterfallenv && hasCM ? "waterfallenvrefract" : "waterfallrefract"); } void renderwater() { if(editmode && showmat && !envmapping) return; if(!rplanes) return; if(renderpath==R_FIXEDFUNCTION) { renderwaterff(); return; } glDisable(GL_CULL_FACE); glActiveTexture_(GL_TEXTURE1_ARB); glEnable(GL_TEXTURE_2D); glActiveTexture_(GL_TEXTURE2_ARB); glEnable(GL_TEXTURE_2D); if(!glaring && !minimapping) { if(waterrefract) { glActiveTexture_(GL_TEXTURE3_ARB); glEnable(GL_TEXTURE_2D); if(waterfade && hasFBO) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } else { glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_SRC_ALPHA); } } glActiveTexture_(GL_TEXTURE0_ARB); if(!glaring && waterenvmap && !waterreflect && hasCM && !minimapping) { glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_CUBE_MAP_ARB); } setenvparamf("camera", SHPARAM_VERTEX, 0, camera1->o.x, camera1->o.y, camera1->o.z); setenvparamf("millis", SHPARAM_VERTEX, 1, lastmillis/1000.0f, lastmillis/1000.0f, lastmillis/1000.0f); #define SETWATERSHADER(which, name) \ do { \ static Shader *name##shader = NULL; \ if(!name##shader) name##shader = lookupshaderbyname(#name); \ which##shader = name##shader; \ } while(0) Shader *aboveshader = NULL; if(glaring) SETWATERSHADER(above, waterglare); else if(minimapping) aboveshader = notextureshader; else if(waterenvmap && !waterreflect && hasCM) { if(waterrefract) { if(waterfade && hasFBO) SETWATERSHADER(above, waterenvfade); else SETWATERSHADER(above, waterenvrefract); } else SETWATERSHADER(above, waterenv); } else if(waterrefract) { if(waterfade && hasFBO) SETWATERSHADER(above, waterfade); else SETWATERSHADER(above, waterrefract); } else if(waterreflect) SETWATERSHADER(above, waterreflect); else SETWATERSHADER(above, water); Shader *belowshader = NULL; if(!glaring && !minimapping) { if(waterrefract) { if(waterfade && hasFBO) SETWATERSHADER(below, underwaterfade); else SETWATERSHADER(below, underwaterrefract); } else SETWATERSHADER(below, underwater); if(waterreflect || waterrefract) glMatrixMode(GL_TEXTURE); } varray::enable(); vec ambient(max(skylightcolor[0], ambientcolor[0]), max(skylightcolor[1], ambientcolor[1]), max(skylightcolor[2], ambientcolor[2])); float offset = -WATER_OFFSET; loopi(MAXREFLECTIONS) { Reflection &ref = reflections[i]; if(ref.height<0 || ref.lastusedowner==&ref) { if(!ref.prevquery || ref.prevquery->owner!=&ref || checkquery(ref.prevquery)) { if(checkquery(ref.query)) continue; } } bool below = camera1->o.z < ref.height+offset; if(below) { if(!belowshader) continue; belowshader->set(); } else aboveshader->set(); if(!glaring && !minimapping) { if(waterreflect || waterrefract) { if(waterreflect || !waterenvmap || !hasCM) glBindTexture(GL_TEXTURE_2D, waterreflect ? ref.tex : ref.refracttex); setprojtexmatrix(ref); } if(waterrefract) { glActiveTexture_(GL_TEXTURE3_ARB); glBindTexture(GL_TEXTURE_2D, ref.refracttex); if(waterfade) { float fadeheight = ref.height+offset+(below ? -2 : 2); setlocalparamf("waterheight", SHPARAM_VERTEX, 7, fadeheight, fadeheight, fadeheight); } } } MSlot &mslot = lookupmaterialslot(ref.material); glActiveTexture_(GL_TEXTURE1_ARB); glBindTexture(GL_TEXTURE_2D, mslot.sts.inrange(2) ? mslot.sts[2].t->id : notexture->id); glActiveTexture_(GL_TEXTURE2_ARB); glBindTexture(GL_TEXTURE_2D, mslot.sts.inrange(3) ? mslot.sts[3].t->id : notexture->id); glActiveTexture_(GL_TEXTURE0_ARB); if(!glaring && waterenvmap && !waterreflect && hasCM && !minimapping) { glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, lookupenvmap(mslot)); } glColor3ubv(getwatercolor(ref.material).v); int wfog = getwaterfog(ref.material), wspec = getwaterspec(ref.material); entity *lastlight = (entity *)-1; int lastdepth = -1; loopvj(ref.matsurfs) { materialsurface &m = *ref.matsurfs[j]; entity *light = (m.light && m.light->type==ET_LIGHT ? m.light : NULL); if(light!=lastlight) { if(varray::data.length()) varray::end(); const vec &lightpos = light ? light->o : vec(worldsize/2, worldsize/2, worldsize); float lightrad = light && light->attr1 ? light->attr1 : worldsize*8.0f; const vec &lightcol = (light ? vec(light->attr2, light->attr3, light->attr4) : vec(ambient)).div(255.0f).mul(wspec/100.0f); setlocalparamf("lightpos", SHPARAM_VERTEX, 2, lightpos.x, lightpos.y, lightpos.z); setlocalparamf("lightcolor", SHPARAM_PIXEL, 3, lightcol.x, lightcol.y, lightcol.z); setlocalparamf("lightradius", SHPARAM_PIXEL, 4, lightrad, lightrad, lightrad); lastlight = light; } if(!glaring && !waterrefract && m.depth!=lastdepth) { if(varray::data.length()) varray::end(); float depth = !wfog ? 1.0f : min(0.75f*m.depth/wfog, 0.95f); depth = max(depth, !below && (waterreflect || (waterenvmap && hasCM)) ? 0.3f : 0.6f); setlocalparamf("depth", SHPARAM_PIXEL, 5, depth, 1.0f-depth); lastdepth = m.depth; } renderwater(m); } if(varray::data.length()) varray::end(); } varray::disable(); if(!glaring && !minimapping) { if(waterreflect || waterrefract) { glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } if(waterrefract) { glActiveTexture_(GL_TEXTURE3_ARB); glDisable(GL_TEXTURE_2D); if(hasFBO && renderpath!=R_FIXEDFUNCTION && waterfade) glDisable(GL_BLEND); } else { glDepthMask(GL_TRUE); glDisable(GL_BLEND); } } loopi(2) { glActiveTexture_(GL_TEXTURE1_ARB+i); glDisable(GL_TEXTURE_2D); } glActiveTexture_(GL_TEXTURE0_ARB); if(!glaring && waterenvmap && !waterreflect && hasCM && !minimapping) { glDisable(GL_TEXTURE_CUBE_MAP_ARB); glEnable(GL_TEXTURE_2D); } glEnable(GL_CULL_FACE); } void setupwaterfallrefract(GLenum tmu1, GLenum tmu2) { glActiveTexture_(tmu1); glBindTexture(GL_TEXTURE_2D, waterfallrefraction.refracttex ? waterfallrefraction.refracttex : notexture->id); glActiveTexture_(tmu2); glMatrixMode(GL_TEXTURE); setprojtexmatrix(waterfallrefraction); glMatrixMode(GL_MODELVIEW); } void cleanreflection(Reflection &ref) { ref.material = -1; ref.height = -1; ref.lastupdate = 0; ref.query = ref.prevquery = NULL; ref.matsurfs.setsize(0); if(ref.tex) { glDeleteTextures(1, &ref.tex); ref.tex = 0; } if(ref.refracttex) { glDeleteTextures(1, &ref.refracttex); ref.refracttex = 0; } } void cleanreflections() { loopi(MAXREFLECTIONS) cleanreflection(reflections[i]); cleanreflection(waterfallrefraction); if(reflectionfb) { glDeleteFramebuffers_(1, &reflectionfb); reflectionfb = 0; } if(reflectiondb) { glDeleteRenderbuffers_(1, &reflectiondb); reflectiondb = 0; } } VARFP(reflectsize, 6, 8, 10, cleanreflections()); void genwatertex(GLuint &tex, GLuint &fb, GLuint &db, bool refract = false) { static const GLenum colorfmts[] = { GL_RGBA, GL_RGBA8, GL_RGB, GL_RGB8, GL_FALSE }, depthfmts[] = { GL_DEPTH_STENCIL_EXT, GL_DEPTH24_STENCIL8_EXT, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT32, GL_FALSE }; const int stencilfmts = 2; static GLenum reflectfmt = GL_FALSE, refractfmt = GL_FALSE, depthfmt = GL_FALSE, stencilfmt = GL_FALSE; static bool usingalpha = false; bool needsalpha = refract && hasFBO && renderpath!=R_FIXEDFUNCTION && waterrefract && waterfade; if(refract && usingalpha!=needsalpha) { usingalpha = needsalpha; refractfmt = GL_FALSE; } int size = 1<screen->w || size>screen->h) size /= 2; while(size>hwtexsize) size /= 2; glGenTextures(1, &tex); char *buf = new char[size*size*4]; memset(buf, 0, size*size*4); GLenum &colorfmt = refract ? refractfmt : reflectfmt; if(colorfmt && (!hasFBO || (fb && db))) { createtexture(tex, size, size, buf, 3, 1, colorfmt); delete[] buf; return; } if(hasFBO) { if(!fb) glGenFramebuffers_(1, &fb); glBindFramebuffer_(GL_FRAMEBUFFER_EXT, fb); } int find = needsalpha ? 0 : 2; do { createtexture(tex, size, size, buf, 3, 1, colorfmt ? colorfmt : colorfmts[find]); if(!hasFBO) break; else { glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, tex, 0); if(glCheckFramebufferStatus_(GL_FRAMEBUFFER_EXT)==GL_FRAMEBUFFER_COMPLETE_EXT) break; } } while(!colorfmt && colorfmts[++find]); if(!colorfmt) colorfmt = colorfmts[find]; delete[] buf; if(hasFBO) { if(!db) { glGenRenderbuffers_(1, &db); depthfmt = stencilfmt = GL_FALSE; } if(!depthfmt) glBindRenderbuffer_(GL_RENDERBUFFER_EXT, db); find = hasstencil && hasDS ? 0 : stencilfmts; do { if(!depthfmt) glRenderbufferStorage_(GL_RENDERBUFFER_EXT, depthfmts[find], size, size); glFramebufferRenderbuffer_(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, db); if(depthfmt ? stencilfmt : findlastused) oldest = &r; } if(!ref) { if(!oldest || oldest->lastused==totalmillis) return; ref = oldest; } if(ref->height!=height || ref->material!=mat) { ref->material = mat; ref->height = height; ref->prevquery = NULL; } rplanes++; ref->lastused = totalmillis; ref->matsurfs.setsize(0); ref->matsurfs.add(&m); ref->depth = m.depth; if(nowater || minimapping) return; if(waterreflect && !ref->tex) genwatertex(ref->tex, reflectionfb, reflectiondb); if(waterrefract && !ref->refracttex) genwatertex(ref->refracttex, reflectionfb, reflectiondb, true); } static void drawmaterialquery(const materialsurface &m, float offset, float border = 0) { if(varray::data.empty()) { varray::defattrib(varray::ATTRIB_VERTEX, 3, GL_FLOAT); varray::begin(GL_QUADS); } float x = m.o.x, y = m.o.y, z = m.o.z, csize = m.csize + border, rsize = m.rsize + border; switch(m.orient) { #define GENFACEORIENT(orient, v0, v1, v2, v3) \ case orient: v0 v1 v2 v3 break; #define GENFACEVERT(orient, vert, mx,my,mz, sx,sy,sz) \ varray::attrib(mx sx, my sy, mz sz); GENFACEVERTS(x, x, y, y, z, z, - border, + csize, - border, + rsize, + offset, - offset) #undef GENFACEORIENT #undef GENFACEVERT } } extern vtxarray *visibleva; extern void drawreflection(float z, bool refract, int fogdepth = -1, const bvec &col = bvec(0, 0, 0)); int rplanes = 0; static int lastquery = 0; void queryreflection(Reflection &ref, bool init) { if(init) { nocolorshader->set(); glDepthMask(GL_FALSE); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDisable(GL_CULL_FACE); } startquery(ref.query); loopvj(ref.matsurfs) { materialsurface &m = *ref.matsurfs[j]; float offset = 0.1f; if(m.orient==O_TOP) { offset = WATER_OFFSET + (vertwater ? WATER_AMPLITUDE*(camera1->pitch > 0 || m.depth < WATER_AMPLITUDE+0.5f ? -1 : 1) : 0); if(fabs(m.o.z-offset - camera1->o.z) < 0.5f && m.depth > WATER_AMPLITUDE+1.5f) offset += camera1->pitch > 0 ? -1 : 1; } drawmaterialquery(m, offset); } xtraverts += varray::end(); endquery(ref.query); } void queryreflections() { rplanes = 0; static int lastsize = 0; int size = 1<screen->w || size>screen->h) size /= 2; while(size>hwtexsize) size /= 2; if(size!=lastsize) { if(lastsize) cleanreflections(); lastsize = size; } bool shouldrefract = waterfallrefract && renderpath!=R_FIXEDFUNCTION; for(vtxarray *va = visibleva; va; va = va->next) { if(!va->matsurfs || va->occluded >= OCCLUDE_BB || va->curvfc >= VFC_FOGGED) continue; int lastmat = -1; loopi(va->matsurfs) { materialsurface &m = va->matbuf[i]; if(m.material != lastmat) { if((m.material&MATF_VOLUME) != MAT_WATER || m.orient == O_BOTTOM) { i += m.skip; continue; } if(m.orient != O_TOP) { if(!shouldrefract || !getwaterfog(m.material)) { i += m.skip; continue; } } lastmat = m.material; } if(m.orient==O_TOP) addreflection(m); else addwaterfallrefraction(m); } } loopi(MAXREFLECTIONS) { Reflection &ref = reflections[i]; if(ref.height>=0 && ref.lastused>=totalmillis && ref.matsurfs.length()) { if(waterpvsoccluded(ref.height)) ref.matsurfs.setsize(0); } } if(renderpath!=R_FIXEDFUNCTION && waterfallrefract) { Reflection &ref = waterfallrefraction; if(ref.height>=0 && ref.lastused>=totalmillis && ref.matsurfs.length()) { if(waterpvsoccluded(-1)) ref.matsurfs.setsize(0); } } lastquery = totalmillis; if((editmode && showmat && !envmapping) || !hasOQ || !oqfrags || !oqwater || nowater || minimapping) return; varray::enable(); int refs = 0; if(waterreflect || waterrefract) loopi(MAXREFLECTIONS) { Reflection &ref = reflections[i]; ref.prevquery = oqwater > 1 ? ref.query : NULL; ref.query = ref.height>=0 && ref.lastused>=totalmillis && ref.matsurfs.length() ? newquery(&ref) : NULL; if(ref.query) queryreflection(ref, !refs++); } if(renderpath!=R_FIXEDFUNCTION && waterfallrefract) { Reflection &ref = waterfallrefraction; ref.prevquery = oqwater > 1 ? ref.query : NULL; ref.query = ref.height>=0 && ref.lastused>=totalmillis && ref.matsurfs.length() ? newquery(&ref) : NULL; if(ref.query) queryreflection(ref, !refs++); } varray::disable(); if(refs) { defaultshader->set(); glDepthMask(GL_TRUE); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glEnable(GL_CULL_FACE); } glFlush(); } VARP(maxreflect, 1, 1, 8); int refracting = 0, refractfog = 0; bvec refractcolor(0, 0, 0); bool reflecting = false, fading = false, fogging = false; float reflectz = 1e16f; VAR(maskreflect, 0, 2, 16); void maskreflection(Reflection &ref, float offset, bool reflect, bool clear = false) { const bvec &wcol = getwatercolor(ref.material); float fogc[4] = { wcol[0]/255.0f, wcol[1]/255.0f, wcol[2]/255.0f, 1.0f }; bool inside = ref.height < INT_MAX && !hasFBO && vertwater && fabs(ref.height + offset - camera1->o.z) <= WATER_AMPLITUDE; if(!maskreflect || inside) { if(clear || inside) glClearColor(fogc[0], fogc[1], fogc[2], fogc[3]); glClear(GL_DEPTH_BUFFER_BIT | (clear || inside ? GL_COLOR_BUFFER_BIT : 0) | (hasstencil && hasDS ? GL_STENCIL_BUFFER_BIT : 0)); return; } glClearDepth(0); glClear(GL_DEPTH_BUFFER_BIT | (hasstencil && hasDS ? GL_STENCIL_BUFFER_BIT : 0)); glClearDepth(1); glDepthRange(1, 1); glDepthFunc(GL_ALWAYS); glDisable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); if(clear) { notextureshader->set(); glColor3f(fogc[0], fogc[1], fogc[2]); } else { nocolorshader->set(); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); } if(reflect) { glPushMatrix(); glTranslatef(0, 0, 2*(ref.height+offset)); glScalef(1, 1, -1); } varray::enable(); loopv(ref.matsurfs) { materialsurface &m = *ref.matsurfs[i]; drawmaterialquery(m, -offset, maskreflect); } xtraverts += varray::end(); varray::disable(); if(reflect) glPopMatrix(); if(!clear) glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); defaultshader->set(); glEnable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); glDepthFunc(GL_LESS); glDepthRange(0, 1); } VAR(reflectscissor, 0, 1, 1); VAR(reflectvfc, 0, 1, 1); static bool calcscissorbox(Reflection &ref, int size, vec &clipmin, vec &clipmax, int &sx, int &sy, int &sw, int &sh) { materialsurface &m0 = *ref.matsurfs[0]; int dim = dimension(m0.orient), r = R[dim], c = C[dim]; ivec bbmin = m0.o, bbmax = bbmin; bbmax[r] += m0.rsize; bbmax[c] += m0.csize; loopvj(ref.matsurfs) { materialsurface &m = *ref.matsurfs[j]; bbmin[r] = min(bbmin[r], m.o[r]); bbmin[c] = min(bbmin[c], m.o[c]); bbmax[r] = max(bbmax[r], m.o[r] + m.rsize); bbmax[c] = max(bbmax[c], m.o[c] + m.csize); bbmin[dim] = min(bbmin[dim], m.o[dim]); bbmax[dim] = max(bbmax[dim], m.o[dim]); } vec4 v[8]; float sx1 = 1, sy1 = 1, sx2 = -1, sy2 = -1; loopi(8) { vec4 &p = v[i]; mvpmatrix.transform(vec(i&1 ? bbmax.x : bbmin.x, i&2 ? bbmax.y : bbmin.y, (i&4 ? bbmax.z + WATER_AMPLITUDE : bbmin.z - WATER_AMPLITUDE) - WATER_OFFSET), p); if(p.z >= -p.w) { float x = p.x / p.w, y = p.y / p.w; sx1 = min(sx1, x); sy1 = min(sy1, y); sx2 = max(sx2, x); sy2 = max(sy2, y); } } if(sx1 >= sx2 || sy1 >= sy2) return false; loopi(8) { const vec4 &p = v[i]; if(p.z >= -p.w) continue; loopj(3) { const vec4 &o = v[i^(1<= 1 && sy2 >= 1) return false; sx1 = max(sx1, -1.0f); sy1 = max(sy1, -1.0f); sx2 = min(sx2, 1.0f); sy2 = min(sy2, 1.0f); if(reflectvfc) { clipmin.x = clamp(clipmin.x, sx1, sx2); clipmin.y = clamp(clipmin.y, sy1, sy2); clipmax.x = clamp(clipmax.x, sx1, sx2); clipmax.y = clamp(clipmax.y, sy1, sy2); } sx = int(floor((hasFBO ? 0 : screen->w-size) + (sx1+1)*0.5f*size)); sy = int(floor((hasFBO ? 0 : screen->h-size) + (sy1+1)*0.5f*size)); sw = max(int(ceil((hasFBO ? 0 : screen->w-size) + (sx2+1)*0.5f*size)) - sx, 0); sh = max(int(ceil((hasFBO ? 0 : screen->h-size) + (sy2+1)*0.5f*size)) - sy, 0); return true; } VARR(refractclear, 0, 0, 1); void drawreflections() { if((editmode && showmat && !envmapping) || nowater || minimapping) return; extern int nvidia_scissor_bug; static int lastdrawn = 0; int refs = 0, n = lastdrawn; float offset = -WATER_OFFSET; int size = 1<screen->w || size>screen->h) size /= 2; while(size>hwtexsize) size /= 2; if(waterreflect || waterrefract) loopi(MAXREFLECTIONS) { Reflection &ref = reflections[++n%MAXREFLECTIONS]; if(ref.height<0 || ref.lastusedowner==&ref) { if(!ref.prevquery || ref.prevquery->owner!=&ref || checkquery(ref.prevquery)) { if(checkquery(ref.query)) continue; } } if(!refs) { glViewport(hasFBO ? 0 : screen->w-size, hasFBO ? 0 : screen->h-size, size, size); if(hasFBO) glBindFramebuffer_(GL_FRAMEBUFFER_EXT, reflectionfb); } refs++; ref.lastupdate = totalmillis; lastdrawn = n; vec clipmin(-1, -1, -1), clipmax(1, 1, 1); int sx, sy, sw, sh; bool scissor = reflectscissor && calcscissorbox(ref, size, clipmin, clipmax, sx, sy, sw, sh); if(scissor) glScissor(sx, sy, sw, sh); else { sx = hasFBO ? 0 : screen->w-size; sy = hasFBO ? 0 : screen->h-size; sw = sh = size; } const bvec &wcol = getwatercolor(ref.material); int wfog = getwaterfog(ref.material); if(waterreflect && ref.tex && camera1->o.z >= ref.height+offset) { if(hasFBO) glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, ref.tex, 0); if(scissor && !nvidia_scissor_bug) glEnable(GL_SCISSOR_TEST); maskreflection(ref, offset, true); if(scissor && nvidia_scissor_bug) glEnable(GL_SCISSOR_TEST); savevfcP(); setvfcP(ref.height+offset, clipmin, clipmax); drawreflection(ref.height+offset, false); restorevfcP(); if(scissor) glDisable(GL_SCISSOR_TEST); if(!hasFBO) { glBindTexture(GL_TEXTURE_2D, ref.tex); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, sx-(screen->w-size), sy-(screen->h-size), sx, sy, sw, sh); } } if(waterrefract && ref.refracttex) { if(hasFBO) glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, ref.refracttex, 0); if(scissor && !nvidia_scissor_bug) glEnable(GL_SCISSOR_TEST); maskreflection(ref, offset, false, refractclear || !wfog || (ref.depth>=10000 && camera1->o.z >= ref.height + offset)); if(scissor && nvidia_scissor_bug) glEnable(GL_SCISSOR_TEST); if(wfog || (renderpath!=R_FIXEDFUNCTION && waterfade && hasFBO)) { savevfcP(); setvfcP(-1, clipmin, clipmax); drawreflection(ref.height+offset, true, wfog, wcol); restorevfcP(); } if(scissor) glDisable(GL_SCISSOR_TEST); if(!hasFBO) { glBindTexture(GL_TEXTURE_2D, ref.refracttex); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, sx-(screen->w-size), sy-(screen->h-size), sx, sy, sw, sh); } } if(refs>=maxreflect) break; } if(renderpath!=R_FIXEDFUNCTION && waterfallrefract && waterfallrefraction.refracttex) { Reflection &ref = waterfallrefraction; if(ref.height<0 || ref.lastusedowner==&ref) { if(!ref.prevquery || ref.prevquery->owner!=&ref || checkquery(ref.prevquery)) { if(checkquery(ref.query)) goto nowaterfall; } } if(!refs) { glViewport(hasFBO ? 0 : screen->w-size, hasFBO ? 0 : screen->h-size, size, size); if(hasFBO) glBindFramebuffer_(GL_FRAMEBUFFER_EXT, reflectionfb); } refs++; ref.lastupdate = totalmillis; vec clipmin(-1, -1, -1), clipmax(1, 1, 1); int sx, sy, sw, sh; bool scissor = reflectscissor && calcscissorbox(ref, size, clipmin, clipmax, sx, sy, sw, sh); if(scissor) glScissor(sx, sy, sw, sh); else { sx = hasFBO ? 0 : screen->w-size; sy = hasFBO ? 0 : screen->h-size; sw = sh = size; } if(hasFBO) glFramebufferTexture2D_(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, ref.refracttex, 0); if(scissor && !nvidia_scissor_bug) glEnable(GL_SCISSOR_TEST); maskreflection(ref, -0.1f, false); if(scissor && nvidia_scissor_bug) glEnable(GL_SCISSOR_TEST); savevfcP(); setvfcP(-1, clipmin, clipmax); drawreflection(-1, true); restorevfcP(); if(scissor) glDisable(GL_SCISSOR_TEST); if(!hasFBO) { glBindTexture(GL_TEXTURE_2D, ref.refracttex); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, sx-(screen->w-size), sy-(screen->h-size), sx, sy, sw, sh); } } nowaterfall: if(!refs) return; glViewport(0, 0, screen->w, screen->h); if(hasFBO) glBindFramebuffer_(GL_FRAMEBUFFER_EXT, 0); defaultshader->set(); } sauerbraten-0.0.20130203.dfsg/engine/smd.h0000644000175000017500000004353312072642735017616 0ustar vincentvincentstruct smd; struct smdbone { string name; int parent; smdbone() : parent(-1) { name[0] = '\0'; } }; struct smd : skelmodel, skelloader { smd(const char *name) : skelmodel(name) {} static const char *formatname() { return "smd"; } int type() const { return MDL_SMD; } struct smdmesh : skelmesh { }; struct smdmeshgroup : skelmeshgroup { smdmeshgroup() { } bool skipcomment(char *&curbuf) { while(*curbuf && isspace(*curbuf)) curbuf++; switch(*curbuf) { case '#': case ';': case '\r': case '\n': case '\0': return true; case '/': if(curbuf[1] == '/') return true; break; } return false; } void skipsection(stream *f, char *buf, size_t bufsize) { while(f->getline(buf, bufsize)) { char *curbuf = buf; if(skipcomment(curbuf)) continue; if(!strncmp(curbuf, "end", 3)) break; } } void readname(char *&curbuf, char *name, size_t namesize) { char *curname = name; while(*curbuf && isspace(*curbuf)) curbuf++; bool allowspace = false; if(*curbuf == '"') { curbuf++; allowspace = true; } while(*curbuf) { char c = *curbuf++; if(c == '"') break; if(isspace(c) && !allowspace) break; if(curname < &name[namesize-1]) *curname++ = c; } *curname = '\0'; } void readnodes(stream *f, char *buf, size_t bufsize, vector &bones) { while(f->getline(buf, bufsize)) { char *curbuf = buf; if(skipcomment(curbuf)) continue; if(!strncmp(curbuf, "end", 3)) break; int id = strtol(curbuf, &curbuf, 10); string name; readname(curbuf, name, sizeof(name)); int parent = strtol(curbuf, &curbuf, 10); if(id < 0 || id > 255 || parent > 255 || !name[0]) continue; while(!bones.inrange(id)) bones.add(); smdbone &bone = bones[id]; copystring(bone.name, name); bone.parent = parent; } } void readmaterial(char *&curbuf, char *name, size_t namesize) { char *curname = name; while(*curbuf && isspace(*curbuf)) curbuf++; while(*curbuf) { char c = *curbuf++; if(isspace(c)) break; if(c == '.') { while(*curbuf && !isspace(*curbuf)) curbuf++; break; } if(curname < &name[namesize-1]) *curname++ = c; } *curname = '\0'; } struct smdmeshdata { smdmesh *mesh; vector verts; vector tris; void finalize() { if(verts.empty() || tris.empty()) return; vert *mverts = new vert[mesh->numverts + verts.length()]; if(mesh->numverts) { memcpy(mverts, mesh->verts, mesh->numverts*sizeof(vert)); delete[] mesh->verts; } memcpy(&mverts[mesh->numverts], verts.getbuf(), verts.length()*sizeof(vert)); mesh->numverts += verts.length(); mesh->verts = mverts; tri *mtris = new tri[mesh->numtris + tris.length()]; if(mesh->numtris) { memcpy(mtris, mesh->tris, mesh->numtris*sizeof(tri)); delete[] mesh->tris; } memcpy(&mtris[mesh->numtris], tris.getbuf(), tris.length()*sizeof(tri)); mesh->numtris += tris.length(); mesh->tris = mtris; } }; struct smdvertkey : vert { smdmeshdata *mesh; smdvertkey(smdmeshdata *mesh) : mesh(mesh) {} }; void readtriangles(stream *f, char *buf, size_t bufsize) { smdmeshdata *curmesh = NULL; hashtable materials(1<<6); hashset verts(1<<12); while(f->getline(buf, bufsize)) { char *curbuf = buf; if(skipcomment(curbuf)) continue; if(!strncmp(curbuf, "end", 3)) break; string material; readmaterial(curbuf, material, sizeof(material)); if(!curmesh || strcmp(curmesh->mesh->name, material)) { curmesh = materials.access(material); if(!curmesh) { smdmesh *m = new smdmesh; m->group = this; m->name = newstring(material); meshes.add(m); curmesh = &materials[m->name]; curmesh->mesh = m; } } tri curtri; loopi(3) { char *curbuf; do { if(!f->getline(buf, bufsize)) goto endsection; curbuf = buf; } while(skipcomment(curbuf)); smdvertkey key(curmesh); int parent = -1, numlinks = 0, len = 0; if(sscanf(curbuf, " %d %f %f %f %f %f %f %f %f %d%n", &parent, &key.pos.x, &key.pos.y, &key.pos.z, &key.norm.x, &key.norm.y, &key.norm.z, &key.u, &key.v, &numlinks, &len) < 9) goto endsection; curbuf += len; key.pos.y = -key.pos.y; key.norm.y = -key.norm.y; key.v = 1 - key.v; blendcombo c; int sorted = 0; float pweight = 0, tweight = 0; for(; numlinks > 0; numlinks--) { int bone = -1, len = 0; float weight = 0; if(sscanf(curbuf, " %d %f%n", &bone, &weight, &len) < 2) break; curbuf += len; tweight += weight; if(bone == parent) pweight += weight; else sorted = c.addweight(sorted, weight, bone); } if(tweight < 1) pweight += 1 - tweight; if(pweight > 0) sorted = c.addweight(sorted, pweight, parent); c.finalize(sorted); key.blend = curmesh->mesh->addblendcombo(c); int index = verts.access(key, curmesh->verts.length()); if(index == curmesh->verts.length()) curmesh->verts.add(key); curtri.vert[2-i] = index; } curmesh->tris.add(curtri); } endsection: enumerate(materials, smdmeshdata, data, data.finalize()); } void readskeleton(stream *f, char *buf, size_t bufsize) { int frame = -1; while(f->getline(buf, bufsize)) { char *curbuf = buf; if(skipcomment(curbuf)) continue; if(sscanf(curbuf, " time %d", &frame) == 1) continue; else if(!strncmp(curbuf, "end", 3)) break; else if(frame != 0) continue; int bone; vec pos, rot; if(sscanf(curbuf, " %d %f %f %f %f %f %f", &bone, &pos.x, &pos.y, &pos.z, &rot.x, &rot.y, &rot.z) != 7) continue; if(bone < 0 || bone >= skel->numbones) continue; rot.x = -rot.x; rot.z = -rot.z; float cx = cosf(rot.x/2), sx = sinf(rot.x/2), cy = cosf(rot.y/2), sy = sinf(rot.y/2), cz = cosf(rot.z/2), sz = sinf(rot.z/2); pos.y = -pos.y; dualquat dq(quat(sx*cy*cz - cx*sy*sz, cx*sy*cz + sx*cy*sz, cx*cy*sz - sx*sy*cz, cx*cy*cz + sx*sy*sz), pos); boneinfo &b = skel->bones[bone]; if(b.parent < 0) b.base = dq; else b.base.mul(skel->bones[b.parent].base, dq); (b.invbase = b.base).invert(); } } bool loadmesh(const char *filename) { stream *f = openfile(filename, "r"); if(!f) return false; char buf[512]; int version = -1; while(f->getline(buf, sizeof(buf))) { char *curbuf = buf; if(skipcomment(curbuf)) continue; if(sscanf(curbuf, " version %d", &version) == 1) { if(version != 1) { delete f; return false; } } else if(!strncmp(curbuf, "nodes", 5)) { if(skel->numbones > 0) { skipsection(f, buf, sizeof(buf)); continue; } vector bones; readnodes(f, buf, sizeof(buf), bones); if(bones.empty()) continue; skel->numbones = bones.length(); skel->bones = new boneinfo[skel->numbones]; loopv(bones) { boneinfo &dst = skel->bones[i]; smdbone &src = bones[i]; dst.name = newstring(src.name); dst.parent = src.parent; } skel->linkchildren(); } else if(!strncmp(curbuf, "triangles", 9)) readtriangles(f, buf, sizeof(buf)); else if(!strncmp(curbuf, "skeleton", 8)) { if(skel->shared > 1) skipsection(f, buf, sizeof(buf)); else readskeleton(f, buf, sizeof(buf)); } else if(!strncmp(curbuf, "vertexanimation", 15)) skipsection(f, buf, sizeof(buf)); } sortblendcombos(); delete f; return true; } int readframes(stream *f, char *buf, size_t bufsize, vector &animbones) { int frame = -1, numframes = 0, lastbone = skel->numbones; while(f->getline(buf, bufsize)) { char *curbuf = buf; if(skipcomment(curbuf)) continue; int nextframe = -1; if(sscanf(curbuf, " time %d", &nextframe) == 1) { for(; lastbone < skel->numbones; lastbone++) animbones[frame*skel->numbones + lastbone] = animbones[lastbone]; if(nextframe >= numframes) { databuf framebones = animbones.reserve(skel->numbones * (nextframe + 1 - numframes)); loopi(nextframe - numframes) framebones.put(animbones.getbuf(), skel->numbones); animbones.addbuf(framebones); animbones.advance(skel->numbones); numframes = nextframe + 1; } frame = nextframe; lastbone = 0; continue; } else if(!strncmp(curbuf, "end", 3)) break; int bone; vec pos, rot; if(sscanf(curbuf, " %d %f %f %f %f %f %f", &bone, &pos.x, &pos.y, &pos.z, &rot.x, &rot.y, &rot.z) != 7) continue; if(bone < 0 || bone >= skel->numbones) continue; for(; lastbone < bone; lastbone++) animbones[frame*skel->numbones + lastbone] = animbones[lastbone]; lastbone++; float cx = cosf(rot.x/2), sx = sinf(rot.x/2), cy = cosf(rot.y/2), sy = sinf(rot.y/2), cz = cosf(rot.z/2), sz = sinf(rot.z/2); pos.y = -pos.y; dualquat dq(quat(-(sx*cy*cz - cx*sy*sz), cx*sy*cz + sx*cy*sz, -(cx*cy*sz - sx*sy*cz), cx*cy*cz + sx*sy*sz), pos); if(adjustments.inrange(bone)) adjustments[bone].adjust(dq); dq.mul(skel->bones[bone].invbase); dualquat &dst = animbones[frame*skel->numbones + bone]; if(skel->bones[bone].parent < 0) dst = dq; else dst.mul(skel->bones[skel->bones[bone].parent].base, dq); dst.fixantipodal(skel->numframes > 0 ? skel->framebones[bone] : animbones[bone]); } for(; lastbone < skel->numbones; lastbone++) animbones[frame*skel->numbones + lastbone] = animbones[lastbone]; return numframes; } skelanimspec *loadanim(const char *filename) { skelanimspec *sa = skel->findskelanim(filename); if(sa || skel->numbones <= 0) return sa; stream *f = openfile(filename, "r"); if(!f) return NULL; char buf[512]; int version = -1; vector animbones; while(f->getline(buf, sizeof(buf))) { char *curbuf = buf; if(skipcomment(curbuf)) continue; if(sscanf(curbuf, " version %d", &version) == 1) { if(version != 1) { delete f; return NULL; } } else if(!strncmp(curbuf, "nodes", 5)) { vector bones; readnodes(f, buf, sizeof(buf), bones); if(bones.length() != skel->numbones) { delete f; return NULL; } } else if(!strncmp(curbuf, "triangles", 9)) skipsection(f, buf, sizeof(buf)); else if(!strncmp(curbuf, "skeleton", 8)) readframes(f, buf, sizeof(buf), animbones); else if(!strncmp(curbuf, "vertexanimation", 15)) skipsection(f, buf, sizeof(buf)); } int numframes = animbones.length() / skel->numbones; dualquat *framebones = new dualquat[(skel->numframes+numframes)*skel->numbones]; if(skel->framebones) { memcpy(framebones, skel->framebones, skel->numframes*skel->numbones*sizeof(dualquat)); delete[] skel->framebones; } memcpy(&framebones[skel->numframes*skel->numbones], animbones.getbuf(), numframes*skel->numbones*sizeof(dualquat)); skel->framebones = framebones; sa = &skel->addskelanim(filename); sa->frame = skel->numframes; sa->range = numframes; skel->numframes += numframes; delete f; return sa; } bool load(const char *meshfile) { name = newstring(meshfile); if(!loadmesh(meshfile)) return false; return true; } }; meshgroup *loadmeshes(const char *name, va_list args) { smdmeshgroup *group = new smdmeshgroup; group->shareskeleton(va_arg(args, char *)); if(!group->load(name)) { delete group; return NULL; } return group; } bool loaddefaultparts() { skelpart &mdl = *new skelpart; parts.add(&mdl); mdl.model = this; mdl.index = 0; mdl.pitchscale = mdl.pitchoffset = mdl.pitchmin = mdl.pitchmax = 0; adjustments.setsize(0); const char *fname = loadname + strlen(loadname); do --fname; while(fname >= loadname && *fname!='/' && *fname!='\\'); fname++; defformatstring(meshname)("packages/models/%s/%s.smd", loadname, fname); mdl.meshes = sharemeshes(path(meshname), NULL); if(!mdl.meshes) return false; mdl.initanimparts(); mdl.initskins(); return true; } bool load() { if(loaded) return true; formatstring(dir)("packages/models/%s", loadname); defformatstring(cfgname)("packages/models/%s/smd.cfg", loadname); loading = this; identflags &= ~IDF_PERSIST; if(execfile(cfgname, false) && parts.length()) // configured smd, will call the smd* commands below { identflags |= IDF_PERSIST; loading = NULL; loopv(parts) if(!parts[i]->meshes) return false; } else // smd without configuration, try default tris and skin { identflags |= IDF_PERSIST; if(!loaddefaultparts()) { loading = NULL; return false; } loading = NULL; } scale /= 4; parts[0]->translate = translate; loopv(parts) { skelpart *p = (skelpart *)parts[i]; p->endanimparts(); p->meshes->shared++; } return loaded = true; } }; static inline uint hthash(const smd::smdmeshgroup::smdvertkey &k) { return hthash(k.pos); } static inline bool htcmp(const smd::smdmeshgroup::smdvertkey &k, int index) { if(!k.mesh->verts.inrange(index)) return false; const smd::vert &v = k.mesh->verts[index]; return k.pos == v.pos && k.norm == v.norm && k.u == v.u && k.v == v.v && k.blend == v.blend; } skelcommands smdcommands; sauerbraten-0.0.20130203.dfsg/engine/rendertext.cpp0000644000175000017500000002504511763374055021553 0ustar vincentvincent#include "engine.h" static inline bool htcmp(const char *key, const font &f) { return !strcmp(key, f.name); } static hashset fonts; static font *fontdef = NULL; static int fontdeftex = 0; font *curfont = NULL; int curfonttex = 0; void newfont(char *name, char *tex, int *defaultw, int *defaulth) { font *f = &fonts[name]; if(!f->name) f->name = newstring(name); f->texs.shrink(0); f->texs.add(textureload(tex)); f->chars.shrink(0); f->charoffset = '!'; f->defaultw = *defaultw; f->defaulth = *defaulth; f->scale = f->defaulth; fontdef = f; fontdeftex = 0; } void fontoffset(char *c) { if(!fontdef) return; fontdef->charoffset = c[0]; } void fontscale(int *scale) { if(!fontdef) return; fontdef->scale = *scale > 0 ? *scale : fontdef->defaulth; } void fonttex(char *s) { if(!fontdef) return; Texture *t = textureload(s); loopv(fontdef->texs) if(fontdef->texs[i] == t) { fontdeftex = i; return; } fontdeftex = fontdef->texs.length(); fontdef->texs.add(t); } void fontchar(int *x, int *y, int *w, int *h, int *offsetx, int *offsety, int *advance) { if(!fontdef) return; font::charinfo &c = fontdef->chars.add(); c.x = *x; c.y = *y; c.w = *w ? *w : fontdef->defaultw; c.h = *h ? *h : fontdef->defaulth; c.offsetx = *offsetx; c.offsety = *offsety; c.advance = *advance ? *advance : c.offsetx + c.w; c.tex = fontdeftex; } void fontskip(int *n) { if(!fontdef) return; loopi(max(*n, 1)) { font::charinfo &c = fontdef->chars.add(); c.x = c.y = c.w = c.h = c.offsetx = c.offsety = c.advance = c.tex = 0; } } COMMANDN(font, newfont, "ssii"); COMMAND(fontoffset, "s"); COMMAND(fontscale, "i"); COMMAND(fonttex, "s"); COMMAND(fontchar, "iiiiiii"); COMMAND(fontskip, "i"); void fontalias(const char *dst, const char *src) { font *s = fonts.access(src); if(!s) return; font *d = &fonts[dst]; if(!d->name) d->name = newstring(dst); d->texs = s->texs; d->chars = s->chars; d->charoffset = s->charoffset; d->defaultw = s->defaultw; d->defaulth = s->defaulth; d->scale = s->scale; fontdef = d; fontdeftex = d->texs.length()-1; } COMMAND(fontalias, "ss"); bool setfont(const char *name) { font *f = fonts.access(name); if(!f) return false; curfont = f; return true; } static vector fontstack; void pushfont() { fontstack.add(curfont); } bool popfont() { if(fontstack.empty()) return false; curfont = fontstack.pop(); return true; } void gettextres(int &w, int &h) { if(w < MINRESW || h < MINRESH) { if(MINRESW > w*MINRESH/h) { h = h*MINRESW/w; w = MINRESW; } else { w = w*MINRESH/h; h = MINRESH; } } } float text_widthf(const char *str) { float width, height; text_boundsf(str, width, height); return width; } #define FONTTAB (4*FONTW) #define TEXTTAB(x) ((int((x)/FONTTAB)+1.0f)*FONTTAB) void tabify(const char *str, int *numtabs) { int tw = max(*numtabs, 0)*FONTTAB-1, tabs = 0; for(float w = text_widthf(str); w <= tw; w = TEXTTAB(w)) ++tabs; int len = strlen(str); char *tstr = newstring(len + tabs); memcpy(tstr, str, len); memset(&tstr[len], '\t', tabs); tstr[len+tabs] = '\0'; stringret(tstr); } COMMAND(tabify, "si"); void draw_textf(const char *fstr, int left, int top, ...) { defvformatstring(str, top, fstr); draw_text(str, left, top); } static float draw_char(Texture *&tex, int c, float x, float y, float scale) { font::charinfo &info = curfont->chars[c-curfont->charoffset]; if(tex != curfont->texs[info.tex]) { xtraverts += varray::end(); tex = curfont->texs[info.tex]; glBindTexture(GL_TEXTURE_2D, tex->id); } float x1 = x + scale*info.offsetx, y1 = y + scale*info.offsety, x2 = x + scale*(info.offsetx + info.w), y2 = y + scale*(info.offsety + info.h), tx1 = info.x / float(tex->xs), ty1 = info.y / float(tex->ys), tx2 = (info.x + info.w) / float(tex->xs), ty2 = (info.y + info.h) / float(tex->ys); varray::attrib(x1, y1); varray::attrib(tx1, ty1); varray::attrib(x2, y1); varray::attrib(tx2, ty1); varray::attrib(x2, y2); varray::attrib(tx2, ty2); varray::attrib(x1, y2); varray::attrib(tx1, ty2); return scale*info.advance; } //stack[sp] is current color index static void text_color(char c, char *stack, int size, int &sp, bvec color, int a) { if(c=='s') // save color { c = stack[sp]; if(sp 0) ? --sp : sp]; // restore color else stack[sp] = c; switch(c) { case '0': color = bvec( 64, 255, 128); break; // green: player talk case '1': color = bvec( 96, 160, 255); break; // blue: "echo" command case '2': color = bvec(255, 192, 64); break; // yellow: gameplay messages case '3': color = bvec(255, 64, 64); break; // red: important errors case '4': color = bvec(128, 128, 128); break; // gray case '5': color = bvec(192, 64, 192); break; // magenta case '6': color = bvec(255, 128, 0); break; // orange case '7': color = bvec(255, 255, 255); break; // white // provided color: everything else } glColor4ub(color.x, color.y, color.z, a); } } #define TEXTSKELETON \ float y = 0, x = 0, scale = curfont->scale/float(curfont->defaulth);\ int i;\ for(i = 0; str[i]; i++)\ {\ TEXTINDEX(i)\ int c = uchar(str[i]);\ if(c=='\t') { x = TEXTTAB(x); TEXTWHITE(i) }\ else if(c==' ') { x += scale*curfont->defaultw; TEXTWHITE(i) }\ else if(c=='\n') { TEXTLINE(i) x = 0; y += FONTH; }\ else if(c=='\f') { if(str[i+1]) { i++; TEXTCOLOR(i) }}\ else if(curfont->chars.inrange(c-curfont->charoffset))\ {\ float cw = scale*curfont->chars[c-curfont->charoffset].advance;\ if(cw <= 0) continue;\ if(maxwidth != -1)\ {\ int j = i;\ float w = cw;\ for(; str[i+1]; i++)\ {\ int c = uchar(str[i+1]);\ if(c=='\f') { if(str[i+2]) i++; continue; }\ if(i-j > 16) break;\ if(!curfont->chars.inrange(c-curfont->charoffset)) break;\ float cw = scale*curfont->chars[c-curfont->charoffset].advance;\ if(cw <= 0 || w + cw > maxwidth) break;\ w += cw;\ }\ if(x + w > maxwidth && j!=0) { TEXTLINE(j-1) x = 0; y += FONTH; }\ TEXTWORD\ }\ else\ { TEXTCHAR(i) }\ }\ } //all the chars are guaranteed to be either drawable or color commands #define TEXTWORDSKELETON \ for(; j <= i; j++)\ {\ TEXTINDEX(j)\ int c = uchar(str[j]);\ if(c=='\f') { if(str[j+1]) { j++; TEXTCOLOR(j) }}\ else { float cw = scale*curfont->chars[c-curfont->charoffset].advance; TEXTCHAR(j) }\ } #define TEXTEND(cursor) if(cursor >= i) { do { TEXTINDEX(cursor); } while(0); } int text_visible(const char *str, float hitx, float hity, int maxwidth) { #define TEXTINDEX(idx) #define TEXTWHITE(idx) if(y+FONTH > hity && x >= hitx) return idx; #define TEXTLINE(idx) if(y+FONTH > hity) return idx; #define TEXTCOLOR(idx) #define TEXTCHAR(idx) x += cw; TEXTWHITE(idx) #define TEXTWORD TEXTWORDSKELETON TEXTSKELETON #undef TEXTINDEX #undef TEXTWHITE #undef TEXTLINE #undef TEXTCOLOR #undef TEXTCHAR #undef TEXTWORD return i; } //inverse of text_visible void text_posf(const char *str, int cursor, float &cx, float &cy, int maxwidth) { #define TEXTINDEX(idx) if(idx == cursor) { cx = x; cy = y; break; } #define TEXTWHITE(idx) #define TEXTLINE(idx) #define TEXTCOLOR(idx) #define TEXTCHAR(idx) x += cw; #define TEXTWORD TEXTWORDSKELETON if(i >= cursor) break; cx = cy = 0; TEXTSKELETON TEXTEND(cursor) #undef TEXTINDEX #undef TEXTWHITE #undef TEXTLINE #undef TEXTCOLOR #undef TEXTCHAR #undef TEXTWORD } void text_boundsf(const char *str, float &width, float &height, int maxwidth) { #define TEXTINDEX(idx) #define TEXTWHITE(idx) #define TEXTLINE(idx) if(x > width) width = x; #define TEXTCOLOR(idx) #define TEXTCHAR(idx) x += cw; #define TEXTWORD x += w; width = 0; TEXTSKELETON height = y + FONTH; TEXTLINE(_) #undef TEXTINDEX #undef TEXTWHITE #undef TEXTLINE #undef TEXTCOLOR #undef TEXTCHAR #undef TEXTWORD } void draw_text(const char *str, int left, int top, int r, int g, int b, int a, int cursor, int maxwidth) { #define TEXTINDEX(idx) if(idx == cursor) { cx = x; cy = y; } #define TEXTWHITE(idx) #define TEXTLINE(idx) #define TEXTCOLOR(idx) if(usecolor) text_color(str[idx], colorstack, sizeof(colorstack), colorpos, color, a); #define TEXTCHAR(idx) draw_char(tex, c, left+x, top+y, scale); x += cw; #define TEXTWORD TEXTWORDSKELETON char colorstack[10]; colorstack[0] = 'c'; //indicate user color bvec color(r, g, b); int colorpos = 0; float cx = -FONTW, cy = 0; bool usecolor = true; if(a < 0) { usecolor = false; a = -a; } Texture *tex = curfont->texs[0]; glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBindTexture(GL_TEXTURE_2D, tex->id); glColor4ub(color.x, color.y, color.z, a); varray::enable(); varray::defattrib(varray::ATTRIB_VERTEX, 2, GL_FLOAT); varray::defattrib(varray::ATTRIB_TEXCOORD0, 2, GL_FLOAT); varray::begin(GL_QUADS); TEXTSKELETON TEXTEND(cursor) xtraverts += varray::end(); if(cursor >= 0 && (totalmillis/250)&1) { glColor4ub(r, g, b, a); if(maxwidth != -1 && cx >= maxwidth) { cx = 0; cy += FONTH; } draw_char(tex, '_', left+cx, top+cy, scale); xtraverts += varray::end(); } varray::disable(); #undef TEXTINDEX #undef TEXTWHITE #undef TEXTLINE #undef TEXTCOLOR #undef TEXTCHAR #undef TEXTWORD } void reloadfonts() { enumerate(fonts, font, f, loopv(f.texs) if(!reloadtexture(*f.texs[i])) fatal("failed to reload font texture"); ); } sauerbraten-0.0.20130203.dfsg/enet/0000755000175000017500000000000012100771040016320 5ustar vincentvincentsauerbraten-0.0.20130203.dfsg/enet/host.c0000644000175000017500000004237312062514762017467 0ustar vincentvincent/** @file host.c @brief ENet host management functions */ #define ENET_BUILDING_LIB 1 #include #include #include "enet/enet.h" /** @defgroup host ENet host functions @{ */ /** Creates a host for communicating to peers. @param address the address at which other peers may connect to this host. If NULL, then no peers may connect to the host. @param peerCount the maximum number of peers that should be allocated for the host. @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT @param incomingBandwidth downstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth. @param outgoingBandwidth upstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth. @returns the host on success and NULL on failure @remarks ENet will strategically drop packets on specific sides of a connection between hosts to ensure the host's bandwidth is not overwhelmed. The bandwidth parameters also determine the window size of a connection which limits the amount of reliable packets that may be in transit at any given time. */ ENetHost * enet_host_create (const ENetAddress * address, size_t peerCount, size_t channelLimit, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth) { ENetHost * host; ENetPeer * currentPeer; if (peerCount > ENET_PROTOCOL_MAXIMUM_PEER_ID) return NULL; host = (ENetHost *) enet_malloc (sizeof (ENetHost)); if (host == NULL) return NULL; memset (host, 0, sizeof (ENetHost)); host -> peers = (ENetPeer *) enet_malloc (peerCount * sizeof (ENetPeer)); if (host -> peers == NULL) { enet_free (host); return NULL; } memset (host -> peers, 0, peerCount * sizeof (ENetPeer)); host -> socket = enet_socket_create (ENET_SOCKET_TYPE_DATAGRAM); if (host -> socket == ENET_SOCKET_NULL || (address != NULL && enet_socket_bind (host -> socket, address) < 0)) { if (host -> socket != ENET_SOCKET_NULL) enet_socket_destroy (host -> socket); enet_free (host -> peers); enet_free (host); return NULL; } enet_socket_set_option (host -> socket, ENET_SOCKOPT_NONBLOCK, 1); enet_socket_set_option (host -> socket, ENET_SOCKOPT_BROADCAST, 1); enet_socket_set_option (host -> socket, ENET_SOCKOPT_RCVBUF, ENET_HOST_RECEIVE_BUFFER_SIZE); enet_socket_set_option (host -> socket, ENET_SOCKOPT_SNDBUF, ENET_HOST_SEND_BUFFER_SIZE); if (address != NULL) host -> address = * address; if (! channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT) channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT; else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT) channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT; host -> randomSeed = (enet_uint32) (size_t) host; #ifdef WIN32 host -> randomSeed += (enet_uint32) timeGetTime(); #else host -> randomSeed += (enet_uint32) time(NULL); #endif host -> randomSeed = (host -> randomSeed << 16) | (host -> randomSeed >> 16); host -> channelLimit = channelLimit; host -> incomingBandwidth = incomingBandwidth; host -> outgoingBandwidth = outgoingBandwidth; host -> bandwidthThrottleEpoch = 0; host -> recalculateBandwidthLimits = 0; host -> mtu = ENET_HOST_DEFAULT_MTU; host -> peerCount = peerCount; host -> commandCount = 0; host -> bufferCount = 0; host -> checksum = NULL; host -> receivedAddress.host = ENET_HOST_ANY; host -> receivedAddress.port = 0; host -> receivedData = NULL; host -> receivedDataLength = 0; host -> totalSentData = 0; host -> totalSentPackets = 0; host -> totalReceivedData = 0; host -> totalReceivedPackets = 0; host -> compressor.context = NULL; host -> compressor.compress = NULL; host -> compressor.decompress = NULL; host -> compressor.destroy = NULL; host -> intercept = NULL; enet_list_clear (& host -> dispatchQueue); for (currentPeer = host -> peers; currentPeer < & host -> peers [host -> peerCount]; ++ currentPeer) { currentPeer -> host = host; currentPeer -> incomingPeerID = currentPeer - host -> peers; currentPeer -> outgoingSessionID = currentPeer -> incomingSessionID = 0xFF; currentPeer -> data = NULL; enet_list_clear (& currentPeer -> acknowledgements); enet_list_clear (& currentPeer -> sentReliableCommands); enet_list_clear (& currentPeer -> sentUnreliableCommands); enet_list_clear (& currentPeer -> outgoingReliableCommands); enet_list_clear (& currentPeer -> outgoingUnreliableCommands); enet_list_clear (& currentPeer -> dispatchedCommands); enet_peer_reset (currentPeer); } return host; } /** Destroys the host and all resources associated with it. @param host pointer to the host to destroy */ void enet_host_destroy (ENetHost * host) { ENetPeer * currentPeer; if (host == NULL) return; enet_socket_destroy (host -> socket); for (currentPeer = host -> peers; currentPeer < & host -> peers [host -> peerCount]; ++ currentPeer) { enet_peer_reset (currentPeer); } if (host -> compressor.context != NULL && host -> compressor.destroy) (* host -> compressor.destroy) (host -> compressor.context); enet_free (host -> peers); enet_free (host); } /** Initiates a connection to a foreign host. @param host host seeking the connection @param address destination for the connection @param channelCount number of channels to allocate @param data user data supplied to the receiving host @returns a peer representing the foreign host on success, NULL on failure @remarks The peer returned will have not completed the connection until enet_host_service() notifies of an ENET_EVENT_TYPE_CONNECT event for the peer. */ ENetPeer * enet_host_connect (ENetHost * host, const ENetAddress * address, size_t channelCount, enet_uint32 data) { ENetPeer * currentPeer; ENetChannel * channel; ENetProtocol command; if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT) channelCount = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT; else if (channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT) channelCount = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT; for (currentPeer = host -> peers; currentPeer < & host -> peers [host -> peerCount]; ++ currentPeer) { if (currentPeer -> state == ENET_PEER_STATE_DISCONNECTED) break; } if (currentPeer >= & host -> peers [host -> peerCount]) return NULL; currentPeer -> channels = (ENetChannel *) enet_malloc (channelCount * sizeof (ENetChannel)); if (currentPeer -> channels == NULL) return NULL; currentPeer -> channelCount = channelCount; currentPeer -> state = ENET_PEER_STATE_CONNECTING; currentPeer -> address = * address; currentPeer -> connectID = ++ host -> randomSeed; if (host -> outgoingBandwidth == 0) currentPeer -> windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; else currentPeer -> windowSize = (host -> outgoingBandwidth / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; if (currentPeer -> windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) currentPeer -> windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; else if (currentPeer -> windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) currentPeer -> windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; for (channel = currentPeer -> channels; channel < & currentPeer -> channels [channelCount]; ++ channel) { channel -> outgoingReliableSequenceNumber = 0; channel -> outgoingUnreliableSequenceNumber = 0; channel -> incomingReliableSequenceNumber = 0; channel -> incomingUnreliableSequenceNumber = 0; enet_list_clear (& channel -> incomingReliableCommands); enet_list_clear (& channel -> incomingUnreliableCommands); channel -> usedReliableWindows = 0; memset (channel -> reliableWindows, 0, sizeof (channel -> reliableWindows)); } command.header.command = ENET_PROTOCOL_COMMAND_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE; command.header.channelID = 0xFF; command.connect.outgoingPeerID = ENET_HOST_TO_NET_16 (currentPeer -> incomingPeerID); command.connect.incomingSessionID = currentPeer -> incomingSessionID; command.connect.outgoingSessionID = currentPeer -> outgoingSessionID; command.connect.mtu = ENET_HOST_TO_NET_32 (currentPeer -> mtu); command.connect.windowSize = ENET_HOST_TO_NET_32 (currentPeer -> windowSize); command.connect.channelCount = ENET_HOST_TO_NET_32 (channelCount); command.connect.incomingBandwidth = ENET_HOST_TO_NET_32 (host -> incomingBandwidth); command.connect.outgoingBandwidth = ENET_HOST_TO_NET_32 (host -> outgoingBandwidth); command.connect.packetThrottleInterval = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleInterval); command.connect.packetThrottleAcceleration = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleAcceleration); command.connect.packetThrottleDeceleration = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleDeceleration); command.connect.connectID = currentPeer -> connectID; command.connect.data = ENET_HOST_TO_NET_32 (data); enet_peer_queue_outgoing_command (currentPeer, & command, NULL, 0, 0); return currentPeer; } /** Queues a packet to be sent to all peers associated with the host. @param host host on which to broadcast the packet @param channelID channel on which to broadcast @param packet packet to broadcast */ void enet_host_broadcast (ENetHost * host, enet_uint8 channelID, ENetPacket * packet) { ENetPeer * currentPeer; for (currentPeer = host -> peers; currentPeer < & host -> peers [host -> peerCount]; ++ currentPeer) { if (currentPeer -> state != ENET_PEER_STATE_CONNECTED) continue; enet_peer_send (currentPeer, channelID, packet); } if (packet -> referenceCount == 0) enet_packet_destroy (packet); } /** Sets the packet compressor the host should use to compress and decompress packets. @param host host to enable or disable compression for @param compressor callbacks for for the packet compressor; if NULL, then compression is disabled */ void enet_host_compress (ENetHost * host, const ENetCompressor * compressor) { if (host -> compressor.context != NULL && host -> compressor.destroy) (* host -> compressor.destroy) (host -> compressor.context); if (compressor) host -> compressor = * compressor; else host -> compressor.context = NULL; } /** Limits the maximum allowed channels of future incoming connections. @param host host to limit @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT */ void enet_host_channel_limit (ENetHost * host, size_t channelLimit) { if (! channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT) channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT; else if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT) channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT; host -> channelLimit = channelLimit; } /** Adjusts the bandwidth limits of a host. @param host host to adjust @param incomingBandwidth new incoming bandwidth @param outgoingBandwidth new outgoing bandwidth @remarks the incoming and outgoing bandwidth parameters are identical in function to those specified in enet_host_create(). */ void enet_host_bandwidth_limit (ENetHost * host, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth) { host -> incomingBandwidth = incomingBandwidth; host -> outgoingBandwidth = outgoingBandwidth; host -> recalculateBandwidthLimits = 1; } void enet_host_bandwidth_throttle (ENetHost * host) { enet_uint32 timeCurrent = enet_time_get (), elapsedTime = timeCurrent - host -> bandwidthThrottleEpoch, peersTotal = 0, dataTotal = 0, peersRemaining, bandwidth, throttle = 0, bandwidthLimit = 0; int needsAdjustment; ENetPeer * peer; ENetProtocol command; if (elapsedTime < ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL) return; for (peer = host -> peers; peer < & host -> peers [host -> peerCount]; ++ peer) { if (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) continue; ++ peersTotal; dataTotal += peer -> outgoingDataTotal; } if (peersTotal == 0) return; peersRemaining = peersTotal; needsAdjustment = 1; if (host -> outgoingBandwidth == 0) bandwidth = ~0; else bandwidth = (host -> outgoingBandwidth * elapsedTime) / 1000; while (peersRemaining > 0 && needsAdjustment != 0) { needsAdjustment = 0; if (dataTotal < bandwidth) throttle = ENET_PEER_PACKET_THROTTLE_SCALE; else throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal; for (peer = host -> peers; peer < & host -> peers [host -> peerCount]; ++ peer) { enet_uint32 peerBandwidth; if ((peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) || peer -> incomingBandwidth == 0 || peer -> outgoingBandwidthThrottleEpoch == timeCurrent) continue; peerBandwidth = (peer -> incomingBandwidth * elapsedTime) / 1000; if ((throttle * peer -> outgoingDataTotal) / ENET_PEER_PACKET_THROTTLE_SCALE <= peerBandwidth) continue; peer -> packetThrottleLimit = (peerBandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / peer -> outgoingDataTotal; if (peer -> packetThrottleLimit == 0) peer -> packetThrottleLimit = 1; if (peer -> packetThrottle > peer -> packetThrottleLimit) peer -> packetThrottle = peer -> packetThrottleLimit; peer -> outgoingBandwidthThrottleEpoch = timeCurrent; needsAdjustment = 1; -- peersRemaining; bandwidth -= peerBandwidth; dataTotal -= peerBandwidth; } } if (peersRemaining > 0) for (peer = host -> peers; peer < & host -> peers [host -> peerCount]; ++ peer) { if ((peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) || peer -> outgoingBandwidthThrottleEpoch == timeCurrent) continue; peer -> packetThrottleLimit = throttle; if (peer -> packetThrottle > peer -> packetThrottleLimit) peer -> packetThrottle = peer -> packetThrottleLimit; } if (host -> recalculateBandwidthLimits) { host -> recalculateBandwidthLimits = 0; peersRemaining = peersTotal; bandwidth = host -> incomingBandwidth; needsAdjustment = 1; if (bandwidth == 0) bandwidthLimit = 0; else while (peersRemaining > 0 && needsAdjustment != 0) { needsAdjustment = 0; bandwidthLimit = bandwidth / peersRemaining; for (peer = host -> peers; peer < & host -> peers [host -> peerCount]; ++ peer) { if ((peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) || peer -> incomingBandwidthThrottleEpoch == timeCurrent) continue; if (peer -> outgoingBandwidth > 0 && peer -> outgoingBandwidth >= bandwidthLimit) continue; peer -> incomingBandwidthThrottleEpoch = timeCurrent; needsAdjustment = 1; -- peersRemaining; bandwidth -= peer -> outgoingBandwidth; } } for (peer = host -> peers; peer < & host -> peers [host -> peerCount]; ++ peer) { if (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) continue; command.header.command = ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE; command.header.channelID = 0xFF; command.bandwidthLimit.outgoingBandwidth = ENET_HOST_TO_NET_32 (host -> outgoingBandwidth); if (peer -> incomingBandwidthThrottleEpoch == timeCurrent) command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32 (peer -> outgoingBandwidth); else command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32 (bandwidthLimit); enet_peer_queue_outgoing_command (peer, & command, NULL, 0, 0); } } host -> bandwidthThrottleEpoch = timeCurrent; for (peer = host -> peers; peer < & host -> peers [host -> peerCount]; ++ peer) { peer -> incomingDataTotal = 0; peer -> outgoingDataTotal = 0; } } /** @} */ sauerbraten-0.0.20130203.dfsg/enet/ltmain.sh0000755000175000017500000105202612006035707020161 0ustar vincentvincent # libtool (GNU libtool) 2.4.2 # Written by Gordon Matzigkeit , 1996 # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, # 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, # or obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Usage: $progname [OPTION]... [MODE-ARG]... # # Provide generalized library-building support services. # # --config show all configuration variables # --debug enable verbose shell tracing # -n, --dry-run display commands without modifying any files # --features display basic configuration information and exit # --mode=MODE use operation mode MODE # --preserve-dup-deps don't remove duplicate dependency libraries # --quiet, --silent don't print informational messages # --no-quiet, --no-silent # print informational messages (default) # --no-warn don't display warning messages # --tag=TAG use configuration variables from tag TAG # -v, --verbose print more informational messages than default # --no-verbose don't print the extra informational messages # --version print version information # -h, --help, --help-all print short, long, or detailed help message # # MODE must be one of the following: # # clean remove files from the build directory # compile compile a source file into a libtool object # execute automatically set library path, then run a program # finish complete the installation of libtool libraries # install install libraries or executables # link create a library or an executable # uninstall remove libraries from an installed directory # # MODE-ARGS vary depending on the MODE. When passed as first option, # `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that. # Try `$progname --help --mode=MODE' for a more detailed description of MODE. # # When reporting a bug, please describe a test case to reproduce it and # include the following information: # # host-triplet: $host # shell: $SHELL # compiler: $LTCC # compiler flags: $LTCFLAGS # linker: $LD (gnu? $with_gnu_ld) # $progname: (GNU libtool) 2.4.2 Debian-2.4.2-1.1 # automake: $automake_version # autoconf: $autoconf_version # # Report bugs to . # GNU libtool home page: . # General help using GNU software: . PROGRAM=libtool PACKAGE=libtool VERSION="2.4.2 Debian-2.4.2-1.1" TIMESTAMP="" package_revision=1.3337 # Be Bourne compatible if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } # NLS nuisances: We save the old values to restore during execute mode. lt_user_locale= lt_safe_locale= for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${$lt_var+set}\" = set; then save_$lt_var=\$$lt_var $lt_var=C export $lt_var lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\" lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\" fi" done LC_ALL=C LANGUAGE=C export LANGUAGE LC_ALL $lt_unset CDPATH # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh # is ksh but when the shell is invoked as "sh" and the current value of # the _XPG environment variable is not equal to 1 (one), the special # positional parameter $0, within a function call, is the name of the # function. progpath="$0" : ${CP="cp -f"} test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'} : ${MAKE="make"} : ${MKDIR="mkdir"} : ${MV="mv -f"} : ${RM="rm -f"} : ${SHELL="${CONFIG_SHELL-/bin/sh}"} : ${Xsed="$SED -e 1s/^X//"} # Global variables: EXIT_SUCCESS=0 EXIT_FAILURE=1 EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. exit_status=$EXIT_SUCCESS # Make sure IFS has a sensible default lt_nl=' ' IFS=" $lt_nl" dirname="s,/[^/]*$,," basename="s,^.*/,," # func_dirname file append nondir_replacement # Compute the dirname of FILE. If nonempty, add APPEND to the result, # otherwise set result to NONDIR_REPLACEMENT. func_dirname () { func_dirname_result=`$ECHO "${1}" | $SED "$dirname"` if test "X$func_dirname_result" = "X${1}"; then func_dirname_result="${3}" else func_dirname_result="$func_dirname_result${2}" fi } # func_dirname may be replaced by extended shell implementation # func_basename file func_basename () { func_basename_result=`$ECHO "${1}" | $SED "$basename"` } # func_basename may be replaced by extended shell implementation # func_dirname_and_basename file append nondir_replacement # perform func_basename and func_dirname in a single function # call: # dirname: Compute the dirname of FILE. If nonempty, # add APPEND to the result, otherwise set result # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. # value retuned in "$func_basename_result" # Implementation must be kept synchronized with func_dirname # and func_basename. For efficiency, we do not delegate to # those functions but instead duplicate the functionality here. func_dirname_and_basename () { # Extract subdirectory from the argument. func_dirname_result=`$ECHO "${1}" | $SED -e "$dirname"` if test "X$func_dirname_result" = "X${1}"; then func_dirname_result="${3}" else func_dirname_result="$func_dirname_result${2}" fi func_basename_result=`$ECHO "${1}" | $SED -e "$basename"` } # func_dirname_and_basename may be replaced by extended shell implementation # func_stripname prefix suffix name # strip PREFIX and SUFFIX off of NAME. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). # func_strip_suffix prefix name func_stripname () { case ${2} in .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; esac } # func_stripname may be replaced by extended shell implementation # These SED scripts presuppose an absolute path with a trailing slash. pathcar='s,^/\([^/]*\).*$,\1,' pathcdr='s,^/[^/]*,,' removedotparts=':dotsl s@/\./@/@g t dotsl s,/\.$,/,' collapseslashes='s@/\{1,\}@/@g' finalslash='s,/*$,/,' # func_normal_abspath PATH # Remove doubled-up and trailing slashes, "." path components, # and cancel out any ".." path components in PATH after making # it an absolute path. # value returned in "$func_normal_abspath_result" func_normal_abspath () { # Start from root dir and reassemble the path. func_normal_abspath_result= func_normal_abspath_tpath=$1 func_normal_abspath_altnamespace= case $func_normal_abspath_tpath in "") # Empty path, that just means $cwd. func_stripname '' '/' "`pwd`" func_normal_abspath_result=$func_stripname_result return ;; # The next three entries are used to spot a run of precisely # two leading slashes without using negated character classes; # we take advantage of case's first-match behaviour. ///*) # Unusual form of absolute path, do nothing. ;; //*) # Not necessarily an ordinary path; POSIX reserves leading '//' # and for example Cygwin uses it to access remote file shares # over CIFS/SMB, so we conserve a leading double slash if found. func_normal_abspath_altnamespace=/ ;; /*) # Absolute path, do nothing. ;; *) # Relative path, prepend $cwd. func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath ;; esac # Cancel out all the simple stuff to save iterations. We also want # the path to end with a slash for ease of parsing, so make sure # there is one (and only one) here. func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"` while :; do # Processed it all yet? if test "$func_normal_abspath_tpath" = / ; then # If we ascended to the root using ".." the result may be empty now. if test -z "$func_normal_abspath_result" ; then func_normal_abspath_result=/ fi break fi func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$pathcar"` func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$pathcdr"` # Figure out what to do with it case $func_normal_abspath_tcomponent in "") # Trailing empty path component, ignore it. ;; ..) # Parent dir; strip last assembled component from result. func_dirname "$func_normal_abspath_result" func_normal_abspath_result=$func_dirname_result ;; *) # Actual path component, append it. func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent ;; esac done # Restore leading double-slash if one was found on entry. func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result } # func_relative_path SRCDIR DSTDIR # generates a relative path from SRCDIR to DSTDIR, with a trailing # slash if non-empty, suitable for immediately appending a filename # without needing to append a separator. # value returned in "$func_relative_path_result" func_relative_path () { func_relative_path_result= func_normal_abspath "$1" func_relative_path_tlibdir=$func_normal_abspath_result func_normal_abspath "$2" func_relative_path_tbindir=$func_normal_abspath_result # Ascend the tree starting from libdir while :; do # check if we have found a prefix of bindir case $func_relative_path_tbindir in $func_relative_path_tlibdir) # found an exact match func_relative_path_tcancelled= break ;; $func_relative_path_tlibdir*) # found a matching prefix func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir" func_relative_path_tcancelled=$func_stripname_result if test -z "$func_relative_path_result"; then func_relative_path_result=. fi break ;; *) func_dirname $func_relative_path_tlibdir func_relative_path_tlibdir=${func_dirname_result} if test "x$func_relative_path_tlibdir" = x ; then # Have to descend all the way to the root! func_relative_path_result=../$func_relative_path_result func_relative_path_tcancelled=$func_relative_path_tbindir break fi func_relative_path_result=../$func_relative_path_result ;; esac done # Now calculate path; take care to avoid doubling-up slashes. func_stripname '' '/' "$func_relative_path_result" func_relative_path_result=$func_stripname_result func_stripname '/' '/' "$func_relative_path_tcancelled" if test "x$func_stripname_result" != x ; then func_relative_path_result=${func_relative_path_result}/${func_stripname_result} fi # Normalisation. If bindir is libdir, return empty string, # else relative path ending with a slash; either way, target # file name can be directly appended. if test ! -z "$func_relative_path_result"; then func_stripname './' '' "$func_relative_path_result/" func_relative_path_result=$func_stripname_result fi } # The name of this program: func_dirname_and_basename "$progpath" progname=$func_basename_result # Make sure we have an absolute path for reexecution: case $progpath in [\\/]*|[A-Za-z]:\\*) ;; *[\\/]*) progdir=$func_dirname_result progdir=`cd "$progdir" && pwd` progpath="$progdir/$progname" ;; *) save_IFS="$IFS" IFS=${PATH_SEPARATOR-:} for progdir in $PATH; do IFS="$save_IFS" test -x "$progdir/$progname" && break done IFS="$save_IFS" test -n "$progdir" || progdir=`pwd` progpath="$progdir/$progname" ;; esac # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. Xsed="${SED}"' -e 1s/^X//' sed_quote_subst='s/\([`"$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution that turns a string into a regex matching for the # string literally. sed_make_literal_regex='s,[].[^$\\*\/],\\&,g' # Sed substitution that converts a w32 file name or path # which contains forward slashes, into one that contains # (escaped) backslashes. A very naive implementation. lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' # Re-`\' parameter expansions in output of double_quote_subst that were # `\'-ed in input to the same. If an odd number of `\' preceded a '$' # in input to double_quote_subst, that '$' was protected from expansion. # Since each input `\' is now two `\'s, look for any number of runs of # four `\'s followed by two `\'s and then a '$'. `\' that '$'. bs='\\' bs2='\\\\' bs4='\\\\\\\\' dollar='\$' sed_double_backslash="\ s/$bs4/&\\ /g s/^$bs2$dollar/$bs&/ s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g s/\n//g" # Standard options: opt_dry_run=false opt_help=false opt_quiet=false opt_verbose=false opt_warning=: # func_echo arg... # Echo program name prefixed message, along with the current mode # name if it has been set yet. func_echo () { $ECHO "$progname: ${opt_mode+$opt_mode: }$*" } # func_verbose arg... # Echo program name prefixed message in verbose mode only. func_verbose () { $opt_verbose && func_echo ${1+"$@"} # A bug in bash halts the script if the last line of a function # fails when set -e is in force, so we need another command to # work around that: : } # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } # func_error arg... # Echo program name prefixed message to standard error. func_error () { $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2 } # func_warning arg... # Echo program name prefixed warning message to standard error. func_warning () { $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2 # bash bug again: : } # func_fatal_error arg... # Echo program name prefixed message to standard error, and exit. func_fatal_error () { func_error ${1+"$@"} exit $EXIT_FAILURE } # func_fatal_help arg... # Echo program name prefixed message to standard error, followed by # a help hint, and exit. func_fatal_help () { func_error ${1+"$@"} func_fatal_error "$help" } help="Try \`$progname --help' for more information." ## default # func_grep expression filename # Check whether EXPRESSION matches any line of FILENAME, without output. func_grep () { $GREP "$1" "$2" >/dev/null 2>&1 } # func_mkdir_p directory-path # Make sure the entire path to DIRECTORY-PATH is available. func_mkdir_p () { my_directory_path="$1" my_dir_list= if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then # Protect directory names starting with `-' case $my_directory_path in -*) my_directory_path="./$my_directory_path" ;; esac # While some portion of DIR does not yet exist... while test ! -d "$my_directory_path"; do # ...make a list in topmost first order. Use a colon delimited # list incase some portion of path contains whitespace. my_dir_list="$my_directory_path:$my_dir_list" # If the last portion added has no slash in it, the list is done case $my_directory_path in */*) ;; *) break ;; esac # ...otherwise throw away the child directory and loop my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"` done my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'` save_mkdir_p_IFS="$IFS"; IFS=':' for my_dir in $my_dir_list; do IFS="$save_mkdir_p_IFS" # mkdir can fail with a `File exist' error if two processes # try to create one of the directories concurrently. Don't # stop in that case! $MKDIR "$my_dir" 2>/dev/null || : done IFS="$save_mkdir_p_IFS" # Bail out if we (or some other process) failed to create a directory. test -d "$my_directory_path" || \ func_fatal_error "Failed to create \`$1'" fi } # func_mktempdir [string] # Make a temporary directory that won't clash with other running # libtool processes, and avoids race conditions if possible. If # given, STRING is the basename for that directory. func_mktempdir () { my_template="${TMPDIR-/tmp}/${1-$progname}" if test "$opt_dry_run" = ":"; then # Return a directory name, but don't create it in dry-run mode my_tmpdir="${my_template}-$$" else # If mktemp works, use that first and foremost my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` if test ! -d "$my_tmpdir"; then # Failing that, at least try and use $RANDOM to avoid a race my_tmpdir="${my_template}-${RANDOM-0}$$" save_mktempdir_umask=`umask` umask 0077 $MKDIR "$my_tmpdir" umask $save_mktempdir_umask fi # If we're not in dry-run mode, bomb out on failure test -d "$my_tmpdir" || \ func_fatal_error "cannot create temporary directory \`$my_tmpdir'" fi $ECHO "$my_tmpdir" } # func_quote_for_eval arg # Aesthetically quote ARG to be evaled later. # This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT # is double-quoted, suitable for a subsequent eval, whereas # FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters # which are still active within double quotes backslashified. func_quote_for_eval () { case $1 in *[\\\`\"\$]*) func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;; *) func_quote_for_eval_unquoted_result="$1" ;; esac case $func_quote_for_eval_unquoted_result in # Double-quote args containing shell metacharacters to delay # word splitting, command substitution and and variable # expansion for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\"" ;; *) func_quote_for_eval_result="$func_quote_for_eval_unquoted_result" esac } # func_quote_for_expand arg # Aesthetically quote ARG to be evaled later; same as above, # but do not quote variable references. func_quote_for_expand () { case $1 in *[\\\`\"]*) my_arg=`$ECHO "$1" | $SED \ -e "$double_quote_subst" -e "$sed_double_backslash"` ;; *) my_arg="$1" ;; esac case $my_arg in # Double-quote args containing shell metacharacters to delay # word splitting and command substitution for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") my_arg="\"$my_arg\"" ;; esac func_quote_for_expand_result="$my_arg" } # func_show_eval cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. func_show_eval () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$my_cmd" my_status=$? if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_show_eval_locale cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. Use the saved locale for evaluation. func_show_eval_locale () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$lt_user_locale $my_cmd" my_status=$? eval "$lt_safe_locale" if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_tr_sh # Turn $1 into a string suitable for a shell variable name. # Result is stored in $func_tr_sh_result. All characters # not in the set a-zA-Z0-9_ are replaced with '_'. Further, # if $1 begins with a digit, a '_' is prepended as well. func_tr_sh () { case $1 in [0-9]* | *[!a-zA-Z0-9_]*) func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'` ;; * ) func_tr_sh_result=$1 ;; esac } # func_version # Echo version message to standard output and exit. func_version () { $opt_debug $SED -n '/(C)/!b go :more /\./!{ N s/\n# / / b more } :go /^# '$PROGRAM' (GNU /,/# warranty; / { s/^# // s/^# *$// s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/ p }' < "$progpath" exit $? } # func_usage # Echo short help message to standard output and exit. func_usage () { $opt_debug $SED -n '/^# Usage:/,/^# *.*--help/ { s/^# // s/^# *$// s/\$progname/'$progname'/ p }' < "$progpath" echo $ECHO "run \`$progname --help | more' for full usage" exit $? } # func_help [NOEXIT] # Echo long help message to standard output and exit, # unless 'noexit' is passed as argument. func_help () { $opt_debug $SED -n '/^# Usage:/,/# Report bugs to/ { :print s/^# // s/^# *$// s*\$progname*'$progname'* s*\$host*'"$host"'* s*\$SHELL*'"$SHELL"'* s*\$LTCC*'"$LTCC"'* s*\$LTCFLAGS*'"$LTCFLAGS"'* s*\$LD*'"$LD"'* s/\$with_gnu_ld/'"$with_gnu_ld"'/ s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/ s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/ p d } /^# .* home page:/b print /^# General help using/b print ' < "$progpath" ret=$? if test -z "$1"; then exit $ret fi } # func_missing_arg argname # Echo program name prefixed message to standard error and set global # exit_cmd. func_missing_arg () { $opt_debug func_error "missing argument for $1." exit_cmd=exit } # func_split_short_opt shortopt # Set func_split_short_opt_name and func_split_short_opt_arg shell # variables after splitting SHORTOPT after the 2nd character. func_split_short_opt () { my_sed_short_opt='1s/^\(..\).*$/\1/;q' my_sed_short_rest='1s/^..\(.*\)$/\1/;q' func_split_short_opt_name=`$ECHO "$1" | $SED "$my_sed_short_opt"` func_split_short_opt_arg=`$ECHO "$1" | $SED "$my_sed_short_rest"` } # func_split_short_opt may be replaced by extended shell implementation # func_split_long_opt longopt # Set func_split_long_opt_name and func_split_long_opt_arg shell # variables after splitting LONGOPT at the `=' sign. func_split_long_opt () { my_sed_long_opt='1s/^\(--[^=]*\)=.*/\1/;q' my_sed_long_arg='1s/^--[^=]*=//' func_split_long_opt_name=`$ECHO "$1" | $SED "$my_sed_long_opt"` func_split_long_opt_arg=`$ECHO "$1" | $SED "$my_sed_long_arg"` } # func_split_long_opt may be replaced by extended shell implementation exit_cmd=: magic="%%%MAGIC variable%%%" magic_exe="%%%MAGIC EXE variable%%%" # Global variables. nonopt= preserve_args= lo2o="s/\\.lo\$/.${objext}/" o2lo="s/\\.${objext}\$/.lo/" extracted_archives= extracted_serial=0 # If this variable is set in any of the actions, the command in it # will be execed at the end. This prevents here-documents from being # left over by shells. exec_cmd= # func_append var value # Append VALUE to the end of shell variable VAR. func_append () { eval "${1}=\$${1}\${2}" } # func_append may be replaced by extended shell implementation # func_append_quoted var value # Quote VALUE and append to the end of shell variable VAR, separated # by a space. func_append_quoted () { func_quote_for_eval "${2}" eval "${1}=\$${1}\\ \$func_quote_for_eval_result" } # func_append_quoted may be replaced by extended shell implementation # func_arith arithmetic-term... func_arith () { func_arith_result=`expr "${@}"` } # func_arith may be replaced by extended shell implementation # func_len string # STRING may not start with a hyphen. func_len () { func_len_result=`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len` } # func_len may be replaced by extended shell implementation # func_lo2o object func_lo2o () { func_lo2o_result=`$ECHO "${1}" | $SED "$lo2o"` } # func_lo2o may be replaced by extended shell implementation # func_xform libobj-or-source func_xform () { func_xform_result=`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'` } # func_xform may be replaced by extended shell implementation # func_fatal_configuration arg... # Echo program name prefixed message to standard error, followed by # a configuration failure hint, and exit. func_fatal_configuration () { func_error ${1+"$@"} func_error "See the $PACKAGE documentation for more information." func_fatal_error "Fatal configuration error." } # func_config # Display the configuration for all the tags in this script. func_config () { re_begincf='^# ### BEGIN LIBTOOL' re_endcf='^# ### END LIBTOOL' # Default configuration. $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" # Now print the configurations for the tags. for tagname in $taglist; do $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" done exit $? } # func_features # Display the features supported by this script. func_features () { echo "host: $host" if test "$build_libtool_libs" = yes; then echo "enable shared libraries" else echo "disable shared libraries" fi if test "$build_old_libs" = yes; then echo "enable static libraries" else echo "disable static libraries" fi exit $? } # func_enable_tag tagname # Verify that TAGNAME is valid, and either flag an error and exit, or # enable the TAGNAME tag. We also add TAGNAME to the global $taglist # variable here. func_enable_tag () { # Global variable: tagname="$1" re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" sed_extractcf="/$re_begincf/,/$re_endcf/p" # Validate tagname. case $tagname in *[!-_A-Za-z0-9,/]*) func_fatal_error "invalid tag name: $tagname" ;; esac # Don't test for the "default" C tag, as we know it's # there but not specially marked. case $tagname in CC) ;; *) if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then taglist="$taglist $tagname" # Evaluate the configuration. Be careful to quote the path # and the sed script, to avoid splitting on whitespace, but # also don't use non-portable quotes within backquotes within # quotes we have to do it in 2 steps: extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` eval "$extractedcf" else func_error "ignoring unknown tag $tagname" fi ;; esac } # func_check_version_match # Ensure that we are using m4 macros, and libtool script from the same # release of libtool. func_check_version_match () { if test "$package_revision" != "$macro_revision"; then if test "$VERSION" != "$macro_version"; then if test -z "$macro_version"; then cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from an older release. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from $PACKAGE $macro_version. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF fi else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, $progname: but the definition of this LT_INIT comes from revision $macro_revision. $progname: You should recreate aclocal.m4 with macros from revision $package_revision $progname: of $PACKAGE $VERSION and run autoconf again. _LT_EOF fi exit $EXIT_MISMATCH fi } # Shorthand for --mode=foo, only valid as the first argument case $1 in clean|clea|cle|cl) shift; set dummy --mode clean ${1+"$@"}; shift ;; compile|compil|compi|comp|com|co|c) shift; set dummy --mode compile ${1+"$@"}; shift ;; execute|execut|execu|exec|exe|ex|e) shift; set dummy --mode execute ${1+"$@"}; shift ;; finish|finis|fini|fin|fi|f) shift; set dummy --mode finish ${1+"$@"}; shift ;; install|instal|insta|inst|ins|in|i) shift; set dummy --mode install ${1+"$@"}; shift ;; link|lin|li|l) shift; set dummy --mode link ${1+"$@"}; shift ;; uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) shift; set dummy --mode uninstall ${1+"$@"}; shift ;; esac # Option defaults: opt_debug=: opt_dry_run=false opt_config=false opt_preserve_dup_deps=false opt_features=false opt_finish=false opt_help=false opt_help_all=false opt_silent=: opt_warning=: opt_verbose=: opt_silent=false opt_verbose=false # Parse options once, thoroughly. This comes as soon as possible in the # script to make things like `--version' happen as quickly as we can. { # this just eases exit handling while test $# -gt 0; do opt="$1" shift case $opt in --debug|-x) opt_debug='set -x' func_echo "enabling shell trace mode" $opt_debug ;; --dry-run|--dryrun|-n) opt_dry_run=: ;; --config) opt_config=: func_config ;; --dlopen|-dlopen) optarg="$1" opt_dlopen="${opt_dlopen+$opt_dlopen }$optarg" shift ;; --preserve-dup-deps) opt_preserve_dup_deps=: ;; --features) opt_features=: func_features ;; --finish) opt_finish=: set dummy --mode finish ${1+"$@"}; shift ;; --help) opt_help=: ;; --help-all) opt_help_all=: opt_help=': help-all' ;; --mode) test $# = 0 && func_missing_arg $opt && break optarg="$1" opt_mode="$optarg" case $optarg in # Valid mode arguments: clean|compile|execute|finish|install|link|relink|uninstall) ;; # Catch anything else as an error *) func_error "invalid argument for $opt" exit_cmd=exit break ;; esac shift ;; --no-silent|--no-quiet) opt_silent=false func_append preserve_args " $opt" ;; --no-warning|--no-warn) opt_warning=false func_append preserve_args " $opt" ;; --no-verbose) opt_verbose=false func_append preserve_args " $opt" ;; --silent|--quiet) opt_silent=: func_append preserve_args " $opt" opt_verbose=false ;; --verbose|-v) opt_verbose=: func_append preserve_args " $opt" opt_silent=false ;; --tag) test $# = 0 && func_missing_arg $opt && break optarg="$1" opt_tag="$optarg" func_append preserve_args " $opt $optarg" func_enable_tag "$optarg" shift ;; -\?|-h) func_usage ;; --help) func_help ;; --version) func_version ;; # Separate optargs to long options: --*=*) func_split_long_opt "$opt" set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"} shift ;; # Separate non-argument short options: -\?*|-h*|-n*|-v*) func_split_short_opt "$opt" set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"} shift ;; --) break ;; -*) func_fatal_help "unrecognized option \`$opt'" ;; *) set dummy "$opt" ${1+"$@"}; shift; break ;; esac done # Validate options: # save first non-option argument if test "$#" -gt 0; then nonopt="$opt" shift fi # preserve --debug test "$opt_debug" = : || func_append preserve_args " --debug" case $host in *cygwin* | *mingw* | *pw32* | *cegcc*) # don't eliminate duplications in $postdeps and $predeps opt_duplicate_compiler_generated_deps=: ;; *) opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps ;; esac $opt_help || { # Sanity checks first: func_check_version_match if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then func_fatal_configuration "not configured to build any kind of library" fi # Darwin sucks eval std_shrext=\"$shrext_cmds\" # Only execute mode is allowed to have -dlopen flags. if test -n "$opt_dlopen" && test "$opt_mode" != execute; then func_error "unrecognized option \`-dlopen'" $ECHO "$help" 1>&2 exit $EXIT_FAILURE fi # Change the help message to a mode-specific one. generic_help="$help" help="Try \`$progname --help --mode=$opt_mode' for more information." } # Bail if the options were screwed $exit_cmd $EXIT_FAILURE } ## ----------- ## ## Main. ## ## ----------- ## # func_lalib_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_lalib_p () { test -f "$1" && $SED -e 4q "$1" 2>/dev/null \ | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 } # func_lalib_unsafe_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function implements the same check as func_lalib_p without # resorting to external programs. To this end, it redirects stdin and # closes it afterwards, without saving the original file descriptor. # As a safety measure, use it only where a negative result would be # fatal anyway. Works if `file' does not exist. func_lalib_unsafe_p () { lalib_p=no if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then for lalib_p_l in 1 2 3 4 do read lalib_p_line case "$lalib_p_line" in \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; esac done exec 0<&5 5<&- fi test "$lalib_p" = yes } # func_ltwrapper_script_p file # True iff FILE is a libtool wrapper script # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_script_p () { func_lalib_p "$1" } # func_ltwrapper_executable_p file # True iff FILE is a libtool wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_executable_p () { func_ltwrapper_exec_suffix= case $1 in *.exe) ;; *) func_ltwrapper_exec_suffix=.exe ;; esac $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 } # func_ltwrapper_scriptname file # Assumes file is an ltwrapper_executable # uses $file to determine the appropriate filename for a # temporary ltwrapper_script. func_ltwrapper_scriptname () { func_dirname_and_basename "$1" "" "." func_stripname '' '.exe' "$func_basename_result" func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper" } # func_ltwrapper_p file # True iff FILE is a libtool wrapper script or wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_p () { func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" } # func_execute_cmds commands fail_cmd # Execute tilde-delimited COMMANDS. # If FAIL_CMD is given, eval that upon failure. # FAIL_CMD may read-access the current command in variable CMD! func_execute_cmds () { $opt_debug save_ifs=$IFS; IFS='~' for cmd in $1; do IFS=$save_ifs eval cmd=\"$cmd\" func_show_eval "$cmd" "${2-:}" done IFS=$save_ifs } # func_source file # Source FILE, adding directory component if necessary. # Note that it is not necessary on cygwin/mingw to append a dot to # FILE even if both FILE and FILE.exe exist: automatic-append-.exe # behavior happens only for exec(3), not for open(2)! Also, sourcing # `FILE.' does not work on cygwin managed mounts. func_source () { $opt_debug case $1 in */* | *\\*) . "$1" ;; *) . "./$1" ;; esac } # func_resolve_sysroot PATH # Replace a leading = in PATH with a sysroot. Store the result into # func_resolve_sysroot_result func_resolve_sysroot () { func_resolve_sysroot_result=$1 case $func_resolve_sysroot_result in =*) func_stripname '=' '' "$func_resolve_sysroot_result" func_resolve_sysroot_result=$lt_sysroot$func_stripname_result ;; esac } # func_replace_sysroot PATH # If PATH begins with the sysroot, replace it with = and # store the result into func_replace_sysroot_result. func_replace_sysroot () { case "$lt_sysroot:$1" in ?*:"$lt_sysroot"*) func_stripname "$lt_sysroot" '' "$1" func_replace_sysroot_result="=$func_stripname_result" ;; *) # Including no sysroot. func_replace_sysroot_result=$1 ;; esac } # func_infer_tag arg # Infer tagged configuration to use if any are available and # if one wasn't chosen via the "--tag" command line option. # Only attempt this if the compiler in the base compile # command doesn't match the default compiler. # arg is usually of the form 'gcc ...' func_infer_tag () { $opt_debug if test -n "$available_tags" && test -z "$tagname"; then CC_quoted= for arg in $CC; do func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case $@ in # Blanks in the command may have been stripped by the calling shell, # but not from the CC environment variable when configure was run. " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;; # Blanks at the start of $base_compile will cause this to fail # if we don't check for them as well. *) for z in $available_tags; do if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then # Evaluate the configuration. eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" CC_quoted= for arg in $CC; do # Double-quote args containing other shell metacharacters. func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case "$@ " in " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) # The compiler in the base compile command matches # the one in the tagged configuration. # Assume this is the tagged configuration we want. tagname=$z break ;; esac fi done # If $tagname still isn't set, then no tagged configuration # was found and let the user know that the "--tag" command # line option must be used. if test -z "$tagname"; then func_echo "unable to infer tagged configuration" func_fatal_error "specify a tag with \`--tag'" # else # func_verbose "using $tagname tagged configuration" fi ;; esac fi } # func_write_libtool_object output_name pic_name nonpic_name # Create a libtool object file (analogous to a ".la" file), # but don't create it if we're doing a dry run. func_write_libtool_object () { write_libobj=${1} if test "$build_libtool_libs" = yes; then write_lobj=\'${2}\' else write_lobj=none fi if test "$build_old_libs" = yes; then write_oldobj=\'${3}\' else write_oldobj=none fi $opt_dry_run || { cat >${write_libobj}T </dev/null` if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" | $SED -e "$lt_sed_naive_backslashify"` else func_convert_core_file_wine_to_w32_result= fi fi } # end: func_convert_core_file_wine_to_w32 # func_convert_core_path_wine_to_w32 ARG # Helper function used by path conversion functions when $build is *nix, and # $host is mingw, cygwin, or some other w32 environment. Relies on a correctly # configured wine environment available, with the winepath program in $build's # $PATH. Assumes ARG has no leading or trailing path separator characters. # # ARG is path to be converted from $build format to win32. # Result is available in $func_convert_core_path_wine_to_w32_result. # Unconvertible file (directory) names in ARG are skipped; if no directory names # are convertible, then the result may be empty. func_convert_core_path_wine_to_w32 () { $opt_debug # unfortunately, winepath doesn't convert paths, only file names func_convert_core_path_wine_to_w32_result="" if test -n "$1"; then oldIFS=$IFS IFS=: for func_convert_core_path_wine_to_w32_f in $1; do IFS=$oldIFS func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f" if test -n "$func_convert_core_file_wine_to_w32_result" ; then if test -z "$func_convert_core_path_wine_to_w32_result"; then func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result" else func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result" fi fi done IFS=$oldIFS fi } # end: func_convert_core_path_wine_to_w32 # func_cygpath ARGS... # Wrapper around calling the cygpath program via LT_CYGPATH. This is used when # when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2) # $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or # (2), returns the Cygwin file name or path in func_cygpath_result (input # file name or path is assumed to be in w32 format, as previously converted # from $build's *nix or MSYS format). In case (3), returns the w32 file name # or path in func_cygpath_result (input file name or path is assumed to be in # Cygwin format). Returns an empty string on error. # # ARGS are passed to cygpath, with the last one being the file name or path to # be converted. # # Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH # environment variable; do not put it in $PATH. func_cygpath () { $opt_debug if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null` if test "$?" -ne 0; then # on failure, ensure result is empty func_cygpath_result= fi else func_cygpath_result= func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'" fi } #end: func_cygpath # func_convert_core_msys_to_w32 ARG # Convert file name or path ARG from MSYS format to w32 format. Return # result in func_convert_core_msys_to_w32_result. func_convert_core_msys_to_w32 () { $opt_debug # awkward: cmd appends spaces to result func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null | $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"` } #end: func_convert_core_msys_to_w32 # func_convert_file_check ARG1 ARG2 # Verify that ARG1 (a file name in $build format) was converted to $host # format in ARG2. Otherwise, emit an error message, but continue (resetting # func_to_host_file_result to ARG1). func_convert_file_check () { $opt_debug if test -z "$2" && test -n "$1" ; then func_error "Could not determine host file name corresponding to" func_error " \`$1'" func_error "Continuing, but uninstalled executables may not work." # Fallback: func_to_host_file_result="$1" fi } # end func_convert_file_check # func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH # Verify that FROM_PATH (a path in $build format) was converted to $host # format in TO_PATH. Otherwise, emit an error message, but continue, resetting # func_to_host_file_result to a simplistic fallback value (see below). func_convert_path_check () { $opt_debug if test -z "$4" && test -n "$3"; then func_error "Could not determine the host path corresponding to" func_error " \`$3'" func_error "Continuing, but uninstalled executables may not work." # Fallback. This is a deliberately simplistic "conversion" and # should not be "improved". See libtool.info. if test "x$1" != "x$2"; then lt_replace_pathsep_chars="s|$1|$2|g" func_to_host_path_result=`echo "$3" | $SED -e "$lt_replace_pathsep_chars"` else func_to_host_path_result="$3" fi fi } # end func_convert_path_check # func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG # Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT # and appending REPL if ORIG matches BACKPAT. func_convert_path_front_back_pathsep () { $opt_debug case $4 in $1 ) func_to_host_path_result="$3$func_to_host_path_result" ;; esac case $4 in $2 ) func_append func_to_host_path_result "$3" ;; esac } # end func_convert_path_front_back_pathsep ################################################## # $build to $host FILE NAME CONVERSION FUNCTIONS # ################################################## # invoked via `$to_host_file_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # Result will be available in $func_to_host_file_result. # func_to_host_file ARG # Converts the file name ARG from $build format to $host format. Return result # in func_to_host_file_result. func_to_host_file () { $opt_debug $to_host_file_cmd "$1" } # end func_to_host_file # func_to_tool_file ARG LAZY # converts the file name ARG from $build format to toolchain format. Return # result in func_to_tool_file_result. If the conversion in use is listed # in (the comma separated) LAZY, no conversion takes place. func_to_tool_file () { $opt_debug case ,$2, in *,"$to_tool_file_cmd",*) func_to_tool_file_result=$1 ;; *) $to_tool_file_cmd "$1" func_to_tool_file_result=$func_to_host_file_result ;; esac } # end func_to_tool_file # func_convert_file_noop ARG # Copy ARG to func_to_host_file_result. func_convert_file_noop () { func_to_host_file_result="$1" } # end func_convert_file_noop # func_convert_file_msys_to_w32 ARG # Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_file_result. func_convert_file_msys_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_to_host_file_result="$func_convert_core_msys_to_w32_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_w32 # func_convert_file_cygwin_to_w32 ARG # Convert file name ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_file_cygwin_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then # because $build is cygwin, we call "the" cygpath in $PATH; no need to use # LT_CYGPATH in this case. func_to_host_file_result=`cygpath -m "$1"` fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_cygwin_to_w32 # func_convert_file_nix_to_w32 ARG # Convert file name ARG from *nix to w32 format. Requires a wine environment # and a working winepath. Returns result in func_to_host_file_result. func_convert_file_nix_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_file_wine_to_w32 "$1" func_to_host_file_result="$func_convert_core_file_wine_to_w32_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_w32 # func_convert_file_msys_to_cygwin ARG # Convert file name ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_file_msys_to_cygwin () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_cygpath -u "$func_convert_core_msys_to_w32_result" func_to_host_file_result="$func_cygpath_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_cygwin # func_convert_file_nix_to_cygwin ARG # Convert file name ARG from *nix to Cygwin format. Requires Cygwin installed # in a wine environment, working winepath, and LT_CYGPATH set. Returns result # in func_to_host_file_result. func_convert_file_nix_to_cygwin () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then # convert from *nix to w32, then use cygpath to convert from w32 to cygwin. func_convert_core_file_wine_to_w32 "$1" func_cygpath -u "$func_convert_core_file_wine_to_w32_result" func_to_host_file_result="$func_cygpath_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_cygwin ############################################# # $build to $host PATH CONVERSION FUNCTIONS # ############################################# # invoked via `$to_host_path_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # The result will be available in $func_to_host_path_result. # # Path separators are also converted from $build format to $host format. If # ARG begins or ends with a path separator character, it is preserved (but # converted to $host format) on output. # # All path conversion functions are named using the following convention: # file name conversion function : func_convert_file_X_to_Y () # path conversion function : func_convert_path_X_to_Y () # where, for any given $build/$host combination the 'X_to_Y' value is the # same. If conversion functions are added for new $build/$host combinations, # the two new functions must follow this pattern, or func_init_to_host_path_cmd # will break. # func_init_to_host_path_cmd # Ensures that function "pointer" variable $to_host_path_cmd is set to the # appropriate value, based on the value of $to_host_file_cmd. to_host_path_cmd= func_init_to_host_path_cmd () { $opt_debug if test -z "$to_host_path_cmd"; then func_stripname 'func_convert_file_' '' "$to_host_file_cmd" to_host_path_cmd="func_convert_path_${func_stripname_result}" fi } # func_to_host_path ARG # Converts the path ARG from $build format to $host format. Return result # in func_to_host_path_result. func_to_host_path () { $opt_debug func_init_to_host_path_cmd $to_host_path_cmd "$1" } # end func_to_host_path # func_convert_path_noop ARG # Copy ARG to func_to_host_path_result. func_convert_path_noop () { func_to_host_path_result="$1" } # end func_convert_path_noop # func_convert_path_msys_to_w32 ARG # Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_path_result. func_convert_path_msys_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # Remove leading and trailing path separator characters from ARG. MSYS # behavior is inconsistent here; cygpath turns them into '.;' and ';.'; # and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result="$func_convert_core_msys_to_w32_result" func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_msys_to_w32 # func_convert_path_cygwin_to_w32 ARG # Convert path ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_path_cygwin_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"` func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_cygwin_to_w32 # func_convert_path_nix_to_w32 ARG # Convert path ARG from *nix to w32 format. Requires a wine environment and # a working winepath. Returns result in func_to_host_file_result. func_convert_path_nix_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result="$func_convert_core_path_wine_to_w32_result" func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_nix_to_w32 # func_convert_path_msys_to_cygwin ARG # Convert path ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_path_msys_to_cygwin () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_msys_to_w32_result" func_to_host_path_result="$func_cygpath_result" func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_msys_to_cygwin # func_convert_path_nix_to_cygwin ARG # Convert path ARG from *nix to Cygwin format. Requires Cygwin installed in a # a wine environment, working winepath, and LT_CYGPATH set. Returns result in # func_to_host_file_result. func_convert_path_nix_to_cygwin () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # Remove leading and trailing path separator characters from # ARG. msys behavior is inconsistent here, cygpath turns them # into '.;' and ';.', and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result" func_to_host_path_result="$func_cygpath_result" func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_nix_to_cygwin # func_mode_compile arg... func_mode_compile () { $opt_debug # Get the compilation command and the source file. base_compile= srcfile="$nonopt" # always keep a non-empty value in "srcfile" suppress_opt=yes suppress_output= arg_mode=normal libobj= later= pie_flag= for arg do case $arg_mode in arg ) # do not "continue". Instead, add this to base_compile lastarg="$arg" arg_mode=normal ;; target ) libobj="$arg" arg_mode=normal continue ;; normal ) # Accept any command-line options. case $arg in -o) test -n "$libobj" && \ func_fatal_error "you cannot specify \`-o' more than once" arg_mode=target continue ;; -pie | -fpie | -fPIE) func_append pie_flag " $arg" continue ;; -shared | -static | -prefer-pic | -prefer-non-pic) func_append later " $arg" continue ;; -no-suppress) suppress_opt=no continue ;; -Xcompiler) arg_mode=arg # the next one goes into the "base_compile" arg list continue # The current "srcfile" will either be retained or ;; # replaced later. I would guess that would be a bug. -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result lastarg= save_ifs="$IFS"; IFS=',' for arg in $args; do IFS="$save_ifs" func_append_quoted lastarg "$arg" done IFS="$save_ifs" func_stripname ' ' '' "$lastarg" lastarg=$func_stripname_result # Add the arguments to base_compile. func_append base_compile " $lastarg" continue ;; *) # Accept the current argument as the source file. # The previous "srcfile" becomes the current argument. # lastarg="$srcfile" srcfile="$arg" ;; esac # case $arg ;; esac # case $arg_mode # Aesthetically quote the previous argument. func_append_quoted base_compile "$lastarg" done # for arg case $arg_mode in arg) func_fatal_error "you must specify an argument for -Xcompile" ;; target) func_fatal_error "you must specify a target with \`-o'" ;; *) # Get the name of the library object. test -z "$libobj" && { func_basename "$srcfile" libobj="$func_basename_result" } ;; esac # Recognize several different file suffixes. # If the user specifies -o file.o, it is replaced with file.lo case $libobj in *.[cCFSifmso] | \ *.ada | *.adb | *.ads | *.asm | \ *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup) func_xform "$libobj" libobj=$func_xform_result ;; esac case $libobj in *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; *) func_fatal_error "cannot determine name of library object from \`$libobj'" ;; esac func_infer_tag $base_compile for arg in $later; do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no continue ;; -static) build_libtool_libs=no build_old_libs=yes continue ;; -prefer-pic) pic_mode=yes continue ;; -prefer-non-pic) pic_mode=no continue ;; esac done func_quote_for_eval "$libobj" test "X$libobj" != "X$func_quote_for_eval_result" \ && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ && func_warning "libobj name \`$libobj' may not contain shell special characters." func_dirname_and_basename "$obj" "/" "" objname="$func_basename_result" xdir="$func_dirname_result" lobj=${xdir}$objdir/$objname test -z "$base_compile" && \ func_fatal_help "you must specify a compilation command" # Delete any leftover library objects. if test "$build_old_libs" = yes; then removelist="$obj $lobj $libobj ${libobj}T" else removelist="$lobj $libobj ${libobj}T" fi # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in cygwin* | mingw* | pw32* | os2* | cegcc*) pic_mode=default ;; esac if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then # non-PIC code in shared libraries is not supported pic_mode=default fi # Calculate the filename of the output object if compiler does # not support -o with -c if test "$compiler_c_o" = no; then output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext} lockfile="$output_obj.lock" else output_obj= need_locks=no lockfile= fi # Lock this critical section if it is needed # We use this script file to make the link, it avoids creating a new file if test "$need_locks" = yes; then until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done elif test "$need_locks" = warn; then if test -f "$lockfile"; then $ECHO "\ *** ERROR, $lockfile exists and contains: `cat $lockfile 2>/dev/null` This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi func_append removelist " $output_obj" $ECHO "$srcfile" > "$lockfile" fi $opt_dry_run || $RM $removelist func_append removelist " $lockfile" trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 func_to_tool_file "$srcfile" func_convert_file_msys_to_w32 srcfile=$func_to_tool_file_result func_quote_for_eval "$srcfile" qsrcfile=$func_quote_for_eval_result # Only build a PIC object if we are building libtool libraries. if test "$build_libtool_libs" = yes; then # Without this assignment, base_compile gets emptied. fbsd_hideous_sh_bug=$base_compile if test "$pic_mode" != no; then command="$base_compile $qsrcfile $pic_flag" else # Don't build PIC code command="$base_compile $qsrcfile" fi func_mkdir_p "$xdir$objdir" if test -z "$output_obj"; then # Place PIC objects in $objdir func_append command " -o $lobj" fi func_show_eval_locale "$command" \ 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed, then go on to compile the next one if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then func_show_eval '$MV "$output_obj" "$lobj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi # Allow error messages only from the first compilation. if test "$suppress_opt" = yes; then suppress_output=' >/dev/null 2>&1' fi fi # Only build a position-dependent object if we build old libraries. if test "$build_old_libs" = yes; then if test "$pic_mode" != yes; then # Don't build PIC code command="$base_compile $qsrcfile$pie_flag" else command="$base_compile $qsrcfile $pic_flag" fi if test "$compiler_c_o" = yes; then func_append command " -o $obj" fi # Suppress compiler output if we already did a PIC compilation. func_append command "$suppress_output" func_show_eval_locale "$command" \ '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then func_show_eval '$MV "$output_obj" "$obj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi fi $opt_dry_run || { func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" # Unlock the critical section if it was locked if test "$need_locks" != no; then removelist=$lockfile $RM "$lockfile" fi } exit $EXIT_SUCCESS } $opt_help || { test "$opt_mode" = compile && func_mode_compile ${1+"$@"} } func_mode_help () { # We need to display help for each of the modes. case $opt_mode in "") # Generic help is extracted from the usage comments # at the start of this file. func_help ;; clean) $ECHO \ "Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... Remove files from the build directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, object or program, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; compile) $ECHO \ "Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE Compile a source file into a libtool library object. This mode accepts the following additional options: -o OUTPUT-FILE set the output file name to OUTPUT-FILE -no-suppress do not suppress compiler output for multiple passes -prefer-pic try to build PIC objects only -prefer-non-pic try to build non-PIC objects only -shared do not build a \`.o' file suitable for static linking -static only build a \`.o' file suitable for static linking -Wc,FLAG pass FLAG directly to the compiler COMPILE-COMMAND is a command to be used in creating a \`standard' object file from the given SOURCEFILE. The output file name is determined by removing the directory component from SOURCEFILE, then substituting the C source code suffix \`.c' with the library object suffix, \`.lo'." ;; execute) $ECHO \ "Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... Automatically set library path, then run a program. This mode accepts the following additional options: -dlopen FILE add the directory containing FILE to the library path This mode sets the library path environment variable according to \`-dlopen' flags. If any of the ARGS are libtool executable wrappers, then they are translated into their corresponding uninstalled binary, and any of their required library directories are added to the library path. Then, COMMAND is executed, with ARGS as arguments." ;; finish) $ECHO \ "Usage: $progname [OPTION]... --mode=finish [LIBDIR]... Complete the installation of libtool libraries. Each LIBDIR is a directory that contains libtool libraries. The commands that this mode executes may require superuser privileges. Use the \`--dry-run' option if you just want to see what would be executed." ;; install) $ECHO \ "Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... Install executables or libraries. INSTALL-COMMAND is the installation command. The first component should be either the \`install' or \`cp' program. The following components of INSTALL-COMMAND are treated specially: -inst-prefix-dir PREFIX-DIR Use PREFIX-DIR as a staging area for installation The rest of the components are interpreted as arguments to that command (only BSD-compatible install options are recognized)." ;; link) $ECHO \ "Usage: $progname [OPTION]... --mode=link LINK-COMMAND... Link object files or libraries together to form another library, or to create an executable program. LINK-COMMAND is a command using the C compiler that you would use to create a program from several object files. The following components of LINK-COMMAND are treated specially: -all-static do not do any dynamic linking at all -avoid-version do not add a version suffix if possible -bindir BINDIR specify path to binaries directory (for systems where libraries must be found in the PATH setting at runtime) -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened -no-fast-install disable the fast-install mode -no-install link a not-installable executable -no-undefined declare that a library does not refer to external symbols -o OUTPUT-FILE create OUTPUT-FILE from the specified objects -objectlist FILE Use a list of object files found in FILE to specify objects -precious-files-regex REGEX don't remove output files matching REGEX -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries -shared only do dynamic linking of libtool libraries -shrext SUFFIX override the standard shared library file extension -static do not do any dynamic linking of uninstalled libtool libraries -static-libtool-libs do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] specify library version info [each variable defaults to 0] -weak LIBNAME declare that the target provides the LIBNAME interface -Wc,FLAG -Xcompiler FLAG pass linker-specific FLAG directly to the compiler -Wl,FLAG -Xlinker FLAG pass linker-specific FLAG directly to the linker -XCClinker FLAG pass link-specific FLAG to the compiler driver (CC) All other options (arguments beginning with \`-') are ignored. Every other argument is treated as a filename. Files ending in \`.la' are treated as uninstalled libtool libraries, other files are standard or library object files. If the OUTPUT-FILE ends in \`.la', then a libtool library is created, only library objects (\`.lo' files) may be specified, and \`-rpath' is required, except when creating a convenience library. If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created using \`ar' and \`ranlib', or on Windows using \`lib'. If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file is created, otherwise an executable program is created." ;; uninstall) $ECHO \ "Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... Remove libraries from an installation directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; *) func_fatal_help "invalid operation mode \`$opt_mode'" ;; esac echo $ECHO "Try \`$progname --help' for more information about other modes." } # Now that we've collected a possible --mode arg, show help if necessary if $opt_help; then if test "$opt_help" = :; then func_mode_help else { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do func_mode_help done } | sed -n '1p; 2,$s/^Usage:/ or: /p' { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do echo func_mode_help done } | sed '1d /^When reporting/,/^Report/{ H d } $x /information about other modes/d /more detailed .*MODE/d s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/' fi exit $? fi # func_mode_execute arg... func_mode_execute () { $opt_debug # The first argument is the command name. cmd="$nonopt" test -z "$cmd" && \ func_fatal_help "you must specify a COMMAND" # Handle -dlopen flags immediately. for file in $opt_dlopen; do test -f "$file" \ || func_fatal_help "\`$file' is not a file" dir= case $file in *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$lib' is not a valid libtool archive" # Read the libtool library. dlname= library_names= func_source "$file" # Skip this library if it cannot be dlopened. if test -z "$dlname"; then # Warn if it was a shared library. test -n "$library_names" && \ func_warning "\`$file' was not linked with \`-export-dynamic'" continue fi func_dirname "$file" "" "." dir="$func_dirname_result" if test -f "$dir/$objdir/$dlname"; then func_append dir "/$objdir" else if test ! -f "$dir/$dlname"; then func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" fi fi ;; *.lo) # Just add the directory containing the .lo file. func_dirname "$file" "" "." dir="$func_dirname_result" ;; *) func_warning "\`-dlopen' is ignored for non-libtool libraries and objects" continue ;; esac # Get the absolute pathname. absdir=`cd "$dir" && pwd` test -n "$absdir" && dir="$absdir" # Now add the directory to shlibpath_var. if eval "test -z \"\$$shlibpath_var\""; then eval "$shlibpath_var=\"\$dir\"" else eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" fi done # This variable tells wrapper scripts just to set shlibpath_var # rather than running their programs. libtool_execute_magic="$magic" # Check if any of the arguments is a wrapper script. args= for file do case $file in -* | *.la | *.lo ) ;; *) # Do a test to see if this is really a libtool program. if func_ltwrapper_script_p "$file"; then func_source "$file" # Transform arg to wrapped name. file="$progdir/$program" elif func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" func_source "$func_ltwrapper_scriptname_result" # Transform arg to wrapped name. file="$progdir/$program" fi ;; esac # Quote arguments (to preserve shell metacharacters). func_append_quoted args "$file" done if test "X$opt_dry_run" = Xfalse; then if test -n "$shlibpath_var"; then # Export the shlibpath_var. eval "export $shlibpath_var" fi # Restore saved environment variables for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${save_$lt_var+set}\" = set; then $lt_var=\$save_$lt_var; export $lt_var else $lt_unset $lt_var fi" done # Now prepare to actually exec the command. exec_cmd="\$cmd$args" else # Display what would be done. if test -n "$shlibpath_var"; then eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" echo "export $shlibpath_var" fi $ECHO "$cmd$args" exit $EXIT_SUCCESS fi } test "$opt_mode" = execute && func_mode_execute ${1+"$@"} # func_mode_finish arg... func_mode_finish () { $opt_debug libs= libdirs= admincmds= for opt in "$nonopt" ${1+"$@"} do if test -d "$opt"; then func_append libdirs " $opt" elif test -f "$opt"; then if func_lalib_unsafe_p "$opt"; then func_append libs " $opt" else func_warning "\`$opt' is not a valid libtool archive" fi else func_fatal_error "invalid argument \`$opt'" fi done if test -n "$libs"; then if test -n "$lt_sysroot"; then sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"` sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;" else sysroot_cmd= fi # Remove sysroot references if $opt_dry_run; then for lib in $libs; do echo "removing references to $lt_sysroot and \`=' prefixes from $lib" done else tmpdir=`func_mktempdir` for lib in $libs; do sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \ > $tmpdir/tmp-la mv -f $tmpdir/tmp-la $lib done ${RM}r "$tmpdir" fi fi if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. func_execute_cmds "$finish_cmds" 'admincmds="$admincmds '"$cmd"'"' fi if test -n "$finish_eval"; then # Do the single finish_eval. eval cmds=\"$finish_eval\" $opt_dry_run || eval "$cmds" || func_append admincmds " $cmds" fi done fi # Exit here if they wanted silent mode. $opt_silent && exit $EXIT_SUCCESS if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then echo "----------------------------------------------------------------------" echo "Libraries have been installed in:" for libdir in $libdirs; do $ECHO " $libdir" done echo echo "If you ever happen to want to link against installed libraries" echo "in a given directory, LIBDIR, you must either use libtool, and" echo "specify the full pathname of the library, or use the \`-LLIBDIR'" echo "flag during linking and do at least one of the following:" if test -n "$shlibpath_var"; then echo " - add LIBDIR to the \`$shlibpath_var' environment variable" echo " during execution" fi if test -n "$runpath_var"; then echo " - add LIBDIR to the \`$runpath_var' environment variable" echo " during linking" fi if test -n "$hardcode_libdir_flag_spec"; then libdir=LIBDIR eval flag=\"$hardcode_libdir_flag_spec\" $ECHO " - use the \`$flag' linker flag" fi if test -n "$admincmds"; then $ECHO " - have your system administrator run these commands:$admincmds" fi if test -f /etc/ld.so.conf; then echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" fi echo echo "See any operating system documentation about shared libraries for" case $host in solaris2.[6789]|solaris2.1[0-9]) echo "more information, such as the ld(1), crle(1) and ld.so(8) manual" echo "pages." ;; *) echo "more information, such as the ld(1) and ld.so(8) manual pages." ;; esac echo "----------------------------------------------------------------------" fi exit $EXIT_SUCCESS } test "$opt_mode" = finish && func_mode_finish ${1+"$@"} # func_mode_install arg... func_mode_install () { $opt_debug # There may be an optional sh(1) argument at the beginning of # install_prog (especially on Windows NT). if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || # Allow the use of GNU shtool's install command. case $nonopt in *shtool*) :;; *) false;; esac; then # Aesthetically quote it. func_quote_for_eval "$nonopt" install_prog="$func_quote_for_eval_result " arg=$1 shift else install_prog= arg=$nonopt fi # The real first argument should be the name of the installation program. # Aesthetically quote it. func_quote_for_eval "$arg" func_append install_prog "$func_quote_for_eval_result" install_shared_prog=$install_prog case " $install_prog " in *[\\\ /]cp\ *) install_cp=: ;; *) install_cp=false ;; esac # We need to accept at least all the BSD install flags. dest= files= opts= prev= install_type= isdir=no stripme= no_mode=: for arg do arg2= if test -n "$dest"; then func_append files " $dest" dest=$arg continue fi case $arg in -d) isdir=yes ;; -f) if $install_cp; then :; else prev=$arg fi ;; -g | -m | -o) prev=$arg ;; -s) stripme=" -s" continue ;; -*) ;; *) # If the previous option needed an argument, then skip it. if test -n "$prev"; then if test "x$prev" = x-m && test -n "$install_override_mode"; then arg2=$install_override_mode no_mode=false fi prev= else dest=$arg continue fi ;; esac # Aesthetically quote the argument. func_quote_for_eval "$arg" func_append install_prog " $func_quote_for_eval_result" if test -n "$arg2"; then func_quote_for_eval "$arg2" fi func_append install_shared_prog " $func_quote_for_eval_result" done test -z "$install_prog" && \ func_fatal_help "you must specify an install program" test -n "$prev" && \ func_fatal_help "the \`$prev' option requires an argument" if test -n "$install_override_mode" && $no_mode; then if $install_cp; then :; else func_quote_for_eval "$install_override_mode" func_append install_shared_prog " -m $func_quote_for_eval_result" fi fi if test -z "$files"; then if test -z "$dest"; then func_fatal_help "no file or destination specified" else func_fatal_help "you must specify a destination" fi fi # Strip any trailing slash from the destination. func_stripname '' '/' "$dest" dest=$func_stripname_result # Check to see that the destination is a directory. test -d "$dest" && isdir=yes if test "$isdir" = yes; then destdir="$dest" destname= else func_dirname_and_basename "$dest" "" "." destdir="$func_dirname_result" destname="$func_basename_result" # Not a directory, so check to see that there is only one file specified. set dummy $files; shift test "$#" -gt 1 && \ func_fatal_help "\`$dest' is not a directory" fi case $destdir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) for file in $files; do case $file in *.lo) ;; *) func_fatal_help "\`$destdir' must be an absolute directory name" ;; esac done ;; esac # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" staticlibs= future_libdirs= current_libdirs= for file in $files; do # Do each installation. case $file in *.$libext) # Do the static libraries later. func_append staticlibs " $file" ;; *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$file' is not a valid libtool archive" library_names= old_library= relink_command= func_source "$file" # Add the libdir to current_libdirs if it is the destination. if test "X$destdir" = "X$libdir"; then case "$current_libdirs " in *" $libdir "*) ;; *) func_append current_libdirs " $libdir" ;; esac else # Note the libdir as a future libdir. case "$future_libdirs " in *" $libdir "*) ;; *) func_append future_libdirs " $libdir" ;; esac fi func_dirname "$file" "/" "" dir="$func_dirname_result" func_append dir "$objdir" if test -n "$relink_command"; then # Determine the prefix the user has applied to our future dir. inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that # are installed to the same prefix. # At present, this check doesn't affect windows .dll's that # are installed into $libdir/../bin (currently, that works fine) # but it's something to keep an eye on. test "$inst_prefix_dir" = "$destdir" && \ func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` else relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"` fi func_warning "relinking \`$file'" func_show_eval "$relink_command" \ 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"' fi # See the names of the shared library. set dummy $library_names; shift if test -n "$1"; then realname="$1" shift srcname="$realname" test -n "$relink_command" && srcname="$realname"T # Install the shared library and build the symlinks. func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \ 'exit $?' tstripme="$stripme" case $host_os in cygwin* | mingw* | pw32* | cegcc*) case $realname in *.dll.a) tstripme="" ;; esac ;; esac if test -n "$tstripme" && test -n "$striplib"; then func_show_eval "$striplib $destdir/$realname" 'exit $?' fi if test "$#" -gt 0; then # Delete the old symlinks, and create new ones. # Try `ln -sf' first, because the `ln' binary might depend on # the symlink we replace! Solaris /bin/ln does not understand -f, # so we also need to try rm && ln -s. for linkname do test "$linkname" != "$realname" \ && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" done fi # Do each command in the postinstall commands. lib="$destdir/$realname" func_execute_cmds "$postinstall_cmds" 'exit $?' fi # Install the pseudo-library for information purposes. func_basename "$file" name="$func_basename_result" instname="$dir/$name"i func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' # Maybe install the static library, too. test -n "$old_library" && func_append staticlibs " $dir/$old_library" ;; *.lo) # Install (i.e. copy) a libtool object. # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # Deduce the name of the destination old-style object file. case $destfile in *.lo) func_lo2o "$destfile" staticdest=$func_lo2o_result ;; *.$objext) staticdest="$destfile" destfile= ;; *) func_fatal_help "cannot copy a libtool object to \`$destfile'" ;; esac # Install the libtool object if requested. test -n "$destfile" && \ func_show_eval "$install_prog $file $destfile" 'exit $?' # Install the old object if enabled. if test "$build_old_libs" = yes; then # Deduce the name of the old-style object file. func_lo2o "$file" staticobj=$func_lo2o_result func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' fi exit $EXIT_SUCCESS ;; *) # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # If the file is missing, and there is a .exe on the end, strip it # because it is most likely a libtool script we actually want to # install stripped_ext="" case $file in *.exe) if test ! -f "$file"; then func_stripname '' '.exe' "$file" file=$func_stripname_result stripped_ext=".exe" fi ;; esac # Do a test to see if this is really a libtool program. case $host in *cygwin* | *mingw*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result else func_stripname '' '.exe' "$file" wrapper=$func_stripname_result fi ;; *) wrapper=$file ;; esac if func_ltwrapper_script_p "$wrapper"; then notinst_deplibs= relink_command= func_source "$wrapper" # Check the variables that should have been set. test -z "$generated_by_libtool_version" && \ func_fatal_error "invalid libtool wrapper script \`$wrapper'" finalize=yes for lib in $notinst_deplibs; do # Check to see that each library is installed. libdir= if test -f "$lib"; then func_source "$lib" fi libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test if test -n "$libdir" && test ! -f "$libfile"; then func_warning "\`$lib' has not been installed in \`$libdir'" finalize=no fi done relink_command= func_source "$wrapper" outputname= if test "$fast_install" = no && test -n "$relink_command"; then $opt_dry_run || { if test "$finalize" = yes; then tmpdir=`func_mktempdir` func_basename "$file$stripped_ext" file="$func_basename_result" outputname="$tmpdir/$file" # Replace the output file specification. relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'` $opt_silent || { func_quote_for_expand "$relink_command" eval "func_echo $func_quote_for_expand_result" } if eval "$relink_command"; then : else func_error "error: relink \`$file' with the above command before installing it" $opt_dry_run || ${RM}r "$tmpdir" continue fi file="$outputname" else func_warning "cannot relink \`$file'" fi } else # Install the binary that we compiled earlier. file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"` fi fi # remove .exe since cygwin /usr/bin/install will append another # one anyway case $install_prog,$host in */usr/bin/install*,*cygwin*) case $file:$destfile in *.exe:*.exe) # this is ok ;; *.exe:*) destfile=$destfile.exe ;; *:*.exe) func_stripname '' '.exe' "$destfile" destfile=$func_stripname_result ;; esac ;; esac func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' $opt_dry_run || if test -n "$outputname"; then ${RM}r "$tmpdir" fi ;; esac done for file in $staticlibs; do func_basename "$file" name="$func_basename_result" # Set up the ranlib parameters. oldlib="$destdir/$name" func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result func_show_eval "$install_prog \$file \$oldlib" 'exit $?' if test -n "$stripme" && test -n "$old_striplib"; then func_show_eval "$old_striplib $tool_oldlib" 'exit $?' fi # Do each command in the postinstall commands. func_execute_cmds "$old_postinstall_cmds" 'exit $?' done test -n "$future_libdirs" && \ func_warning "remember to run \`$progname --finish$future_libdirs'" if test -n "$current_libdirs"; then # Maybe just do a dry run. $opt_dry_run && current_libdirs=" -n$current_libdirs" exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' else exit $EXIT_SUCCESS fi } test "$opt_mode" = install && func_mode_install ${1+"$@"} # func_generate_dlsyms outputname originator pic_p # Extract symbols from dlprefiles and create ${outputname}S.o with # a dlpreopen symbol table. func_generate_dlsyms () { $opt_debug my_outputname="$1" my_originator="$2" my_pic_p="${3-no}" my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'` my_dlsyms= if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then if test -n "$NM" && test -n "$global_symbol_pipe"; then my_dlsyms="${my_outputname}S.c" else func_error "not configured to extract global symbols from dlpreopened files" fi fi if test -n "$my_dlsyms"; then case $my_dlsyms in "") ;; *.c) # Discover the nlist of each of the dlfiles. nlist="$output_objdir/${my_outputname}.nm" func_show_eval "$RM $nlist ${nlist}S ${nlist}T" # Parse the name list into a source file. func_verbose "creating $output_objdir/$my_dlsyms" $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ /* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */ /* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */ #ifdef __cplusplus extern \"C\" { #endif #if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4)) #pragma GCC diagnostic ignored \"-Wstrict-prototypes\" #endif /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif /* External symbol declarations for the compiler. */\ " if test "$dlself" = yes; then func_verbose "generating symbol list for \`$output'" $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" # Add our own program objects to the symbol list. progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP` for progfile in $progfiles; do func_to_tool_file "$progfile" func_convert_file_msys_to_w32 func_verbose "extracting global C symbols from \`$func_to_tool_file_result'" $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'" done if test -n "$exclude_expsyms"; then $opt_dry_run || { eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi if test -n "$export_symbols_regex"; then $opt_dry_run || { eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi # Prepare the list of exported symbols if test -z "$export_symbols"; then export_symbols="$output_objdir/$outputname.exp" $opt_dry_run || { $RM $export_symbols eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; esac } else $opt_dry_run || { eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; esac } fi fi for dlprefile in $dlprefiles; do func_verbose "extracting global C symbols from \`$dlprefile'" func_basename "$dlprefile" name="$func_basename_result" case $host in *cygwin* | *mingw* | *cegcc* ) # if an import library, we need to obtain dlname if func_win32_import_lib_p "$dlprefile"; then func_tr_sh "$dlprefile" eval "curr_lafile=\$libfile_$func_tr_sh_result" dlprefile_dlbasename="" if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then # Use subshell, to avoid clobbering current variable values dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"` if test -n "$dlprefile_dlname" ; then func_basename "$dlprefile_dlname" dlprefile_dlbasename="$func_basename_result" else # no lafile. user explicitly requested -dlpreopen . $sharedlib_from_linklib_cmd "$dlprefile" dlprefile_dlbasename=$sharedlib_from_linklib_result fi fi $opt_dry_run || { if test -n "$dlprefile_dlbasename" ; then eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"' else func_warning "Could not compute DLL name from $name" eval '$ECHO ": $name " >> "$nlist"' fi func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" } else # not an import lib $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } fi ;; *) $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } ;; esac done $opt_dry_run || { # Make sure we have at least an empty file. test -f "$nlist" || : > "$nlist" if test -n "$exclude_expsyms"; then $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T $MV "$nlist"T "$nlist" fi # Try sorting and uniquifying the output. if $GREP -v "^: " < "$nlist" | if sort -k 3 /dev/null 2>&1; then sort -k 3 else sort +2 fi | uniq > "$nlist"S; then : else $GREP -v "^: " < "$nlist" > "$nlist"S fi if test -f "$nlist"S; then eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' else echo '/* NONE */' >> "$output_objdir/$my_dlsyms" fi echo >> "$output_objdir/$my_dlsyms" "\ /* The mapping between symbol names and symbols. */ typedef struct { const char *name; void *address; } lt_dlsymlist; extern LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[]; LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[] = {\ { \"$my_originator\", (void *) 0 }," case $need_lib_prefix in no) eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; *) eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; esac echo >> "$output_objdir/$my_dlsyms" "\ {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt_${my_prefix}_LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif\ " } # !$opt_dry_run pic_flag_for_symtable= case "$compile_command " in *" -static "*) ;; *) case $host in # compiling the symbol table file with pic_flag works around # a FreeBSD bug that causes programs to crash when -lm is # linked before any other PIC object. But we must not use # pic_flag when linking with -static. The problem exists in # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; *-*-hpux*) pic_flag_for_symtable=" $pic_flag" ;; *) if test "X$my_pic_p" != Xno; then pic_flag_for_symtable=" $pic_flag" fi ;; esac ;; esac symtab_cflags= for arg in $LTCFLAGS; do case $arg in -pie | -fpie | -fPIE) ;; *) func_append symtab_cflags " $arg" ;; esac done # Now compile the dynamic symbol file. func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' # Clean up the generated files. func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"' # Transform the symbol file into the correct name. symfileobj="$output_objdir/${my_outputname}S.$objext" case $host in *cygwin* | *mingw* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` else compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` fi ;; *) compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` ;; esac ;; *) func_fatal_error "unknown suffix for \`$my_dlsyms'" ;; esac else # We keep going just in case the user didn't refer to # lt_preloaded_symbols. The linker will fail if global_symbol_pipe # really was required. # Nullify the symbol file. compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"` finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"` fi } # func_win32_libid arg # return the library type of file 'arg' # # Need a lot of goo to handle *both* DLLs and import libs # Has to be a shell function in order to 'eat' the argument # that is supplied when $file_magic_command is called. # Despite the name, also deal with 64 bit binaries. func_win32_libid () { $opt_debug win32_libid_type="unknown" win32_fileres=`file -L $1 2>/dev/null` case $win32_fileres in *ar\ archive\ import\ library*) # definitely import win32_libid_type="x86 archive import" ;; *ar\ archive*) # could be an import, or static # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then func_to_tool_file "$1" func_convert_file_msys_to_w32 win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" | $SED -n -e ' 1,100{ / I /{ s,.*,import, p q } }'` case $win32_nmres in import*) win32_libid_type="x86 archive import";; *) win32_libid_type="x86 archive static";; esac fi ;; *DLL*) win32_libid_type="x86 DLL" ;; *executable*) # but shell scripts are "executable" too... case $win32_fileres in *MS\ Windows\ PE\ Intel*) win32_libid_type="x86 DLL" ;; esac ;; esac $ECHO "$win32_libid_type" } # func_cygming_dll_for_implib ARG # # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib () { $opt_debug sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"` } # func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs # # The is the core of a fallback implementation of a # platform-specific function to extract the name of the # DLL associated with the specified import library LIBNAME. # # SECTION_NAME is either .idata$6 or .idata$7, depending # on the platform and compiler that created the implib. # # Echos the name of the DLL associated with the # specified import library. func_cygming_dll_for_implib_fallback_core () { $opt_debug match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"` $OBJDUMP -s --section "$1" "$2" 2>/dev/null | $SED '/^Contents of section '"$match_literal"':/{ # Place marker at beginning of archive member dllname section s/.*/====MARK====/ p d } # These lines can sometimes be longer than 43 characters, but # are always uninteresting /:[ ]*file format pe[i]\{,1\}-/d /^In archive [^:]*:/d # Ensure marker is printed /^====MARK====/p # Remove all lines with less than 43 characters /^.\{43\}/!d # From remaining lines, remove first 43 characters s/^.\{43\}//' | $SED -n ' # Join marker and all lines until next marker into a single line /^====MARK====/ b para H $ b para b :para x s/\n//g # Remove the marker s/^====MARK====// # Remove trailing dots and whitespace s/[\. \t]*$// # Print /./p' | # we now have a list, one entry per line, of the stringified # contents of the appropriate section of all members of the # archive which possess that section. Heuristic: eliminate # all those which have a first or second character that is # a '.' (that is, objdump's representation of an unprintable # character.) This should work for all archives with less than # 0x302f exports -- but will fail for DLLs whose name actually # begins with a literal '.' or a single character followed by # a '.'. # # Of those that remain, print the first one. $SED -e '/^\./d;/^.\./d;q' } # func_cygming_gnu_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is a GNU/binutils-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_gnu_implib_p () { $opt_debug func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'` test -n "$func_cygming_gnu_implib_tmp" } # func_cygming_ms_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is an MS-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_ms_implib_p () { $opt_debug func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'` test -n "$func_cygming_ms_implib_tmp" } # func_cygming_dll_for_implib_fallback ARG # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # # This fallback implementation is for use when $DLLTOOL # does not support the --identify-strict option. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib_fallback () { $opt_debug if func_cygming_gnu_implib_p "$1" ; then # binutils import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"` elif func_cygming_ms_implib_p "$1" ; then # ms-generated import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"` else # unknown sharedlib_from_linklib_result="" fi } # func_extract_an_archive dir oldlib func_extract_an_archive () { $opt_debug f_ex_an_ar_dir="$1"; shift f_ex_an_ar_oldlib="$1" if test "$lock_old_archive_extraction" = yes; then lockfile=$f_ex_an_ar_oldlib.lock until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done fi func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \ 'stat=$?; rm -f "$lockfile"; exit $stat' if test "$lock_old_archive_extraction" = yes; then $opt_dry_run || rm -f "$lockfile" fi if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then : else func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" fi } # func_extract_archives gentop oldlib ... func_extract_archives () { $opt_debug my_gentop="$1"; shift my_oldlibs=${1+"$@"} my_oldobjs="" my_xlib="" my_xabs="" my_xdir="" for my_xlib in $my_oldlibs; do # Extract the objects. case $my_xlib in [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; *) my_xabs=`pwd`"/$my_xlib" ;; esac func_basename "$my_xlib" my_xlib="$func_basename_result" my_xlib_u=$my_xlib while :; do case " $extracted_archives " in *" $my_xlib_u "*) func_arith $extracted_serial + 1 extracted_serial=$func_arith_result my_xlib_u=lt$extracted_serial-$my_xlib ;; *) break ;; esac done extracted_archives="$extracted_archives $my_xlib_u" my_xdir="$my_gentop/$my_xlib_u" func_mkdir_p "$my_xdir" case $host in *-darwin*) func_verbose "Extracting $my_xabs" # Do not bother doing anything if just a dry run $opt_dry_run || { darwin_orig_dir=`pwd` cd $my_xdir || exit $? darwin_archive=$my_xabs darwin_curdir=`pwd` darwin_base_archive=`basename "$darwin_archive"` darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` if test -n "$darwin_arches"; then darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` darwin_arch= func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" for darwin_arch in $darwin_arches ; do func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}" $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" func_extract_an_archive "`pwd`" "${darwin_base_archive}" cd "$darwin_curdir" $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" done # $darwin_arches ## Okay now we've a bunch of thin objects, gotta fatten them up :) darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u` darwin_file= darwin_files= for darwin_file in $darwin_filelist; do darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP` $LIPO -create -output "$darwin_file" $darwin_files done # $darwin_filelist $RM -rf unfat-$$ cd "$darwin_orig_dir" else cd $darwin_orig_dir func_extract_an_archive "$my_xdir" "$my_xabs" fi # $darwin_arches } # !$opt_dry_run ;; *) func_extract_an_archive "$my_xdir" "$my_xabs" ;; esac my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP` done func_extract_archives_result="$my_oldobjs" } # func_emit_wrapper [arg=no] # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to # incorporate the script contents within a cygwin/mingw # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. # # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory in which it is stored is # the $objdir directory. This is a cygwin/mingw-specific # behavior. func_emit_wrapper () { func_emit_wrapper_arg1=${1-no} $ECHO "\ #! $SHELL # $output - temporary wrapper script for $objdir/$outputname # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # The $output program cannot be directly executed until all the libtool # libraries that it depends on are installed. # # This wrapper script should never be moved out of the build directory. # If it is, it will not operate correctly. # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='$sed_quote_subst' # Be Bourne compatible if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH relink_command=\"$relink_command\" # This environment variable determines our operation mode. if test \"\$libtool_install_magic\" = \"$magic\"; then # install mode needs the following variables: generated_by_libtool_version='$macro_version' notinst_deplibs='$notinst_deplibs' else # When we are sourced in execute mode, \$file and \$ECHO are already set. if test \"\$libtool_execute_magic\" != \"$magic\"; then file=\"\$0\"" qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"` $ECHO "\ # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } ECHO=\"$qECHO\" fi # Very basic option parsing. These options are (a) specific to # the libtool wrapper, (b) are identical between the wrapper # /script/ and the wrapper /executable/ which is used only on # windows platforms, and (c) all begin with the string "--lt-" # (application programs are unlikely to have options which match # this pattern). # # There are only two supported options: --lt-debug and # --lt-dump-script. There is, deliberately, no --lt-help. # # The first argument to this parsing function should be the # script's $0 value, followed by "$@". lt_option_debug= func_parse_lt_options () { lt_script_arg0=\$0 shift for lt_opt do case \"\$lt_opt\" in --lt-debug) lt_option_debug=1 ;; --lt-dump-script) lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\` test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=. lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\` cat \"\$lt_dump_D/\$lt_dump_F\" exit 0 ;; --lt-*) \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2 exit 1 ;; esac done # Print the debug banner immediately: if test -n \"\$lt_option_debug\"; then echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2 fi } # Used when --lt-debug. Prints its arguments to stdout # (redirection is the responsibility of the caller) func_lt_dump_args () { lt_dump_args_N=1; for lt_arg do \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\" lt_dump_args_N=\`expr \$lt_dump_args_N + 1\` done } # Core function for launching the target application func_exec_program_core () { " case $host in # Backslashes separate directories on plain windows *-*-mingw | *-*-os2* | *-cegcc*) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} " ;; *) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir/\$program\" \${1+\"\$@\"} " ;; esac $ECHO "\ \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 exit 1 } # A function to encapsulate launching the target application # Strips options in the --lt-* namespace from \$@ and # launches target application with the remaining arguments. func_exec_program () { case \" \$* \" in *\\ --lt-*) for lt_wr_arg do case \$lt_wr_arg in --lt-*) ;; *) set x \"\$@\" \"\$lt_wr_arg\"; shift;; esac shift done ;; esac func_exec_program_core \${1+\"\$@\"} } # Parse options func_parse_lt_options \"\$0\" \${1+\"\$@\"} # Find the directory that this script lives in. thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\` test \"x\$thisdir\" = \"x\$file\" && thisdir=. # Follow symbolic links until we get to the real thisdir. file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\` while test -n \"\$file\"; do destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\` # If there was a directory component, then change thisdir. if test \"x\$destdir\" != \"x\$file\"; then case \"\$destdir\" in [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; *) thisdir=\"\$thisdir/\$destdir\" ;; esac fi file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\` file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` done # Usually 'no', except on cygwin/mingw when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then # special case for '.' if test \"\$thisdir\" = \".\"; then thisdir=\`pwd\` fi # remove .libs from thisdir case \"\$thisdir\" in *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;; $objdir ) thisdir=. ;; esac fi # Try to get the absolute directory name. absdir=\`cd \"\$thisdir\" && pwd\` test -n \"\$absdir\" && thisdir=\"\$absdir\" " if test "$fast_install" = yes; then $ECHO "\ program=lt-'$outputname'$exeext progdir=\"\$thisdir/$objdir\" if test ! -f \"\$progdir/\$program\" || { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ test \"X\$file\" != \"X\$progdir/\$program\"; }; then file=\"\$\$-\$program\" if test ! -d \"\$progdir\"; then $MKDIR \"\$progdir\" else $RM \"\$progdir/\$file\" fi" $ECHO "\ # relink executable if necessary if test -n \"\$relink_command\"; then if relink_command_output=\`eval \$relink_command 2>&1\`; then : else $ECHO \"\$relink_command_output\" >&2 $RM \"\$progdir/\$file\" exit 1 fi fi $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || { $RM \"\$progdir/\$program\"; $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } $RM \"\$progdir/\$file\" fi" else $ECHO "\ program='$outputname' progdir=\"\$thisdir/$objdir\" " fi $ECHO "\ if test -f \"\$progdir/\$program\"; then" # fixup the dll searchpath if we need to. # # Fix the DLL searchpath if we need to. Do this before prepending # to shlibpath, because on Windows, both are PATH and uninstalled # libraries must come first. if test -n "$dllsearchpath"; then $ECHO "\ # Add the dll search path components to the executable PATH PATH=$dllsearchpath:\$PATH " fi # Export our shlibpath_var if we have one. if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then $ECHO "\ # Add our own library path to $shlibpath_var $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" # Some systems cannot cope with colon-terminated $shlibpath_var # The second colon is a workaround for a bug in BeOS R4 sed $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\` export $shlibpath_var " fi $ECHO "\ if test \"\$libtool_execute_magic\" != \"$magic\"; then # Run the actual program with our arguments. func_exec_program \${1+\"\$@\"} fi else # The program doesn't exist. \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2 \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 exit 1 fi fi\ " } # func_emit_cwrapperexe_src # emit the source code for a wrapper executable on stdout # Must ONLY be called from within func_mode_link because # it depends on a number of variable set therein. func_emit_cwrapperexe_src () { cat < #include #ifdef _MSC_VER # include # include # include #else # include # include # ifdef __CYGWIN__ # include # endif #endif #include #include #include #include #include #include #include #include /* declarations of non-ANSI functions */ #if defined(__MINGW32__) # ifdef __STRICT_ANSI__ int _putenv (const char *); # endif #elif defined(__CYGWIN__) # ifdef __STRICT_ANSI__ char *realpath (const char *, char *); int putenv (char *); int setenv (const char *, const char *, int); # endif /* #elif defined (other platforms) ... */ #endif /* portability defines, excluding path handling macros */ #if defined(_MSC_VER) # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv # define S_IXUSR _S_IEXEC # ifndef _INTPTR_T_DEFINED # define _INTPTR_T_DEFINED # define intptr_t int # endif #elif defined(__MINGW32__) # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv #elif defined(__CYGWIN__) # define HAVE_SETENV # define FOPEN_WB "wb" /* #elif defined (other platforms) ... */ #endif #if defined(PATH_MAX) # define LT_PATHMAX PATH_MAX #elif defined(MAXPATHLEN) # define LT_PATHMAX MAXPATHLEN #else # define LT_PATHMAX 1024 #endif #ifndef S_IXOTH # define S_IXOTH 0 #endif #ifndef S_IXGRP # define S_IXGRP 0 #endif /* path handling portability macros */ #ifndef DIR_SEPARATOR # define DIR_SEPARATOR '/' # define PATH_SEPARATOR ':' #endif #if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ defined (__OS2__) # define HAVE_DOS_BASED_FILE_SYSTEM # define FOPEN_WB "wb" # ifndef DIR_SEPARATOR_2 # define DIR_SEPARATOR_2 '\\' # endif # ifndef PATH_SEPARATOR_2 # define PATH_SEPARATOR_2 ';' # endif #endif #ifndef DIR_SEPARATOR_2 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) #else /* DIR_SEPARATOR_2 */ # define IS_DIR_SEPARATOR(ch) \ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) #endif /* DIR_SEPARATOR_2 */ #ifndef PATH_SEPARATOR_2 # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) #else /* PATH_SEPARATOR_2 */ # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) #endif /* PATH_SEPARATOR_2 */ #ifndef FOPEN_WB # define FOPEN_WB "w" #endif #ifndef _O_BINARY # define _O_BINARY 0 #endif #define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) #define XFREE(stale) do { \ if (stale) { free ((void *) stale); stale = 0; } \ } while (0) #if defined(LT_DEBUGWRAPPER) static int lt_debug = 1; #else static int lt_debug = 0; #endif const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */ void *xmalloc (size_t num); char *xstrdup (const char *string); const char *base_name (const char *name); char *find_executable (const char *wrapper); char *chase_symlinks (const char *pathspec); int make_executable (const char *path); int check_executable (const char *path); char *strendzap (char *str, const char *pat); void lt_debugprintf (const char *file, int line, const char *fmt, ...); void lt_fatal (const char *file, int line, const char *message, ...); static const char *nonnull (const char *s); static const char *nonempty (const char *s); void lt_setenv (const char *name, const char *value); char *lt_extend_str (const char *orig_value, const char *add, int to_end); void lt_update_exe_path (const char *name, const char *value); void lt_update_lib_path (const char *name, const char *value); char **prepare_spawn (char **argv); void lt_dump_script (FILE *f); EOF cat <= 0) && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return 1; else return 0; } int make_executable (const char *path) { int rval = 0; struct stat st; lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n", nonempty (path)); if ((!path) || (!*path)) return 0; if (stat (path, &st) >= 0) { rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); } return rval; } /* Searches for the full path of the wrapper. Returns newly allocated full path name if found, NULL otherwise Does not chase symlinks, even on platforms that support them. */ char * find_executable (const char *wrapper) { int has_slash = 0; const char *p; const char *p_next; /* static buffer for getcwd */ char tmp[LT_PATHMAX + 1]; int tmp_len; char *concat_name; lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n", nonempty (wrapper)); if ((wrapper == NULL) || (*wrapper == '\0')) return NULL; /* Absolute path? */ #if defined (HAVE_DOS_BASED_FILE_SYSTEM) if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } else { #endif if (IS_DIR_SEPARATOR (wrapper[0])) { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } #if defined (HAVE_DOS_BASED_FILE_SYSTEM) } #endif for (p = wrapper; *p; p++) if (*p == '/') { has_slash = 1; break; } if (!has_slash) { /* no slashes; search PATH */ const char *path = getenv ("PATH"); if (path != NULL) { for (p = path; *p; p = p_next) { const char *q; size_t p_len; for (q = p; *q; q++) if (IS_PATH_SEPARATOR (*q)) break; p_len = q - p; p_next = (*q == '\0' ? q : q + 1); if (p_len == 0) { /* empty path: current directory */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); } else { concat_name = XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, p, p_len); concat_name[p_len] = '/'; strcpy (concat_name + p_len + 1, wrapper); } if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } } /* not found in PATH; assume curdir */ } /* Relative path | not found in path: prepend cwd */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); return NULL; } char * chase_symlinks (const char *pathspec) { #ifndef S_ISLNK return xstrdup (pathspec); #else char buf[LT_PATHMAX]; struct stat s; char *tmp_pathspec = xstrdup (pathspec); char *p; int has_symlinks = 0; while (strlen (tmp_pathspec) && !has_symlinks) { lt_debugprintf (__FILE__, __LINE__, "checking path component for symlinks: %s\n", tmp_pathspec); if (lstat (tmp_pathspec, &s) == 0) { if (S_ISLNK (s.st_mode) != 0) { has_symlinks = 1; break; } /* search backwards for last DIR_SEPARATOR */ p = tmp_pathspec + strlen (tmp_pathspec) - 1; while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) p--; if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) { /* no more DIR_SEPARATORS left */ break; } *p = '\0'; } else { lt_fatal (__FILE__, __LINE__, "error accessing file \"%s\": %s", tmp_pathspec, nonnull (strerror (errno))); } } XFREE (tmp_pathspec); if (!has_symlinks) { return xstrdup (pathspec); } tmp_pathspec = realpath (pathspec, buf); if (tmp_pathspec == 0) { lt_fatal (__FILE__, __LINE__, "could not follow symlinks for %s", pathspec); } return xstrdup (tmp_pathspec); #endif } char * strendzap (char *str, const char *pat) { size_t len, patlen; assert (str != NULL); assert (pat != NULL); len = strlen (str); patlen = strlen (pat); if (patlen <= len) { str += len - patlen; if (strcmp (str, pat) == 0) *str = '\0'; } return str; } void lt_debugprintf (const char *file, int line, const char *fmt, ...) { va_list args; if (lt_debug) { (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line); va_start (args, fmt); (void) vfprintf (stderr, fmt, args); va_end (args); } } static void lt_error_core (int exit_status, const char *file, int line, const char *mode, const char *message, va_list ap) { fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode); vfprintf (stderr, message, ap); fprintf (stderr, ".\n"); if (exit_status >= 0) exit (exit_status); } void lt_fatal (const char *file, int line, const char *message, ...) { va_list ap; va_start (ap, message); lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap); va_end (ap); } static const char * nonnull (const char *s) { return s ? s : "(null)"; } static const char * nonempty (const char *s) { return (s && !*s) ? "(empty)" : nonnull (s); } void lt_setenv (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_setenv) setting '%s' to '%s'\n", nonnull (name), nonnull (value)); { #ifdef HAVE_SETENV /* always make a copy, for consistency with !HAVE_SETENV */ char *str = xstrdup (value); setenv (name, str, 1); #else int len = strlen (name) + 1 + strlen (value) + 1; char *str = XMALLOC (char, len); sprintf (str, "%s=%s", name, value); if (putenv (str) != EXIT_SUCCESS) { XFREE (str); } #endif } } char * lt_extend_str (const char *orig_value, const char *add, int to_end) { char *new_value; if (orig_value && *orig_value) { int orig_value_len = strlen (orig_value); int add_len = strlen (add); new_value = XMALLOC (char, add_len + orig_value_len + 1); if (to_end) { strcpy (new_value, orig_value); strcpy (new_value + orig_value_len, add); } else { strcpy (new_value, add); strcpy (new_value + add_len, orig_value); } } else { new_value = xstrdup (add); } return new_value; } void lt_update_exe_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_exe_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); /* some systems can't cope with a ':'-terminated path #' */ int len = strlen (new_value); while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1])) { new_value[len-1] = '\0'; } lt_setenv (name, new_value); XFREE (new_value); } } void lt_update_lib_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_lib_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); } } EOF case $host_os in mingw*) cat <<"EOF" /* Prepares an argument vector before calling spawn(). Note that spawn() does not by itself call the command interpreter (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") : ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&v); v.dwPlatformId == VER_PLATFORM_WIN32_NT; }) ? "cmd.exe" : "command.com"). Instead it simply concatenates the arguments, separated by ' ', and calls CreateProcess(). We must quote the arguments since Win32 CreateProcess() interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a special way: - Space and tab are interpreted as delimiters. They are not treated as delimiters if they are surrounded by double quotes: "...". - Unescaped double quotes are removed from the input. Their only effect is that within double quotes, space and tab are treated like normal characters. - Backslashes not followed by double quotes are not special. - But 2*n+1 backslashes followed by a double quote become n backslashes followed by a double quote (n >= 0): \" -> " \\\" -> \" \\\\\" -> \\" */ #define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" #define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" char ** prepare_spawn (char **argv) { size_t argc; char **new_argv; size_t i; /* Count number of arguments. */ for (argc = 0; argv[argc] != NULL; argc++) ; /* Allocate new argument vector. */ new_argv = XMALLOC (char *, argc + 1); /* Put quoted arguments into the new argument vector. */ for (i = 0; i < argc; i++) { const char *string = argv[i]; if (string[0] == '\0') new_argv[i] = xstrdup ("\"\""); else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL) { int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL); size_t length; unsigned int backslashes; const char *s; char *quoted_string; char *p; length = 0; backslashes = 0; if (quote_around) length++; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') length += backslashes + 1; length++; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) length += backslashes + 1; quoted_string = XMALLOC (char, length + 1); p = quoted_string; backslashes = 0; if (quote_around) *p++ = '"'; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') { unsigned int j; for (j = backslashes + 1; j > 0; j--) *p++ = '\\'; } *p++ = c; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) { unsigned int j; for (j = backslashes; j > 0; j--) *p++ = '\\'; *p++ = '"'; } *p = '\0'; new_argv[i] = quoted_string; } else new_argv[i] = (char *) string; } new_argv[argc] = NULL; return new_argv; } EOF ;; esac cat <<"EOF" void lt_dump_script (FILE* f) { EOF func_emit_wrapper yes | $SED -n -e ' s/^\(.\{79\}\)\(..*\)/\1\ \2/ h s/\([\\"]\)/\\\1/g s/$/\\n/ s/\([^\n]*\).*/ fputs ("\1", f);/p g D' cat <<"EOF" } EOF } # end: func_emit_cwrapperexe_src # func_win32_import_lib_p ARG # True if ARG is an import lib, as indicated by $file_magic_cmd func_win32_import_lib_p () { $opt_debug case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in *import*) : ;; *) false ;; esac } # func_mode_link arg... func_mode_link () { $opt_debug case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # which system we are compiling for in order to pass an extra # flag for every libtool invocation. # allow_undefined=no # FIXME: Unfortunately, there are problems with the above when trying # to make a dll which has undefined symbols, in which case not # even a static library is built. For now, we need to specify # -no-undefined on the libtool link line when we can be certain # that all symbols are satisfied, otherwise we get a static library. allow_undefined=yes ;; *) allow_undefined=yes ;; esac libtool_args=$nonopt base_compile="$nonopt $@" compile_command=$nonopt finalize_command=$nonopt compile_rpath= finalize_rpath= compile_shlibpath= finalize_shlibpath= convenience= old_convenience= deplibs= old_deplibs= compiler_flags= linker_flags= dllsearchpath= lib_search_path=`pwd` inst_prefix_dir= new_inherited_linker_flags= avoid_version=no bindir= dlfiles= dlprefiles= dlself=no export_dynamic=no export_symbols= export_symbols_regex= generated= libobjs= ltlibs= module=no no_install=no objs= non_pic_objects= precious_files_regex= prefer_static_libs=no preload=no prev= prevarg= release= rpath= xrpath= perm_rpath= temp_rpath= thread_safe=no vinfo= vinfo_number=no weak_libs= single_module="${wl}-single_module" func_infer_tag $base_compile # We need to know -static, to get the right output filenames. for arg do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no break ;; -all-static | -static | -static-libtool-libs) case $arg in -all-static) if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then func_warning "complete static linking is impossible in this configuration" fi if test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; -static) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built ;; -static-libtool-libs) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; esac build_libtool_libs=no build_old_libs=yes break ;; esac done # See if our shared archives depend on static archives. test -n "$old_archive_from_new_cmds" && build_old_libs=yes # Go through the arguments, transforming them on the way. while test "$#" -gt 0; do arg="$1" shift func_quote_for_eval "$arg" qarg=$func_quote_for_eval_unquoted_result func_append libtool_args " $func_quote_for_eval_result" # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in output) func_append compile_command " @OUTPUT@" func_append finalize_command " @OUTPUT@" ;; esac case $prev in bindir) bindir="$arg" prev= continue ;; dlfiles|dlprefiles) if test "$preload" = no; then # Add the symbol object into the linking commands. func_append compile_command " @SYMFILE@" func_append finalize_command " @SYMFILE@" preload=yes fi case $arg in *.la | *.lo) ;; # We handle these cases below. force) if test "$dlself" = no; then dlself=needless export_dynamic=yes fi prev= continue ;; self) if test "$prev" = dlprefiles; then dlself=yes elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then dlself=yes else dlself=needless export_dynamic=yes fi prev= continue ;; *) if test "$prev" = dlfiles; then func_append dlfiles " $arg" else func_append dlprefiles " $arg" fi prev= continue ;; esac ;; expsyms) export_symbols="$arg" test -f "$arg" \ || func_fatal_error "symbol file \`$arg' does not exist" prev= continue ;; expsyms_regex) export_symbols_regex="$arg" prev= continue ;; framework) case $host in *-*-darwin*) case "$deplibs " in *" $qarg.ltframework "*) ;; *) func_append deplibs " $qarg.ltframework" # this is fixed later ;; esac ;; esac prev= continue ;; inst_prefix) inst_prefix_dir="$arg" prev= continue ;; objectlist) if test -f "$arg"; then save_arg=$arg moreargs= for fil in `cat "$save_arg"` do # func_append moreargs " $fil" arg=$fil # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi done else func_fatal_error "link input file \`$arg' does not exist" fi arg=$save_arg prev= continue ;; precious_regex) precious_files_regex="$arg" prev= continue ;; release) release="-$arg" prev= continue ;; rpath | xrpath) # We need an absolute path. case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac if test "$prev" = rpath; then case "$rpath " in *" $arg "*) ;; *) func_append rpath " $arg" ;; esac else case "$xrpath " in *" $arg "*) ;; *) func_append xrpath " $arg" ;; esac fi prev= continue ;; shrext) shrext_cmds="$arg" prev= continue ;; weak) func_append weak_libs " $arg" prev= continue ;; xcclinker) func_append linker_flags " $qarg" func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xcompiler) func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xlinker) func_append linker_flags " $qarg" func_append compiler_flags " $wl$qarg" prev= func_append compile_command " $wl$qarg" func_append finalize_command " $wl$qarg" continue ;; *) eval "$prev=\"\$arg\"" prev= continue ;; esac fi # test -n "$prev" prevarg="$arg" case $arg in -all-static) if test -n "$link_static_flag"; then # See comment for -static flag below, for more details. func_append compile_command " $link_static_flag" func_append finalize_command " $link_static_flag" fi continue ;; -allow-undefined) # FIXME: remove this flag sometime in the future. func_fatal_error "\`-allow-undefined' must not be used because it is the default" ;; -avoid-version) avoid_version=yes continue ;; -bindir) prev=bindir continue ;; -dlopen) prev=dlfiles continue ;; -dlpreopen) prev=dlprefiles continue ;; -export-dynamic) export_dynamic=yes continue ;; -export-symbols | -export-symbols-regex) if test -n "$export_symbols" || test -n "$export_symbols_regex"; then func_fatal_error "more than one -exported-symbols argument is not allowed" fi if test "X$arg" = "X-export-symbols"; then prev=expsyms else prev=expsyms_regex fi continue ;; -framework) prev=framework continue ;; -inst-prefix-dir) prev=inst_prefix continue ;; # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* # so, if we see these flags be careful not to treat them like -L -L[A-Z][A-Z]*:*) case $with_gcc/$host in no/*-*-irix* | /*-*-irix*) func_append compile_command " $arg" func_append finalize_command " $arg" ;; esac continue ;; -L*) func_stripname "-L" '' "$arg" if test -z "$func_stripname_result"; then if test "$#" -gt 0; then func_fatal_error "require no space between \`-L' and \`$1'" else func_fatal_error "need path for \`-L' option" fi fi func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) absdir=`cd "$dir" && pwd` test -z "$absdir" && \ func_fatal_error "cannot determine absolute directory name of \`$dir'" dir="$absdir" ;; esac case "$deplibs " in *" -L$dir "* | *" $arg "*) # Will only happen for absolute or sysroot arguments ;; *) # Preserve sysroot, but never include relative directories case $dir in [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;; *) func_append deplibs " -L$dir" ;; esac func_append lib_search_path " $dir" ;; esac case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; ::) dllsearchpath=$dir;; *) func_append dllsearchpath ":$dir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac continue ;; -l*) if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) # These systems don't actually have a C or math library (as such) continue ;; *-*-os2*) # These systems don't actually have a C library (as such) test "X$arg" = "X-lc" && continue ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. test "X$arg" = "X-lc" && continue ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C and math libraries are in the System framework func_append deplibs " System.ltframework" continue ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype test "X$arg" = "X-lc" && continue ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work test "X$arg" = "X-lc" && continue ;; esac elif test "X$arg" = "X-lc_r"; then case $host in *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc_r directly, use -pthread flag. continue ;; esac fi func_append deplibs " $arg" continue ;; -module) module=yes continue ;; # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. -model|-arch|-isysroot|--sysroot) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" prev=xcompiler continue ;; -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case "$new_inherited_linker_flags " in *" $arg "*) ;; * ) func_append new_inherited_linker_flags " $arg" ;; esac continue ;; -multi_module) single_module="${wl}-multi_module" continue ;; -no-fast-install) fast_install=no continue ;; -no-install) case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) # The PATH hackery in wrapper scripts is required on Windows # and Darwin in order for the loader to find any dlls it needs. func_warning "\`-no-install' is ignored for $host" func_warning "assuming \`-no-fast-install' instead" fast_install=no ;; *) no_install=yes ;; esac continue ;; -no-undefined) allow_undefined=no continue ;; -objectlist) prev=objectlist continue ;; -o) prev=output ;; -precious-files-regex) prev=precious_regex continue ;; -release) prev=release continue ;; -rpath) prev=rpath continue ;; -R) prev=xrpath continue ;; -R*) func_stripname '-R' '' "$arg" dir=$func_stripname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; =*) func_stripname '=' '' "$dir" dir=$lt_sysroot$func_stripname_result ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac continue ;; -shared) # The effects of -shared are defined in a previous loop. continue ;; -shrext) prev=shrext continue ;; -static | -static-libtool-libs) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects # would be equivalent was wrong. It would break on at least # Digital Unix and AIX. continue ;; -thread-safe) thread_safe=yes continue ;; -version-info) prev=vinfo continue ;; -version-number) prev=vinfo vinfo_number=yes continue ;; -weak) prev=weak continue ;; -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" func_append arg " $func_quote_for_eval_result" func_append compiler_flags " $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Wl,*) func_stripname '-Wl,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" func_append arg " $wl$func_quote_for_eval_result" func_append compiler_flags " $wl$func_quote_for_eval_result" func_append linker_flags " $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Xcompiler) prev=xcompiler continue ;; -Xlinker) prev=xlinker continue ;; -XCClinker) prev=xcclinker continue ;; # -msg_* for osf cc -msg_*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; # Flags to be passed through unchanged, with rationale: # -64, -mips[0-9] enable 64-bit mode for the SGI compiler # -r[0-9][0-9]* specify processor for the SGI compiler # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler # +DA*, +DD* enable 64-bit mode for the HP compiler # -q* compiler args for the IBM compiler # -m*, -t[45]*, -txscale* architecture-specific flags for GCC # -F/path path to uninstalled frameworks, gcc on darwin # -p, -pg, --coverage, -fprofile-* profiling flags for GCC # @file GCC response files # -tp=* Portland pgcc target processor selection # --sysroot=* for sysroot support # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ -O*|-flto*|-fwhopr*|-fuse-linker-plugin) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" func_append compile_command " $arg" func_append finalize_command " $arg" func_append compiler_flags " $arg" continue ;; # Some other compiler flag. -* | +*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; *.$objext) # A standard object. func_append objs " $arg" ;; *.lo) # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi ;; *.$libext) # An archive. func_append deplibs " $arg" func_append old_deplibs " $arg" continue ;; *.la) # A libtool-controlled library. func_resolve_sysroot "$arg" if test "$prev" = dlfiles; then # This library was specified with -dlopen. func_append dlfiles " $func_resolve_sysroot_result" prev= elif test "$prev" = dlprefiles; then # The library was specified with -dlpreopen. func_append dlprefiles " $func_resolve_sysroot_result" prev= else func_append deplibs " $func_resolve_sysroot_result" fi continue ;; # Some other compiler argument. *) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; esac # arg # Now actually substitute the argument into the commands. if test -n "$arg"; then func_append compile_command " $arg" func_append finalize_command " $arg" fi done # argument parsing loop test -n "$prev" && \ func_fatal_help "the \`$prevarg' option requires an argument" if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then eval arg=\"$export_dynamic_flag_spec\" func_append compile_command " $arg" func_append finalize_command " $arg" fi oldlibs= # calculate the name of the file, without its directory func_basename "$output" outputname="$func_basename_result" libobjs_save="$libobjs" if test -n "$shlibpath_var"; then # get the directories listed in $shlibpath_var eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\` else shlib_search_path= fi eval sys_lib_search_path=\"$sys_lib_search_path_spec\" eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" func_dirname "$output" "/" "" output_objdir="$func_dirname_result$objdir" func_to_tool_file "$output_objdir/" tool_output_objdir=$func_to_tool_file_result # Create the object directory. func_mkdir_p "$output_objdir" # Determine the type of output case $output in "") func_fatal_help "you must specify an output file" ;; *.$libext) linkmode=oldlib ;; *.lo | *.$objext) linkmode=obj ;; *.la) linkmode=lib ;; *) linkmode=prog ;; # Anything else should be a program. esac specialdeplibs= libs= # Find all interdependent deplibs by searching for libraries # that are linked more than once (e.g. -la -lb -la) for deplib in $deplibs; do if $opt_preserve_dup_deps ; then case "$libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append libs " $deplib" done if test "$linkmode" = lib; then libs="$predeps $libs $compiler_lib_search_path $postdeps" # Compute libraries that are listed more than once in $predeps # $postdeps and mark them as special (i.e., whose duplicates are # not to be eliminated). pre_post_deps= if $opt_duplicate_compiler_generated_deps; then for pre_post_dep in $predeps $postdeps; do case "$pre_post_deps " in *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;; esac func_append pre_post_deps " $pre_post_dep" done fi pre_post_deps= fi deplibs= newdependency_libs= newlib_search_path= need_relink=no # whether we're linking any uninstalled libtool libraries notinst_deplibs= # not-installed libtool libraries notinst_path= # paths that contain not-installed libtool libraries case $linkmode in lib) passes="conv dlpreopen link" for file in $dlfiles $dlprefiles; do case $file in *.la) ;; *) func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file" ;; esac done ;; prog) compile_deplibs= finalize_deplibs= alldeplibs=no newdlfiles= newdlprefiles= passes="conv scan dlopen dlpreopen link" ;; *) passes="conv" ;; esac for pass in $passes; do # The preopen pass in lib mode reverses $deplibs; put it back here # so that -L comes before libs that need it for instance... if test "$linkmode,$pass" = "lib,link"; then ## FIXME: Find the place where the list is rebuilt in the wrong ## order, and fix it there properly tmp_deplibs= for deplib in $deplibs; do tmp_deplibs="$deplib $tmp_deplibs" done deplibs="$tmp_deplibs" fi if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan"; then libs="$deplibs" deplibs= fi if test "$linkmode" = prog; then case $pass in dlopen) libs="$dlfiles" ;; dlpreopen) libs="$dlprefiles" ;; link) libs="$deplibs %DEPLIBS%" test "X$link_all_deplibs" != Xno && libs="$libs $dependency_libs" ;; esac fi if test "$linkmode,$pass" = "lib,dlpreopen"; then # Collect and forward deplibs of preopened libtool libs for lib in $dlprefiles; do # Ignore non-libtool-libs dependency_libs= func_resolve_sysroot "$lib" case $lib in *.la) func_source "$func_resolve_sysroot_result" ;; esac # Collect preopened libtool deplibs, except any this library # has declared as weak libs for deplib in $dependency_libs; do func_basename "$deplib" deplib_base=$func_basename_result case " $weak_libs " in *" $deplib_base "*) ;; *) func_append deplibs " $deplib" ;; esac done done libs="$dlprefiles" fi if test "$pass" = dlopen; then # Collect dlpreopened libraries save_deplibs="$deplibs" deplibs= fi for deplib in $libs; do lib= found=no case $deplib in -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append compiler_flags " $deplib" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -l*) if test "$linkmode" != lib && test "$linkmode" != prog; then func_warning "\`-l' is ignored for archives/objects" continue fi func_stripname '-l' '' "$deplib" name=$func_stripname_result if test "$linkmode" = lib; then searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" else searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" fi for searchdir in $searchdirs; do for search_ext in .la $std_shrext .so .a; do # Search the libtool library lib="$searchdir/lib${name}${search_ext}" if test -f "$lib"; then if test "$search_ext" = ".la"; then found=yes else found=no fi break 2 fi done done if test "$found" != yes; then # deplib doesn't seem to be a libtool library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue else # deplib is a libtool library # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, # We need to do some special things here, and not later. if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $deplib "*) if func_lalib_p "$lib"; then library_names= old_library= func_source "$lib" for l in $old_library $library_names; do ll="$l" done if test "X$ll" = "X$old_library" ; then # only static version available found=no func_dirname "$lib" "" "." ladir="$func_dirname_result" lib=$ladir/$old_library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue fi fi ;; *) ;; esac fi fi ;; # -l *.ltframework) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -L*) case $linkmode in lib) deplibs="$deplib $deplibs" test "$pass" = conv && continue newdependency_libs="$deplib $newdependency_libs" func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; prog) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi if test "$pass" = scan; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; *) func_warning "\`-L' is ignored for archives/objects" ;; esac # linkmode continue ;; # -L -R*) if test "$pass" = link; then func_stripname '-R' '' "$deplib" func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # Make sure the xrpath contains only unique directories. case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac fi deplibs="$deplib $deplibs" continue ;; *.la) func_resolve_sysroot "$deplib" lib=$func_resolve_sysroot_result ;; *.$libext) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi case $linkmode in lib) # Linking convenience modules into shared libraries is allowed, # but linking other static libraries is non-portable. case " $dlpreconveniencelibs " in *" $deplib "*) ;; *) valid_a_lib=no case $deplibs_check_method in match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \ | $EGREP "$match_pattern_regex" > /dev/null; then valid_a_lib=yes fi ;; pass_all) valid_a_lib=yes ;; esac if test "$valid_a_lib" != yes; then echo $ECHO "*** Warning: Trying to link with static lib archive $deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because the file extensions .$libext of this argument makes me believe" echo "*** that it is just a static archive that I should not use here." else echo $ECHO "*** Warning: Linking the shared library $output against the" $ECHO "*** static library $deplib is not portable!" deplibs="$deplib $deplibs" fi ;; esac continue ;; prog) if test "$pass" != link; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi continue ;; esac # linkmode ;; # *.$libext *.lo | *.$objext) if test "$pass" = conv; then deplibs="$deplib $deplibs" elif test "$linkmode" = prog; then if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlopen support or we're linking statically, # we need to preload. func_append newdlprefiles " $deplib" compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append newdlfiles " $deplib" fi fi continue ;; %DEPLIBS%) alldeplibs=yes continue ;; esac # case $deplib if test "$found" = yes || test -f "$lib"; then : else func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'" fi # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$lib" \ || func_fatal_error "\`$lib' is not a valid libtool archive" func_dirname "$lib" "" "." ladir="$func_dirname_result" dlname= dlopen= dlpreopen= libdir= library_names= old_library= inherited_linker_flags= # If the library was installed with an old release of libtool, # it will not redefine variables installed, or shouldnotlink installed=yes shouldnotlink=no avoidtemprpath= # Read the .la file func_source "$lib" # Convert "-framework foo" to "foo.ltframework" if test -n "$inherited_linker_flags"; then tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'` for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do case " $new_inherited_linker_flags " in *" $tmp_inherited_linker_flag "*) ;; *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";; esac done fi dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan" || { test "$linkmode" != prog && test "$linkmode" != lib; }; then test -n "$dlopen" && func_append dlfiles " $dlopen" test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen" fi if test "$pass" = conv; then # Only check for convenience libraries deplibs="$lib $deplibs" if test -z "$libdir"; then if test -z "$old_library"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # It is a libtool convenience library, so add in its objects. func_append convenience " $ladir/$objdir/$old_library" func_append old_convenience " $ladir/$objdir/$old_library" tmp_libs= for deplib in $dependency_libs; do deplibs="$deplib $deplibs" if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done elif test "$linkmode" != prog && test "$linkmode" != lib; then func_fatal_error "\`$lib' is not a convenience library" fi continue fi # $pass = conv # Get the name of the library we link against. linklib= if test -n "$old_library" && { test "$prefer_static_libs" = yes || test "$prefer_static_libs,$installed" = "built,no"; }; then linklib=$old_library else for l in $old_library $library_names; do linklib="$l" done fi if test -z "$linklib"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # This library was specified with -dlopen. if test "$pass" = dlopen; then if test -z "$libdir"; then func_fatal_error "cannot -dlopen a convenience library: \`$lib'" fi if test -z "$dlname" || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlname, no dlopen support or we're linking # statically, we need to preload. We also need to preload any # dependent libraries so libltdl's deplib preloader doesn't # bomb out in the load deplibs phase. func_append dlprefiles " $lib $dependency_libs" else func_append newdlfiles " $lib" fi continue fi # $pass = dlopen # We need an absolute path. case $ladir in [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; *) abs_ladir=`cd "$ladir" && pwd` if test -z "$abs_ladir"; then func_warning "cannot determine absolute directory name of \`$ladir'" func_warning "passing it literally to the linker, although it might fail" abs_ladir="$ladir" fi ;; esac func_basename "$lib" laname="$func_basename_result" # Find the relevant object directory and library name. if test "X$installed" = Xyes; then if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then func_warning "library \`$lib' was moved." dir="$ladir" absdir="$abs_ladir" libdir="$abs_ladir" else dir="$lt_sysroot$libdir" absdir="$lt_sysroot$libdir" fi test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes else if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then dir="$ladir" absdir="$abs_ladir" # Remove this search path later func_append notinst_path " $abs_ladir" else dir="$ladir/$objdir" absdir="$abs_ladir/$objdir" # Remove this search path later func_append notinst_path " $abs_ladir" fi fi # $installed = yes func_stripname 'lib' '.la' "$laname" name=$func_stripname_result # This library was specified with -dlpreopen. if test "$pass" = dlpreopen; then if test -z "$libdir" && test "$linkmode" = prog; then func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'" fi case "$host" in # special handling for platforms with PE-DLLs. *cygwin* | *mingw* | *cegcc* ) # Linker will automatically link against shared library if both # static and shared are present. Therefore, ensure we extract # symbols from the import library if a shared library is present # (otherwise, the dlopen module name will be incorrect). We do # this by putting the import library name into $newdlprefiles. # We recover the dlopen module name by 'saving' the la file # name in a special purpose variable, and (later) extracting the # dlname from the la file. if test -n "$dlname"; then func_tr_sh "$dir/$linklib" eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname" func_append newdlprefiles " $dir/$linklib" else func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" fi ;; * ) # Prefer using a static library (so that no silly _DYNAMIC symbols # are required to link). if test -n "$old_library"; then func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" # Otherwise, use the dlname, so that lt_dlopen finds it. elif test -n "$dlname"; then func_append newdlprefiles " $dir/$dlname" else func_append newdlprefiles " $dir/$linklib" fi ;; esac fi # $pass = dlpreopen if test -z "$libdir"; then # Link the convenience library if test "$linkmode" = lib; then deplibs="$dir/$old_library $deplibs" elif test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$dir/$old_library $compile_deplibs" finalize_deplibs="$dir/$old_library $finalize_deplibs" else deplibs="$lib $deplibs" # used for prog,scan pass fi continue fi if test "$linkmode" = prog && test "$pass" != link; then func_append newlib_search_path " $ladir" deplibs="$lib $deplibs" linkalldeplibs=no if test "$link_all_deplibs" != no || test -z "$library_names" || test "$build_libtool_libs" = no; then linkalldeplibs=yes fi tmp_libs= for deplib in $dependency_libs; do case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; esac # Need to link against all dependency_libs? if test "$linkalldeplibs" = yes; then deplibs="$deplib $deplibs" else # Need to hardcode shared library paths # or/and link against static libraries newdependency_libs="$deplib $newdependency_libs" fi if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done # for deplib continue fi # $linkmode = prog... if test "$linkmode,$pass" = "prog,link"; then if test -n "$library_names" && { { test "$prefer_static_libs" = no || test "$prefer_static_libs,$installed" = "built,yes"; } || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then # Make sure the rpath contains only unique directories. case "$temp_rpath:" in *"$absdir:"*) ;; *) func_append temp_rpath "$absdir:" ;; esac fi # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi # $linkmode,$pass = prog,link... if test "$alldeplibs" = yes && { test "$deplibs_check_method" = pass_all || { test "$build_libtool_libs" = yes && test -n "$library_names"; }; }; then # We only need to search for static libraries continue fi fi link_static=no # Whether the deplib will be linked statically use_static_libs=$prefer_static_libs if test "$use_static_libs" = built && test "$installed" = yes; then use_static_libs=no fi if test -n "$library_names" && { test "$use_static_libs" = no || test -z "$old_library"; }; then case $host in *cygwin* | *mingw* | *cegcc*) # No point in relinking DLLs because paths are not encoded func_append notinst_deplibs " $lib" need_relink=no ;; *) if test "$installed" = no; then func_append notinst_deplibs " $lib" need_relink=yes fi ;; esac # This is a shared library # Warn about portability, can't link against -module's on some # systems (darwin). Don't bleat about dlopened modules though! dlopenmodule="" for dlpremoduletest in $dlprefiles; do if test "X$dlpremoduletest" = "X$lib"; then dlopenmodule="$dlpremoduletest" break fi done if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then echo if test "$linkmode" = prog; then $ECHO "*** Warning: Linking the executable $output against the loadable module" else $ECHO "*** Warning: Linking the shared library $output against the loadable module" fi $ECHO "*** $linklib is not portable!" fi if test "$linkmode" = lib && test "$hardcode_into_libs" = yes; then # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi if test -n "$old_archive_from_expsyms_cmds"; then # figure out the soname set dummy $library_names shift realname="$1" shift libname=`eval "\\$ECHO \"$libname_spec\""` # use dlname if we got it. it's perfectly good, no? if test -n "$dlname"; then soname="$dlname" elif test -n "$soname_spec"; then # bleh windows case $host in *cygwin* | mingw* | *cegcc*) func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; esac eval soname=\"$soname_spec\" else soname="$realname" fi # Make a new name for the extract_expsyms_cmds to use soroot="$soname" func_basename "$soroot" soname="$func_basename_result" func_stripname 'lib' '.dll' "$soname" newlib=libimp-$func_stripname_result.a # If the library has no export list, then create one now if test -f "$output_objdir/$soname-def"; then : else func_verbose "extracting exported symbol list from \`$soname'" func_execute_cmds "$extract_expsyms_cmds" 'exit $?' fi # Create $newlib if test -f "$output_objdir/$newlib"; then :; else func_verbose "generating import library for \`$soname'" func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' fi # make sure the library variables are pointing to the new library dir=$output_objdir linklib=$newlib fi # test -n "$old_archive_from_expsyms_cmds" if test "$linkmode" = prog || test "$opt_mode" != relink; then add_shlibpath= add_dir= add= lib_linked=yes case $hardcode_action in immediate | unsupported) if test "$hardcode_direct" = no; then add="$dir/$linklib" case $host in *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; *-*-sysv4*uw2*) add_dir="-L$dir" ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir="-L$dir" ;; *-*-darwin* ) # if the lib is a (non-dlopened) module then we can not # link against it, someone is ignoring the earlier warnings if /usr/bin/file -L $add 2> /dev/null | $GREP ": [^:]* bundle" >/dev/null ; then if test "X$dlopenmodule" != "X$lib"; then $ECHO "*** Warning: lib $linklib is a module, not a shared library" if test -z "$old_library" ; then echo echo "*** And there doesn't seem to be a static archive available" echo "*** The link will probably fail, sorry" else add="$dir/$old_library" fi elif test -n "$old_library"; then add="$dir/$old_library" fi fi esac elif test "$hardcode_minus_L" = no; then case $host in *-*-sunos*) add_shlibpath="$dir" ;; esac add_dir="-L$dir" add="-l$name" elif test "$hardcode_shlibpath_var" = no; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; relink) if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$dir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$absdir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; *) lib_linked=no ;; esac if test "$lib_linked" != yes; then func_fatal_configuration "unsupported hardcode properties" fi if test -n "$add_shlibpath"; then case :$compile_shlibpath: in *":$add_shlibpath:"*) ;; *) func_append compile_shlibpath "$add_shlibpath:" ;; esac fi if test "$linkmode" = prog; then test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" test -n "$add" && compile_deplibs="$add $compile_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" if test "$hardcode_direct" != yes && test "$hardcode_minus_L" != yes && test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac fi fi fi if test "$linkmode" = prog || test "$opt_mode" = relink; then add_shlibpath= add_dir= add= # Finalize command for both is simple: just hardcode it. if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$libdir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$libdir" add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac add="-l$name" elif test "$hardcode_automatic" = yes; then if test -n "$inst_prefix_dir" && test -f "$inst_prefix_dir$libdir/$linklib" ; then add="$inst_prefix_dir$libdir/$linklib" else add="$libdir/$linklib" fi else # We cannot seem to hardcode it, guess we'll fake it. add_dir="-L$libdir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" fi if test "$linkmode" = prog; then test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" test -n "$add" && finalize_deplibs="$add $finalize_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" fi fi elif test "$linkmode" = prog; then # Here we assume that one of hardcode_direct or hardcode_minus_L # is not unsupported. This is valid on all known static and # shared platforms. if test "$hardcode_direct" != unsupported; then test -n "$old_library" && linklib="$old_library" compile_deplibs="$dir/$linklib $compile_deplibs" finalize_deplibs="$dir/$linklib $finalize_deplibs" else compile_deplibs="-l$name -L$dir $compile_deplibs" finalize_deplibs="-l$name -L$dir $finalize_deplibs" fi elif test "$build_libtool_libs" = yes; then # Not a shared library if test "$deplibs_check_method" != pass_all; then # We're trying link a shared library against a static one # but the system doesn't support it. # Just print a warning and add the library to dependency_libs so # that the program can be linked against the static library. echo $ECHO "*** Warning: This system can not link to static lib archive $lib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have." if test "$module" = yes; then echo "*** But as you try to build a module library, libtool will still create " echo "*** a static module, that should work as long as the dlopening application" echo "*** is linked with the -dlopen flag to resolve symbols at runtime." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using \`nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi else deplibs="$dir/$old_library $deplibs" link_static=yes fi fi # link shared/static library? if test "$linkmode" = lib; then if test -n "$dependency_libs" && { test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes || test "$link_static" = yes; }; then # Extract -R from dependency_libs temp_deplibs= for libdir in $dependency_libs; do case $libdir in -R*) func_stripname '-R' '' "$libdir" temp_xrpath=$func_stripname_result case " $xrpath " in *" $temp_xrpath "*) ;; *) func_append xrpath " $temp_xrpath";; esac;; *) func_append temp_deplibs " $libdir";; esac done dependency_libs="$temp_deplibs" fi func_append newlib_search_path " $absdir" # Link against this library test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" # ... and its dependency_libs tmp_libs= for deplib in $dependency_libs; do newdependency_libs="$deplib $newdependency_libs" case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result";; *) func_resolve_sysroot "$deplib" ;; esac if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $func_resolve_sysroot_result "*) func_append specialdeplibs " $func_resolve_sysroot_result" ;; esac fi func_append tmp_libs " $func_resolve_sysroot_result" done if test "$link_all_deplibs" != no; then # Add the search paths of all dependency libraries for deplib in $dependency_libs; do path= case $deplib in -L*) path="$deplib" ;; *.la) func_resolve_sysroot "$deplib" deplib=$func_resolve_sysroot_result func_dirname "$deplib" "" "." dir=$func_dirname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; *) absdir=`cd "$dir" && pwd` if test -z "$absdir"; then func_warning "cannot determine absolute directory name of \`$dir'" absdir="$dir" fi ;; esac if $GREP "^installed=no" $deplib > /dev/null; then case $host in *-*-darwin*) depdepl= eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` if test -n "$deplibrary_names" ; then for tmp in $deplibrary_names ; do depdepl=$tmp done if test -f "$absdir/$objdir/$depdepl" ; then depdepl="$absdir/$objdir/$depdepl" darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` if test -z "$darwin_install_name"; then darwin_install_name=`${OTOOL64} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` fi func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}" func_append linker_flags " -dylib_file ${darwin_install_name}:${depdepl}" path= fi fi ;; *) path="-L$absdir/$objdir" ;; esac else eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" test "$absdir" != "$libdir" && \ func_warning "\`$deplib' seems to be moved" path="-L$absdir" fi ;; esac case " $deplibs " in *" $path "*) ;; *) deplibs="$path $deplibs" ;; esac done fi # link_all_deplibs != no fi # linkmode = lib done # for deplib in $libs if test "$pass" = link; then if test "$linkmode" = "prog"; then compile_deplibs="$new_inherited_linker_flags $compile_deplibs" finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" else compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` fi fi dependency_libs="$newdependency_libs" if test "$pass" = dlpreopen; then # Link the dlpreopened libraries before other libraries for deplib in $save_deplibs; do deplibs="$deplib $deplibs" done fi if test "$pass" != dlopen; then if test "$pass" != conv; then # Make sure lib_search_path contains only unique directories. lib_search_path= for dir in $newlib_search_path; do case "$lib_search_path " in *" $dir "*) ;; *) func_append lib_search_path " $dir" ;; esac done newlib_search_path= fi if test "$linkmode,$pass" != "prog,link"; then vars="deplibs" else vars="compile_deplibs finalize_deplibs" fi for var in $vars dependency_libs; do # Add libraries to $var in reverse order eval tmp_libs=\"\$$var\" new_libs= for deplib in $tmp_libs; do # FIXME: Pedantically, this is the right thing to do, so # that some nasty dependency loop isn't accidentally # broken: #new_libs="$deplib $new_libs" # Pragmatically, this seems to cause very few problems in # practice: case $deplib in -L*) new_libs="$deplib $new_libs" ;; -R*) ;; *) # And here is the reason: when a library appears more # than once as an explicit dependence of a library, or # is implicitly linked in more than once by the # compiler, it is considered special, and multiple # occurrences thereof are not removed. Compare this # with having the same library being listed as a # dependency of multiple other libraries: in this case, # we know (pedantically, we assume) the library does not # need to be listed more than once, so we keep only the # last copy. This is not always right, but it is rare # enough that we require users that really mean to play # such unportable linking tricks to link the library # using -Wl,-lname, so that libtool does not consider it # for duplicate removal. case " $specialdeplibs " in *" $deplib "*) new_libs="$deplib $new_libs" ;; *) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$deplib $new_libs" ;; esac ;; esac ;; esac done tmp_libs= for deplib in $new_libs; do case $deplib in -L*) case " $tmp_libs " in *" $deplib "*) ;; *) func_append tmp_libs " $deplib" ;; esac ;; *) func_append tmp_libs " $deplib" ;; esac done eval $var=\"$tmp_libs\" done # for var fi # Last step: remove runtime libs from dependency_libs # (they stay in deplibs) tmp_libs= for i in $dependency_libs ; do case " $predeps $postdeps $compiler_lib_search_path " in *" $i "*) i="" ;; esac if test -n "$i" ; then func_append tmp_libs " $i" fi done dependency_libs=$tmp_libs done # for pass if test "$linkmode" = prog; then dlfiles="$newdlfiles" fi if test "$linkmode" = prog || test "$linkmode" = lib; then dlprefiles="$newdlprefiles" fi case $linkmode in oldlib) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for archives" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for archives" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for archives" test -n "$xrpath" && \ func_warning "\`-R' is ignored for archives" test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for archives" test -n "$release" && \ func_warning "\`-release' is ignored for archives" test -n "$export_symbols$export_symbols_regex" && \ func_warning "\`-export-symbols' is ignored for archives" # Now set the variables for building old libraries. build_libtool_libs=no oldlibs="$output" func_append objs "$old_deplibs" ;; lib) # Make sure we only generate libraries of the form `libNAME.la'. case $outputname in lib*) func_stripname 'lib' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" ;; *) test "$module" = no && \ func_fatal_help "libtool library \`$output' must begin with \`lib'" if test "$need_lib_prefix" != no; then # Add the "lib" prefix for modules if required func_stripname '' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" else func_stripname '' '.la' "$outputname" libname=$func_stripname_result fi ;; esac if test -n "$objs"; then if test "$deplibs_check_method" != pass_all; then func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs" else echo $ECHO "*** Warning: Linking the shared library $output against the non-libtool" $ECHO "*** objects $objs is not portable!" func_append libobjs " $objs" fi fi test "$dlself" != no && \ func_warning "\`-dlopen self' is ignored for libtool libraries" set dummy $rpath shift test "$#" -gt 1 && \ func_warning "ignoring multiple \`-rpath's for a libtool library" install_libdir="$1" oldlibs= if test -z "$rpath"; then if test "$build_libtool_libs" = yes; then # Building a libtool convenience library. # Some compilers have problems with a `.al' extension so # convenience libraries should have the same extension an # archive normally would. oldlibs="$output_objdir/$libname.$libext $oldlibs" build_libtool_libs=convenience build_old_libs=yes fi test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for convenience libraries" test -n "$release" && \ func_warning "\`-release' is ignored for convenience libraries" else # Parse the version information argument. save_ifs="$IFS"; IFS=':' set dummy $vinfo 0 0 0 shift IFS="$save_ifs" test -n "$7" && \ func_fatal_help "too many parameters to \`-version-info'" # convert absolute version numbers to libtool ages # this retains compatibility with .la files and attempts # to make the code below a bit more comprehensible case $vinfo_number in yes) number_major="$1" number_minor="$2" number_revision="$3" # # There are really only two kinds -- those that # use the current revision as the major version # and those that subtract age and use age as # a minor version. But, then there is irix # which has an extra 1 added just for fun # case $version_type in # correct linux to gnu/linux during the next big refactor darwin|linux|osf|windows|none) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_revision" ;; freebsd-aout|freebsd-elf|qnx|sunos) current="$number_major" revision="$number_minor" age="0" ;; irix|nonstopux) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_minor" lt_irix_increment=no ;; *) func_fatal_configuration "$modename: unknown library version type \`$version_type'" ;; esac ;; no) current="$1" revision="$2" age="$3" ;; esac # Check that each of the things are valid numbers. case $current in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "CURRENT \`$current' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $revision in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "REVISION \`$revision' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $age in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "AGE \`$age' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac if test "$age" -gt "$current"; then func_error "AGE \`$age' is greater than the current interface number \`$current'" func_fatal_error "\`$vinfo' is not valid version information" fi # Calculate the version variables. major= versuffix= verstring= case $version_type in none) ;; darwin) # Like Linux, but with the current version available in # verstring for coding it into the library header func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" # Darwin ld doesn't like 0 for these options... func_arith $current + 1 minor_current=$func_arith_result xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision" verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" ;; freebsd-aout) major=".$current" versuffix=".$current.$revision"; ;; freebsd-elf) major=".$current" versuffix=".$current" ;; irix | nonstopux) if test "X$lt_irix_increment" = "Xno"; then func_arith $current - $age else func_arith $current - $age + 1 fi major=$func_arith_result case $version_type in nonstopux) verstring_prefix=nonstopux ;; *) verstring_prefix=sgi ;; esac verstring="$verstring_prefix$major.$revision" # Add in all the interfaces that we are compatible with. loop=$revision while test "$loop" -ne 0; do func_arith $revision - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring_prefix$major.$iface:$verstring" done # Before this point, $major must not contain `.'. major=.$major versuffix="$major.$revision" ;; linux) # correct to gnu/linux during the next big refactor func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" ;; osf) func_arith $current - $age major=.$func_arith_result versuffix=".$current.$age.$revision" verstring="$current.$age.$revision" # Add in all the interfaces that we are compatible with. loop=$age while test "$loop" -ne 0; do func_arith $current - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring:${iface}.0" done # Make executables depend on our current version. func_append verstring ":${current}.0" ;; qnx) major=".$current" versuffix=".$current" ;; sunos) major=".$current" versuffix=".$current.$revision" ;; windows) # Use '-' rather than '.', since we only want one # extension on DOS 8.3 filesystems. func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; *) func_fatal_configuration "unknown library version type \`$version_type'" ;; esac # Clear the version info if we defaulted, and they specified a release. if test -z "$vinfo" && test -n "$release"; then major= case $version_type in darwin) # we can't check for "0.0" in archive_cmds due to quoting # problems, so we reset it completely verstring= ;; *) verstring="0.0" ;; esac if test "$need_version" = no; then versuffix= else versuffix=".0.0" fi fi # Remove version info from name if versioning should be avoided if test "$avoid_version" = yes && test "$need_version" = no; then major= versuffix= verstring="" fi # Check to see if the archive will have undefined symbols. if test "$allow_undefined" = yes; then if test "$allow_undefined_flag" = unsupported; then func_warning "undefined symbols not allowed in $host shared libraries" build_libtool_libs=no build_old_libs=yes fi else # Don't allow undefined symbols. allow_undefined_flag="$no_undefined_flag" fi fi func_generate_dlsyms "$libname" "$libname" "yes" func_append libobjs " $symfileobj" test "X$libobjs" = "X " && libobjs= if test "$opt_mode" != relink; then # Remove our outputs, but don't remove object files since they # may have been created when compiling PIC objects. removelist= tempremovelist=`$ECHO "$output_objdir/*"` for p in $tempremovelist; do case $p in *.$objext | *.gcno) ;; $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) if test "X$precious_files_regex" != "X"; then if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 then continue fi fi func_append removelist " $p" ;; *) ;; esac done test -n "$removelist" && \ func_show_eval "${RM}r \$removelist" fi # Now set the variables for building old libraries. if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then func_append oldlibs " $output_objdir/$libname.$libext" # Transform .lo files to .o files. oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP` fi # Eliminate all temporary directories. #for path in $notinst_path; do # lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"` # deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"` # dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"` #done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. temp_xrpath= for libdir in $xrpath; do func_replace_sysroot "$libdir" func_append temp_xrpath " -R$func_replace_sysroot_result" case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then dependency_libs="$temp_xrpath $dependency_libs" fi fi # Make sure dlfiles contains only unique files that won't be dlpreopened old_dlfiles="$dlfiles" dlfiles= for lib in $old_dlfiles; do case " $dlprefiles $dlfiles " in *" $lib "*) ;; *) func_append dlfiles " $lib" ;; esac done # Make sure dlprefiles contains only unique files old_dlprefiles="$dlprefiles" dlprefiles= for lib in $old_dlprefiles; do case "$dlprefiles " in *" $lib "*) ;; *) func_append dlprefiles " $lib" ;; esac done if test "$build_libtool_libs" = yes; then if test -n "$rpath"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) # these systems don't actually have a c library (as such)! ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C library is in the System framework func_append deplibs " System.ltframework" ;; *-*-netbsd*) # Don't link with libc until the a.out ld.so is fixed. ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work ;; *) # Add libc to deplibs on all other systems if necessary. if test "$build_libtool_need_lc" = "yes"; then func_append deplibs " -lc" fi ;; esac fi # Transform deplibs into only deplibs that can be linked in shared. name_save=$name libname_save=$libname release_save=$release versuffix_save=$versuffix major_save=$major # I'm not sure if I'm treating the release correctly. I think # release should show up in the -l (ie -lgmp5) so we don't want to # add it in twice. Is that correct? release="" versuffix="" major="" newdeplibs= droppeddeps=no case $deplibs_check_method in pass_all) # Don't check for shared/static. Everything works. # This might be a little naive. We might want to check # whether the library exists or not. But this is on # osf3 & osf4 and I'm not really sure... Just # implementing what was already the behavior. newdeplibs=$deplibs ;; test_compile) # This code stresses the "libraries are programs" paradigm to its # limits. Maybe even breaks it. We compile a program, linking it # against the deplibs as a proxy for the library. Then we can check # whether they linked in statically or dynamically with ldd. $opt_dry_run || $RM conftest.c cat > conftest.c </dev/null` $nocaseglob else potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` fi for potent_lib in $potential_libs; do # Follow soft links. if ls -lLd "$potent_lib" 2>/dev/null | $GREP " -> " >/dev/null; then continue fi # The statement above tries to avoid entering an # endless loop below, in case of cyclic links. # We might still enter an endless loop, since a link # loop can be closed while we follow links, # but so what? potlib="$potent_lib" while test -h "$potlib" 2>/dev/null; do potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` case $potliblink in [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; *) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";; esac done if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | $SED -e 10q | $EGREP "$file_magic_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for file magic test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a file magic. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $a_deplib "*) func_append newdeplibs " $a_deplib" a_deplib="" ;; esac fi if test -n "$a_deplib" ; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do potlib="$potent_lib" # see symlink-check above in file_magic test if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \ $EGREP "$match_pattern_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a regex pattern. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; none | unknown | *) newdeplibs="" tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'` if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then for i in $predeps $postdeps ; do # can't use Xsed below, because $i might contain '/' tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"` done fi case $tmp_deplibs in *[!\ \ ]*) echo if test "X$deplibs_check_method" = "Xnone"; then echo "*** Warning: inter-library dependencies are not supported in this platform." else echo "*** Warning: inter-library dependencies are not known to be supported." fi echo "*** All declared inter-library dependencies are being dropped." droppeddeps=yes ;; esac ;; esac versuffix=$versuffix_save major=$major_save release=$release_save libname=$libname_save name=$name_save case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library with the System framework newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac if test "$droppeddeps" = yes; then if test "$module" = yes; then echo echo "*** Warning: libtool could not satisfy all declared inter-library" $ECHO "*** dependencies of module $libname. Therefore, libtool will create" echo "*** a static module, that should work as long as the dlopening" echo "*** application is linked with the -dlopen flag." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using \`nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi else echo "*** The inter-library dependencies that have been dropped here will be" echo "*** automatically added whenever a program is linked with this library" echo "*** or is declared to -dlopen it." if test "$allow_undefined" = no; then echo echo "*** Since this library must not contain undefined symbols," echo "*** because either the platform does not support them or" echo "*** it was explicitly requested with -no-undefined," echo "*** libtool will only create a static version of it." if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi fi fi # Done checking deplibs! deplibs=$newdeplibs fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" case $host in *-*-darwin*) newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done deplibs="$new_libs" # All the library-specific variables (install_libdir is set above). library_names= old_library= dlname= # Test again, we may have decided not to build it any more if test "$build_libtool_libs" = yes; then # Remove ${wl} instances when linking with ld. # FIXME: should test the right _cmds variable. case $archive_cmds in *\$LD\ *) wl= ;; esac if test "$hardcode_into_libs" = yes; then # Hardcode the library paths hardcode_libdirs= dep_rpath= rpath="$finalize_rpath" test "$opt_mode" != relink && rpath="$compile_rpath$rpath" for libdir in $rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then func_replace_sysroot "$libdir" libdir=$func_replace_sysroot_result if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append dep_rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval "dep_rpath=\"$hardcode_libdir_flag_spec\"" fi if test -n "$runpath_var" && test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" fi test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" fi shlibpath="$finalize_shlibpath" test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath" if test -n "$shlibpath"; then eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" fi # Get the real and link names of the library. eval shared_ext=\"$shrext_cmds\" eval library_names=\"$library_names_spec\" set dummy $library_names shift realname="$1" shift if test -n "$soname_spec"; then eval soname=\"$soname_spec\" else soname="$realname" fi if test -z "$dlname"; then dlname=$soname fi lib="$output_objdir/$realname" linknames= for link do func_append linknames " $link" done # Use standard objects if they are pic test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP` test "X$libobjs" = "X " && libobjs= delfiles= if test -n "$export_symbols" && test -n "$include_expsyms"; then $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" export_symbols="$output_objdir/$libname.uexp" func_append delfiles " $export_symbols" fi orig_export_symbols= case $host_os in cygwin* | mingw* | cegcc*) if test -n "$export_symbols" && test -z "$export_symbols_regex"; then # exporting using user supplied symfile if test "x`$SED 1q $export_symbols`" != xEXPORTS; then # and it's NOT already a .def file. Must figure out # which of the given symbols are data symbols and tag # them as such. So, trigger use of export_symbols_cmds. # export_symbols gets reassigned inside the "prepare # the list of exported symbols" if statement, so the # include_expsyms logic still works. orig_export_symbols="$export_symbols" export_symbols= always_export_symbols=yes fi fi ;; esac # Prepare the list of exported symbols if test -z "$export_symbols"; then if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols cmds=$export_symbols_cmds save_ifs="$IFS"; IFS='~' for cmd1 in $cmds; do IFS="$save_ifs" # Take the normal branch if the nm_file_list_spec branch # doesn't work or if tool conversion is not needed. case $nm_file_list_spec~$to_tool_file_cmd in *~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*) try_normal_branch=yes eval cmd=\"$cmd1\" func_len " $cmd" len=$func_len_result ;; *) try_normal_branch=no ;; esac if test "$try_normal_branch" = yes \ && { test "$len" -lt "$max_cmd_len" \ || test "$max_cmd_len" -le -1; } then func_show_eval "$cmd" 'exit $?' skipped_export=false elif test -n "$nm_file_list_spec"; then func_basename "$output" output_la=$func_basename_result save_libobjs=$libobjs save_output=$output output=${output_objdir}/${output_la}.nm func_to_tool_file "$output" libobjs=$nm_file_list_spec$func_to_tool_file_result func_append delfiles " $output" func_verbose "creating $NM input file list: $output" for obj in $save_libobjs; do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > "$output" eval cmd=\"$cmd1\" func_show_eval "$cmd" 'exit $?' output=$save_output libobjs=$save_libobjs skipped_export=false else # The command line is too long to execute in one step. func_verbose "using reloadable object file for export list..." skipped_export=: # Break out early, otherwise skipped_export may be # set to false by a later but shorter cmd. break fi done IFS="$save_ifs" if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi fi if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi tmp_deplibs= for test_deplib in $deplibs; do case " $convenience " in *" $test_deplib "*) ;; *) func_append tmp_deplibs " $test_deplib" ;; esac done deplibs="$tmp_deplibs" if test -n "$convenience"; then if test -n "$whole_archive_flag_spec" && test "$compiler_needs_object" = yes && test -z "$libobjs"; then # extract the archives, so we have objects to list. # TODO: could optimize this to just extract one archive. whole_archive_flag_spec= fi if test -n "$whole_archive_flag_spec"; then save_libobjs=$libobjs eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= else gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $convenience func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi fi if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then eval flag=\"$thread_safe_flag_spec\" func_append linker_flags " $flag" fi # Make a backup of the uninstalled library when relinking if test "$opt_mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? fi # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then eval test_cmds=\"$module_expsym_cmds\" cmds=$module_expsym_cmds else eval test_cmds=\"$module_cmds\" cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then eval test_cmds=\"$archive_expsym_cmds\" cmds=$archive_expsym_cmds else eval test_cmds=\"$archive_cmds\" cmds=$archive_cmds fi fi if test "X$skipped_export" != "X:" && func_len " $test_cmds" && len=$func_len_result && test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then : else # The command line is too long to link in one step, link piecewise # or, if using GNU ld and skipped_export is not :, use a linker # script. # Save the value of $output and $libobjs because we want to # use them later. If we have whole_archive_flag_spec, we # want to use save_libobjs as it was before # whole_archive_flag_spec was expanded, because we can't # assume the linker understands whole_archive_flag_spec. # This may have to be revisited, in case too many # convenience libraries get linked in and end up exceeding # the spec. if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then save_libobjs=$libobjs fi save_output=$output func_basename "$output" output_la=$func_basename_result # Clear the reloadable object creation command queue and # initialize k to one. test_cmds= concat_cmds= objlist= last_robj= k=1 if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then output=${output_objdir}/${output_la}.lnkscript func_verbose "creating GNU ld script: $output" echo 'INPUT (' > $output for obj in $save_libobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done echo ')' >> $output func_append delfiles " $output" func_to_tool_file "$output" output=$func_to_tool_file_result elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then output=${output_objdir}/${output_la}.lnk func_verbose "creating linker input file list: $output" : > $output set x $save_libobjs shift firstobj= if test "$compiler_needs_object" = yes; then firstobj="$1 " shift fi for obj do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done func_append delfiles " $output" func_to_tool_file "$output" output=$firstobj\"$file_list_spec$func_to_tool_file_result\" else if test -n "$save_libobjs"; then func_verbose "creating reloadable object files..." output=$output_objdir/$output_la-${k}.$objext eval test_cmds=\"$reload_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 # Loop over the list of objects to be linked. for obj in $save_libobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result if test "X$objlist" = X || test "$len" -lt "$max_cmd_len"; then func_append objlist " $obj" else # The command $test_cmds is almost too long, add a # command to the queue. if test "$k" -eq 1 ; then # The first file doesn't have a previous command to add. reload_objs=$objlist eval concat_cmds=\"$reload_cmds\" else # All subsequent reloadable object files will link in # the last one created. reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\" fi last_robj=$output_objdir/$output_la-${k}.$objext func_arith $k + 1 k=$func_arith_result output=$output_objdir/$output_la-${k}.$objext objlist=" $obj" func_len " $last_robj" func_arith $len0 + $func_len_result len=$func_arith_result fi done # Handle the remaining objects by creating one last # reloadable object file. All subsequent reloadable object # files will link in the last one created. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ reload_objs="$objlist $last_robj" eval concat_cmds=\"\${concat_cmds}$reload_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\" fi func_append delfiles " $output" else output= fi if ${skipped_export-false}; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols libobjs=$output # Append the command to create the export file. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi fi test -n "$save_libobjs" && func_verbose "creating a temporary reloadable object file: $output" # Loop through the commands generated above and execute them. save_ifs="$IFS"; IFS='~' for cmd in $concat_cmds; do IFS="$save_ifs" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$opt_mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" if test -n "$export_symbols_regex" && ${skipped_export-false}; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi if ${skipped_export-false}; then if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi fi libobjs=$output # Restore the value of output. output=$save_output if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= fi # Expand the library linking commands again to reset the # value of $libobjs for piecewise linking. # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then cmds=$module_expsym_cmds else cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then cmds=$archive_expsym_cmds else cmds=$archive_cmds fi fi fi if test -n "$delfiles"; then # Append the command to remove temporary files to $cmds. eval cmds=\"\$cmds~\$RM $delfiles\" fi # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi save_ifs="$IFS"; IFS='~' for cmd in $cmds; do IFS="$save_ifs" eval cmd=\"$cmd\" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$opt_mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" # Restore the uninstalled library and exit if test "$opt_mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? if test -n "$convenience"; then if test -z "$whole_archive_flag_spec"; then func_show_eval '${RM}r "$gentop"' fi fi exit $EXIT_SUCCESS fi # Create links to the real library. for linkname in $linknames; do if test "$realname" != "$linkname"; then func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' fi done # If -module or -export-dynamic was specified, set the dlname. if test "$module" = yes || test "$export_dynamic" = yes; then # On all known operating systems, these are identical. dlname="$soname" fi fi ;; obj) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for objects" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for objects" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for objects" test -n "$xrpath" && \ func_warning "\`-R' is ignored for objects" test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for objects" test -n "$release" && \ func_warning "\`-release' is ignored for objects" case $output in *.lo) test -n "$objs$old_deplibs" && \ func_fatal_error "cannot build library object \`$output' from non-libtool objects" libobj=$output func_lo2o "$libobj" obj=$func_lo2o_result ;; *) libobj= obj="$output" ;; esac # Delete the old objects. $opt_dry_run || $RM $obj $libobj # Objects from convenience libraries. This assumes # single-version convenience libraries. Whenever we create # different ones for PIC/non-PIC, this we'll have to duplicate # the extraction. reload_conv_objs= gentop= # reload_cmds runs $LD directly, so let us get rid of # -Wl from whole_archive_flag_spec and hope we can get by with # turning comma into space.. wl= if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'` else gentop="$output_objdir/${obj}x" func_append generated " $gentop" func_extract_archives $gentop $convenience reload_conv_objs="$reload_objs $func_extract_archives_result" fi fi # If we're not building shared, we need to use non_pic_objs test "$build_libtool_libs" != yes && libobjs="$non_pic_objects" # Create the old-style object. reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test output="$obj" func_execute_cmds "$reload_cmds" 'exit $?' # Exit if we aren't doing a library object file. if test -z "$libobj"; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS fi if test "$build_libtool_libs" != yes; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi # Create an invalid libtool object if no PIC, so that we don't # accidentally link it into a program. # $show "echo timestamp > $libobj" # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? exit $EXIT_SUCCESS fi if test -n "$pic_flag" || test "$pic_mode" != default; then # Only do commands if we really have different PIC objects. reload_objs="$libobjs $reload_conv_objs" output="$libobj" func_execute_cmds "$reload_cmds" 'exit $?' fi if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS ;; prog) case $host in *cygwin*) func_stripname '' '.exe' "$output" output=$func_stripname_result.exe;; esac test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for programs" test -n "$release" && \ func_warning "\`-release' is ignored for programs" test "$preload" = yes \ && test "$dlopen_support" = unknown \ && test "$dlopen_self" = unknown \ && test "$dlopen_self_static" = unknown && \ func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support." case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library is the System framework compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac case $host in *-*-darwin*) # Don't allow lazy linking, it breaks C++ global constructors # But is supposedly fixed on 10.4 or later (yay!). if test "$tagname" = CXX ; then case ${MACOSX_DEPLOYMENT_TARGET-10.0} in 10.[0123]) func_append compile_command " ${wl}-bind_at_load" func_append finalize_command " ${wl}-bind_at_load" ;; esac fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $compile_deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $compile_deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done compile_deplibs="$new_libs" func_append compile_command " $compile_deplibs" func_append finalize_command " $finalize_deplibs" if test -n "$rpath$xrpath"; then # If the user specified any rpath flags, then add them. for libdir in $rpath $xrpath; do # This is the magic to use -rpath. case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done fi # Now hardcode the library paths rpath= hardcode_libdirs= for libdir in $compile_rpath $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$libdir:"*) ;; ::) dllsearchpath=$libdir;; *) func_append dllsearchpath ":$libdir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi compile_rpath="$rpath" rpath= hardcode_libdirs= for libdir in $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$finalize_perm_rpath " in *" $libdir "*) ;; *) func_append finalize_perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi finalize_rpath="$rpath" if test -n "$libobjs" && test "$build_old_libs" = yes; then # Transform all the library objects into standard objects. compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP` finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP` fi func_generate_dlsyms "$outputname" "@PROGRAM@" "no" # template prelinking step if test -n "$prelink_cmds"; then func_execute_cmds "$prelink_cmds" 'exit $?' fi wrappers_required=yes case $host in *cegcc* | *mingw32ce*) # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. wrappers_required=no ;; *cygwin* | *mingw* ) if test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; *) if test "$need_relink" = no || test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; esac if test "$wrappers_required" = no; then # Replace the output file specification. compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'` link_command="$compile_command$compile_rpath" # We have no uninstalled library dependencies, so finalize right now. exit_status=0 func_show_eval "$link_command" 'exit_status=$?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Delete the generated files. if test -f "$output_objdir/${outputname}S.${objext}"; then func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"' fi exit $exit_status fi if test -n "$compile_shlibpath$finalize_shlibpath"; then compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" fi if test -n "$finalize_shlibpath"; then finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" fi compile_var= finalize_var= if test -n "$runpath_var"; then if test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done compile_var="$runpath_var=\"$rpath\$$runpath_var\" " fi if test -n "$finalize_perm_rpath"; then # We should set the runpath_var. rpath= for dir in $finalize_perm_rpath; do func_append rpath "$dir:" done finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " fi fi if test "$no_install" = yes; then # We don't need to create a wrapper script. link_command="$compile_var$compile_command$compile_rpath" # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'` # Delete the old output file. $opt_dry_run || $RM $output # Link the executable and exit func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi exit $EXIT_SUCCESS fi if test "$hardcode_action" = relink; then # Fast installation is not supported link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" func_warning "this platform does not like uninstalled shared libraries" func_warning "\`$output' will be relinked during installation" else if test "$fast_install" != no; then link_command="$finalize_var$compile_command$finalize_rpath" if test "$fast_install" = yes; then relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'` else # fast_install is set to needless relink_command= fi else link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" fi fi # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` # Delete the old output files. $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output_objdir/$outputname" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Now create the wrapper script. func_verbose "creating $output" # Quote the relink command for shipping. if test -n "$relink_command"; then # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done relink_command="(cd `pwd`; $relink_command)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` fi # Only actually do things if not in dry run mode. $opt_dry_run || { # win32 will think the script is a binary if it has # a .exe suffix, so we strip it off here. case $output in *.exe) func_stripname '' '.exe' "$output" output=$func_stripname_result ;; esac # test for cygwin because mv fails w/o .exe extensions case $host in *cygwin*) exeext=.exe func_stripname '' '.exe' "$outputname" outputname=$func_stripname_result ;; *) exeext= ;; esac case $host in *cygwin* | *mingw* ) func_dirname_and_basename "$output" "" "." output_name=$func_basename_result output_path=$func_dirname_result cwrappersource="$output_path/$objdir/lt-$output_name.c" cwrapper="$output_path/$output_name.exe" $RM $cwrappersource $cwrapper trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 func_emit_cwrapperexe_src > $cwrappersource # The wrapper executable is built using the $host compiler, # because it contains $host paths and files. If cross- # compiling, it, like the target executable, must be # executed on the $host or under an emulation environment. $opt_dry_run || { $LTCC $LTCFLAGS -o $cwrapper $cwrappersource $STRIP $cwrapper } # Now, create the wrapper script for func_source use: func_ltwrapper_scriptname $cwrapper $RM $func_ltwrapper_scriptname_result trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 $opt_dry_run || { # note: this script will not be executed, so do not chmod. if test "x$build" = "x$host" ; then $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result else func_emit_wrapper no > $func_ltwrapper_scriptname_result fi } ;; * ) $RM $output trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 func_emit_wrapper no > $output chmod +x $output ;; esac } exit $EXIT_SUCCESS ;; esac # See if we need to build an old-fashioned archive. for oldlib in $oldlibs; do if test "$build_libtool_libs" = convenience; then oldobjs="$libobjs_save $symfileobj" addlibs="$convenience" build_libtool_libs=no else if test "$build_libtool_libs" = module; then oldobjs="$libobjs_save" build_libtool_libs=no else oldobjs="$old_deplibs $non_pic_objects" if test "$preload" = yes && test -f "$symfileobj"; then func_append oldobjs " $symfileobj" fi fi addlibs="$old_convenience" fi if test -n "$addlibs"; then gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $addlibs func_append oldobjs " $func_extract_archives_result" fi # Do each command in the archive commands. if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then cmds=$old_archive_from_new_cmds else # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append oldobjs " $func_extract_archives_result" fi # POSIX demands no paths to be encoded in archives. We have # to avoid creating archives with duplicate basenames if we # might have to extract them afterwards, e.g., when creating a # static archive out of a convenience library, or when linking # the entirety of a libtool archive into another (currently # not supported by libtool). if (for obj in $oldobjs do func_basename "$obj" $ECHO "$func_basename_result" done | sort | sort -uc >/dev/null 2>&1); then : else echo "copying selected object files to avoid basename conflicts..." gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_mkdir_p "$gentop" save_oldobjs=$oldobjs oldobjs= counter=1 for obj in $save_oldobjs do func_basename "$obj" objbase="$func_basename_result" case " $oldobjs " in " ") oldobjs=$obj ;; *[\ /]"$objbase "*) while :; do # Make sure we don't pick an alternate name that also # overlaps. newobj=lt$counter-$objbase func_arith $counter + 1 counter=$func_arith_result case " $oldobjs " in *[\ /]"$newobj "*) ;; *) if test ! -f "$gentop/$newobj"; then break; fi ;; esac done func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" func_append oldobjs " $gentop/$newobj" ;; *) func_append oldobjs " $obj" ;; esac done fi func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result eval cmds=\"$old_archive_cmds\" func_len " $cmds" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then cmds=$old_archive_cmds elif test -n "$archiver_list_spec"; then func_verbose "using command file archive linking..." for obj in $oldobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > $output_objdir/$libname.libcmd func_to_tool_file "$output_objdir/$libname.libcmd" oldobjs=" $archiver_list_spec$func_to_tool_file_result" cmds=$old_archive_cmds else # the command line is too long to link in one step, link in parts func_verbose "using piecewise archive linking..." save_RANLIB=$RANLIB RANLIB=: objlist= concat_cmds= save_oldobjs=$oldobjs oldobjs= # Is there a better way of finding the last object in the list? for obj in $save_oldobjs do last_oldobj=$obj done eval test_cmds=\"$old_archive_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 for obj in $save_oldobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result func_append objlist " $obj" if test "$len" -lt "$max_cmd_len"; then : else # the above command should be used before it gets too long oldobjs=$objlist if test "$obj" = "$last_oldobj" ; then RANLIB=$save_RANLIB fi test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" objlist= len=$len0 fi done RANLIB=$save_RANLIB oldobjs=$objlist if test "X$oldobjs" = "X" ; then eval cmds=\"\$concat_cmds\" else eval cmds=\"\$concat_cmds~\$old_archive_cmds\" fi fi fi func_execute_cmds "$cmds" 'exit $?' done test -n "$generated" && \ func_show_eval "${RM}r$generated" # Now create the libtool archive. case $output in *.la) old_library= test "$build_old_libs" = yes && old_library="$libname.$libext" func_verbose "creating $output" # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done # Quote the link command for shipping. relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` if test "$hardcode_automatic" = yes ; then relink_command= fi # Only create the output if not a dry run. $opt_dry_run || { for installed in no yes; do if test "$installed" = yes; then if test -z "$install_libdir"; then break fi output="$output_objdir/$outputname"i # Replace all uninstalled libtool libraries with the installed ones newdependency_libs= for deplib in $dependency_libs; do case $deplib in *.la) func_basename "$deplib" name="$func_basename_result" func_resolve_sysroot "$deplib" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name" ;; -L*) func_stripname -L '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -L$func_replace_sysroot_result" ;; -R*) func_stripname -R '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -R$func_replace_sysroot_result" ;; *) func_append newdependency_libs " $deplib" ;; esac done dependency_libs="$newdependency_libs" newdlfiles= for lib in $dlfiles; do case $lib in *.la) func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name" ;; *) func_append newdlfiles " $lib" ;; esac done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in *.la) # Only pass preopened files to the pseudo-archive (for # eventual linking with the app. that links it) if we # didn't already link the preopened objects directly into # the library: func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name" ;; esac done dlprefiles="$newdlprefiles" else newdlfiles= for lib in $dlfiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlfiles " $abs" done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlprefiles " $abs" done dlprefiles="$newdlprefiles" fi $RM $output # place dlname in correct position for cygwin # In fact, it would be nice if we could use this code for all target # systems that can't hard-code library paths into their executables # and that have no shared library path variable independent of PATH, # but it turns out we can't easily determine that from inspecting # libtool variables, so we have to hard-code the OSs to which it # applies here; at the moment, that means platforms that use the PE # object format with DLL files. See the long comment at the top of # tests/bindir.at for full details. tdlname=$dlname case $host,$output,$installed,$module,$dlname in *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) # If a -bindir argument was supplied, place the dll there. if test "x$bindir" != x ; then func_relative_path "$install_libdir" "$bindir" tdlname=$func_relative_path_result$dlname else # Otherwise fall back on heuristic. tdlname=../bin/$dlname fi ;; esac $ECHO > $output "\ # $outputname - a libtool library file # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # The name that we can dlopen(3). dlname='$tdlname' # Names of this library. library_names='$library_names' # The name of the static archive. old_library='$old_library' # Linker flags that can not go in dependency_libs. inherited_linker_flags='$new_inherited_linker_flags' # Libraries that this one depends upon. dependency_libs='$dependency_libs' # Names of additional weak libraries provided by this library weak_library_names='$weak_libs' # Version information for $libname. current=$current age=$age revision=$revision # Is this an already installed library? installed=$installed # Should we warn about portability when linking against -modules? shouldnotlink=$module # Files to dlopen/dlpreopen dlopen='$dlfiles' dlpreopen='$dlprefiles' # Directory that this library needs to be installed in: libdir='$install_libdir'" if test "$installed" = no && test "$need_relink" = yes; then $ECHO >> $output "\ relink_command=\"$relink_command\"" fi done } # Do a symbolic link so that the libtool archive can be found in # LD_LIBRARY_PATH before the program is installed. func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' ;; esac exit $EXIT_SUCCESS } { test "$opt_mode" = link || test "$opt_mode" = relink; } && func_mode_link ${1+"$@"} # func_mode_uninstall arg... func_mode_uninstall () { $opt_debug RM="$nonopt" files= rmforce= exit_status=0 # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" for arg do case $arg in -f) func_append RM " $arg"; rmforce=yes ;; -*) func_append RM " $arg" ;; *) func_append files " $arg" ;; esac done test -z "$RM" && \ func_fatal_help "you must specify an RM program" rmdirs= for file in $files; do func_dirname "$file" "" "." dir="$func_dirname_result" if test "X$dir" = X.; then odir="$objdir" else odir="$dir/$objdir" fi func_basename "$file" name="$func_basename_result" test "$opt_mode" = uninstall && odir="$dir" # Remember odir for removal later, being careful to avoid duplicates if test "$opt_mode" = clean; then case " $rmdirs " in *" $odir "*) ;; *) func_append rmdirs " $odir" ;; esac fi # Don't error if the file doesn't exist and rm -f was used. if { test -L "$file"; } >/dev/null 2>&1 || { test -h "$file"; } >/dev/null 2>&1 || test -f "$file"; then : elif test -d "$file"; then exit_status=1 continue elif test "$rmforce" = yes; then continue fi rmfiles="$file" case $name in *.la) # Possibly a libtool archive, so verify it. if func_lalib_p "$file"; then func_source $dir/$name # Delete the libtool libraries and symlinks. for n in $library_names; do func_append rmfiles " $odir/$n" done test -n "$old_library" && func_append rmfiles " $odir/$old_library" case "$opt_mode" in clean) case " $library_names " in *" $dlname "*) ;; *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;; esac test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i" ;; uninstall) if test -n "$library_names"; then # Do each command in the postuninstall commands. func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi if test -n "$old_library"; then # Do each command in the old_postuninstall commands. func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi # FIXME: should reinstall the best remaining shared library. ;; esac fi ;; *.lo) # Possibly a libtool object, so verify it. if func_lalib_p "$file"; then # Read the .lo file func_source $dir/$name # Add PIC object to the list of files to remove. if test -n "$pic_object" && test "$pic_object" != none; then func_append rmfiles " $dir/$pic_object" fi # Add non-PIC object to the list of files to remove. if test -n "$non_pic_object" && test "$non_pic_object" != none; then func_append rmfiles " $dir/$non_pic_object" fi fi ;; *) if test "$opt_mode" = clean ; then noexename=$name case $file in *.exe) func_stripname '' '.exe' "$file" file=$func_stripname_result func_stripname '' '.exe' "$name" noexename=$func_stripname_result # $file with .exe has already been added to rmfiles, # add $file without .exe func_append rmfiles " $file" ;; esac # Do a test to see if this is a libtool program. if func_ltwrapper_p "$file"; then if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" relink_command= func_source $func_ltwrapper_scriptname_result func_append rmfiles " $func_ltwrapper_scriptname_result" else relink_command= func_source $dir/$noexename fi # note $name still contains .exe if it was in $file originally # as does the version of $file that was added into $rmfiles func_append rmfiles " $odir/$name $odir/${name}S.${objext}" if test "$fast_install" = yes && test -n "$relink_command"; then func_append rmfiles " $odir/lt-$name" fi if test "X$noexename" != "X$name" ; then func_append rmfiles " $odir/lt-${noexename}.c" fi fi fi ;; esac func_show_eval "$RM $rmfiles" 'exit_status=1' done # Try to remove the ${objdir}s in the directories where we deleted files for dir in $rmdirs; do if test -d "$dir"; then func_show_eval "rmdir $dir >/dev/null 2>&1" fi done exit $exit_status } { test "$opt_mode" = uninstall || test "$opt_mode" = clean; } && func_mode_uninstall ${1+"$@"} test -z "$opt_mode" && { help="$generic_help" func_fatal_help "you must specify a MODE" } test -z "$exec_cmd" && \ func_fatal_help "invalid operation mode \`$opt_mode'" if test -n "$exec_cmd"; then eval exec "$exec_cmd" exit $EXIT_FAILURE fi exit $exit_status # The TAGs below are defined such that we never get into a situation # in which we disable both kinds of libraries. Given conflicting # choices, we go for a static library, that is the most portable, # since we can't tell whether shared libraries were disabled because # the user asked for that or because the platform doesn't support # them. This is particularly important on AIX, because we don't # support having both static and shared libraries enabled at the same # time on that platform, so we default to a shared-only configuration. # If a disable-shared tag is given, we'll fallback to a static-only # configuration. But we'll never go from static-only to shared-only. # ### BEGIN LIBTOOL TAG CONFIG: disable-shared build_libtool_libs=no build_old_libs=yes # ### END LIBTOOL TAG CONFIG: disable-shared # ### BEGIN LIBTOOL TAG CONFIG: disable-static build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` # ### END LIBTOOL TAG CONFIG: disable-static # Local Variables: # mode:shell-script # sh-indentation:2 # End: # vi:sw=2 sauerbraten-0.0.20130203.dfsg/enet/callbacks.c0000644000175000017500000000160611375320316020417 0ustar vincentvincent/** @file callbacks.c @brief ENet callback functions */ #define ENET_BUILDING_LIB 1 #include "enet/enet.h" static ENetCallbacks callbacks = { malloc, free, abort }; int enet_initialize_with_callbacks (ENetVersion version, const ENetCallbacks * inits) { if (version < ENET_VERSION_CREATE (1, 3, 0)) return -1; if (inits -> malloc != NULL || inits -> free != NULL) { if (inits -> malloc == NULL || inits -> free == NULL) return -1; callbacks.malloc = inits -> malloc; callbacks.free = inits -> free; } if (inits -> no_memory != NULL) callbacks.no_memory = inits -> no_memory; return enet_initialize (); } void * enet_malloc (size_t size) { void * memory = callbacks.malloc (size); if (memory == NULL) callbacks.no_memory (); return memory; } void enet_free (void * memory) { callbacks.free (memory); } sauerbraten-0.0.20130203.dfsg/enet/docs/0000755000175000017500000000000012100771040017250 5ustar vincentvincentsauerbraten-0.0.20130203.dfsg/enet/docs/license.dox0000644000175000017500000000210611761204106021413 0ustar vincentvincent/** @page License License Copyright (c) 2002-2012 Lee Salzman Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ sauerbraten-0.0.20130203.dfsg/enet/docs/design.dox0000644000175000017500000001356311112171364021252 0ustar vincentvincent/** @page Features Features and Architecture ENet evolved specifically as a UDP networking layer for the multiplayer first person shooter Cube. Cube necessitated low latency communcation with data sent out very frequently, so TCP was an unsuitable choice due to its high latency and stream orientation. UDP, however, lacks many sometimes necessary features from TCP such as reliability, sequencing, unrestricted packet sizes, and connection management. So UDP by itself was not suitable as a network protocol either. No suitable freely available networking libraries existed at the time of ENet's creation to fill this niche. UDP and TCP could have been used together in Cube to benefit somewhat from both of their features, however, the resulting combinations of protocols still leaves much to be desired. TCP lacks multiple streams of communication without resorting to opening many sockets and complicates delineation of packets due to its buffering behavior. UDP lacks sequencing, connection management, management of bandwidth resources, and imposes limitations on the size of packets. A significant investment is required to integrate these two protocols, and the end result is worse off in features and performance than the uniform protocol presented by ENet. ENet thus attempts to address these issues and provide a single, uniform protocol layered over UDP to the developer with the best features of UDP and TCP as well as some useful features neither provide, with a much cleaner integration than any resulting from a mixture of UDP and TCP. @section CM Connection Management ENet provides a simple connection interface over which to communicate with a foreign host. The liveness of the connection is actively monitored by pinging the foreign host at frequent intervals, and also monitors the network conditions from the local host to the foreign host such as the mean round trip time and packet loss in this fashion. @section Sequencing Sequencing Rather than a single byte stream that complicates the delineation of packets, ENet presents connections as multiple, properly sequenced packet streams that simplify the transfer of various types of data. ENet provides sequencing for all packets by assigning to each sent packet a sequence number that is incremented as packets are sent. ENet guarentees that no packet with a higher sequence number will be delivered before a packet with a lower sequence number, thus ensuring packets are delivered exactly in the order they are sent. For unreliable packets, ENet will simply discard the lower sequence number packet if a packet with a higher sequence number has already been delivered. This allows the packets to be dispatched immediately as they arrive, and reduce latency of unreliable packets to an absolute minimum. For reliable packets, if a higher sequence number packet arrives, but the preceding packets in the sequence have not yet arrived, ENet will stall delivery of the higher sequence number packets until its predecessors have arrived. @section Channels Channels Since ENet will stall delivery of reliable packets to ensure proper sequencing, and consequently any packets of higher sequence number whether reliable or unreliable, in the event the reliable packet's predecessors have not yet arrived, this can introduce latency into the delivery of other packets which may not need to be as strictly ordered with respect to the packet that stalled their delivery. To combat this latency and reduce the ordering restrictions on packets, ENet provides multiple channels of communication over a given connection. Each channel is independently sequenced, and so the delivery status of a packet in one channel will not stall the delivery of other packets in another channel. @section Reliability Reliability ENet provides optional reliability of packet delivery by ensuring the foreign host acknowledges receipt of all reliable packets. ENet will attempt to resend the packet up to a reasonable amount of times, if no acknowledgement of the packet's receipt happens within a specified timeout. Retry timeouts are progressive and become more lenient with every failed attempt to allow for temporary turbulence in network conditions. @section FaR Fragmentation and Reassembly ENet will send and deliver packets regardless of size. Large packets are fragmented into many smaller packets of suitable size, and reassembled on the foreign host to recover the original packet for delivery. The process is entirely transparent to the developer. @section Aggregation Aggregation ENet aggregates all protocol commands, including acknowledgements and packet transfer, into larger protocol packets to ensure the proper utilization of the connection and to limit the opportunities for packet loss that might otherwise result in further delivery latency. @section Adaptability Adaptability ENet provides an in-flight data window for reliable packets to ensure connections are not overwhelmed by volumes of packets. It also provides a static bandwidth allocation mechanism to ensure the total volume of packets sent and received to a host don't exceed the host's capabilities. Further, ENet also provides a dynamic throttle that responds to deviations from normal network connections to rectify various types of network congestion by further limiting the volume of packets sent. @section Portability Portability ENet works on Windows and any other Unix or Unix-like platform providing a BSD sockets interface. The library has a small and stable code base that can easily be extended to support other platforms and integrates easily. ENet makes no assumptions about the underlying platform's endianess or word size. @section Freedom Freedom ENet demands no royalties and doesn't carry a viral license that would restrict you in how you might use it in your programs. ENet is licensed under a short-and-sweet MIT-style license, which gives you the freedom to do anything you want with it (well, almost anything). */ sauerbraten-0.0.20130203.dfsg/enet/docs/mainpage.dox0000644000175000017500000000313712061673417021570 0ustar vincentvincent/** @mainpage enet
http://enet.bespin.org

ENet's purpose is to provide a relatively thin, simple and robust network communication layer on top of UDP (User Datagram Protocol). The primary feature it provides is optional reliable, in-order delivery of packets. ENet omits certain higher level networking features such as authentication, lobbying, server discovery, encryption, or other similar tasks that are particularly application specific so that the library remains flexible, portable, and easily embeddable. @ref Features @ref SourceDistro @ref Installation @ref Tutorial @ref MailingList @ref IRCChannel @ref FAQ @ref License */ /** @page SourceDistro Source Distribution You can retrieve the source to ENet by downloading it in either .tar.gz form or accessing the github distribution directly. The most recent stable release (1.3.6) can be downloaded here. The last release that is protocol compatible with the 1.2 series or earlier (1.2.5) can be downloaded here You can find the most recent ENet source at the github repository. */ /** @page MailingList ENet Mailing List The enet-discuss list is for discussion of ENet, including bug reports or feature requests. */ /** @page IRCChannel ENet IRC Channel Join the \#enet channel on the freenode IRC network (irc.freenode.net) for real-time discussion about the ENet library. */ sauerbraten-0.0.20130203.dfsg/enet/docs/install.dox0000644000175000017500000000436712061673417021463 0ustar vincentvincent/** @page Installation Installation ENet should be trivially simple to integrate with most applications. First, make sure you download the latest source distribution here @ref SourceDistro. @section Unix Unix-like Operating Systems If you are using an ENet release, then you should simply be able to build it by doing the following: ./configure && make && make install If you obtained the package from github, you must have automake and autoconf available to generate the build system first by doing the following command before using the above mentioned build procedure: autoreconf -vfi @subsection SolarisBSD Solaris and BSD When building ENet under Solaris, you must specify the -lsocket and -lnsl parameters to your compiler to ensure that the sockets library is linked in. @section Windows Microsoft Windows You may simply use the included "enet.lib" or "enet64.lib" static libraries. However, if you wish to build the library yourself, then the following instructions apply: There is an included MSVC 6 project (enet.dsp) which you may use to build a suitable library file. Alternatively, you may simply drag all the ENet source files into your main project. You will have to link to the Winsock2 libraries, so make sure to add ws2_32.lib and winmm.lib to your library list (Project Settings | Link | Object/library modules). @subsection enet.dsp Building with the included enet.dsp Load the included enet.dsp. MSVC may ask you to convert it if you are on a newer version of MSVC - just allow the conversion and save the resulting project as "enet" or similar. After you build this project, it will output an "enet.lib" file to either the "Debug/" or "Release/" directory, depending on which configuration you have selected to build. By default, it should produce "Debug/enet.lib". You may then copy the resulting "enet.lib" file and the header files found in the "include/" directory to your other projects and add it to their library lists. Make sure to also link against "ws2_32.lib" and "winmm.lib" as described above. @subsection DLL DLL If you wish to build ENet as a DLL you must first define ENET_DLL within the project (Project Settings | C/C++ | Preprocessor | Preprocessor definitions) or, more invasively, simply define ENET_DLL at the top of enet.h. */ sauerbraten-0.0.20130203.dfsg/enet/docs/FAQ.dox0000644000175000017500000000161611112171364020404 0ustar vincentvincent/** @page FAQ Frequently Answered Questions @section Q1 Is ENet thread safe? ENet does not use any significant global variables, the vast majority of state is encapsulated in the ENetHost structure. As such, as long as the application guards access to this structure, then ENet should operate fine in a multithreaded environment. @section Q2 Isn't ENet just re-inventing TCP?! What's the point? In a perfect world, that would be true. But as many have found, using TCP either in lieu of or in conjunction with UDP can lead to all kinds of nightmares. TCP is a good, solid protocol, however it simply isn't up to the task of real-time games. Too much of TCP's implementation dictates a policy that isn't practical for games. If you want to use TCP, then do so -- this library is for people that either don't want to use TCP or have tried and ended up being discouraged with the performance. */ sauerbraten-0.0.20130203.dfsg/enet/docs/tutorial.dox0000644000175000017500000003002311375320316021636 0ustar vincentvincent/** @page Tutorial Tutorial @ref Initialization @ref CreateServer @ref CreateClient @ref ManageHost @ref SendingPacket @ref Disconnecting @ref Connecting @section Initialization Initialization You should include the file when using ENet. Do not include without the directory prefix, as this may cause file name conflicts on some systems. Before using ENet, you must call enet_initialize() to initialize the library. Upon program exit, you should call enet_deinitialize() so that the library may clean up any used resources. @code #include int main (int argc, char ** argv) { if (enet_initialize () != 0) { fprintf (stderr, "An error occurred while initializing ENet.\n"); return EXIT_FAILURE; } atexit (enet_deinitialize); ... ... ... } @endcode @section CreateServer Creating an ENet server Servers in ENet are constructed with enet_host_create(). You must specify an address on which to receive data and new connections, as well as the maximum allowable numbers of connected peers. You may optionally specify the incoming and outgoing bandwidth of the server in bytes per second so that ENet may try to statically manage bandwidth resources among connected peers in addition to its dynamic throttling algorithm; specifying 0 for these two options will cause ENet to rely entirely upon its dynamic throttling algorithm to manage bandwidth. When done with a host, the host may be destroyed with enet_host_destroy(). All connected peers to the host will be reset, and the resources used by the host will be freed. @code ENetAddress address; ENetHost * server; /* Bind the server to the default localhost. */ /* A specific host address can be specified by */ /* enet_address_set_host (& address, "x.x.x.x"); */ address.host = ENET_HOST_ANY; /* Bind the server to port 1234. */ address.port = 1234; server = enet_host_create (& address /* the address to bind the server host to */, 32 /* allow up to 32 clients and/or outgoing connections */, 2 /* allow up to 2 channels to be used, 0 and 1 */, 0 /* assume any amount of incoming bandwidth */, 0 /* assume any amount of outgoing bandwidth */); if (server == NULL) { fprintf (stderr, "An error occurred while trying to create an ENet server host.\n"); exit (EXIT_FAILURE); } ... ... ... enet_host_destroy(server); @endcode @section CreateClient Creating an ENet client Clients in ENet are similarly constructed with enet_host_create() when no address is specified to bind the host to. Bandwidth may be specified for the client host as in the above example. The peer count controls the maximum number of connections to other server hosts that may be simultaneously open. @code ENetHost * client; client = enet_host_create (NULL /* create a client host */, 1 /* only allow 1 outgoing connection */, 2 /* allow up 2 channels to be used, 0 and 1 */, 57600 / 8 /* 56K modem with 56 Kbps downstream bandwidth */, 14400 / 8 /* 56K modem with 14 Kbps upstream bandwidth */); if (client == NULL) { fprintf (stderr, "An error occurred while trying to create an ENet client host.\n"); exit (EXIT_FAILURE); } ... ... ... enet_host_destroy(client); @endcode @section ManageHost Managing an ENet host ENet uses a polled event model to notify the programmer of significant events. ENet hosts are polled for events with enet_host_service(), where an optional timeout value in milliseconds may be specified to control how long ENet will poll; if a timeout of 0 is specified, enet_host_service() will return immediately if there are no events to dispatch. enet_host_service() will return 1 if an event was dispatched within the specified timeout. Currently there are only four types of significant events in ENet: An event of type ENET_EVENT_TYPE_NONE is returned if no event occurred within the specified time limit. enet_host_service() will return 0 with this event. An event of type ENET_EVENT_TYPE_CONNECT is returned when either a new client host has connected to the server host or when an attempt to establish a connection with a foreign host has succeeded. Only the "peer" field of the event structure is valid for this event and contains the newly connected peer. An event of type ENET_EVENT_TYPE_RECEIVE is returned when a packet is received from a connected peer. The "peer" field contains the peer the packet was received from, "channelID" is the channel on which the packet was sent, and "packet" is the packet that was sent. The packet contained in the "packet" field must be destroyed with enet_packet_destroy() when you are done inspecting its contents. An event of type ENET_EVENT_TYPE_DISCONNECT is returned when a connected peer has either explicitly disconnected or timed out. Only the "peer" field of the event structure is valid for this event and contains the peer that disconnected. Only the "data" field of the peer is still valid on a disconnect event and must be explicitly reset. @code ENetEvent event; /* Wait up to 1000 milliseconds for an event. */ while (enet_host_service (client, & event, 1000) > 0) { switch (event.type) { case ENET_EVENT_TYPE_CONNECT: printf ("A new client connected from %x:%u.\n", event.peer -> address.host, event.peer -> address.port); /* Store any relevant client information here. */ event.peer -> data = "Client information"; break; case ENET_EVENT_TYPE_RECEIVE: printf ("A packet of length %u containing %s was received from %s on channel %u.\n", event.packet -> dataLength, event.packet -> data, event.peer -> data, event.channelID); /* Clean up the packet now that we're done using it. */ enet_packet_destroy (event.packet); break; case ENET_EVENT_TYPE_DISCONNECT: printf ("%s disconected.\n", event.peer -> data); /* Reset the peer's client information. */ event.peer -> data = NULL; } } ... ... ... @endcode @section SendingPacket Sending a packet to an ENet peer Packets in ENet are created with enet_packet_create(), where the size of the packet must be specified. Optionally, initial data may be specified to copy into the packet. Certain flags may also be supplied to enet_packet_create() to control various packet features: ENET_PACKET_FLAG_RELIABLE specifies that the packet must use reliable delivery. A reliable packet is guarenteed to be delivered, and a number of retry attempts will be made until an acknowledgement is received from the foreign host the packet is sent to. If a certain number of retry attempts is reached without any acknowledgement, ENet will assume the peer has disconnected and forcefully reset the connection. If this flag is not specified, the packet is assumed an unreliable packet, and no retry attempts will be made nor acknowledgements generated. A packet may be resized (extended or truncated) with enet_packet_resize(). A packet is sent to a foreign host with enet_peer_send(). enet_peer_send() accepts a channel id over which to send the packet to a given peer. Once the packet is handed over to ENet with enet_peer_send(), ENet will handle its deallocation and enet_packet_destroy() should not be used upon it. One may also use enet_host_broadcast() to send a packet to all connected peers on a given host over a specified channel id, as with enet_peer_send(). Queued packets will be sent on a call to enet_host_service(). Alternatively, enet_host_flush() will send out queued packets without dispatching any events. @code /* Create a reliable packet of size 7 containing "packet\0" */ ENetPacket * packet = enet_packet_create ("packet", strlen ("packet") + 1, ENET_PACKET_FLAG_RELIABLE); /* Extend the packet so and append the string "foo", so it now */ /* contains "packetfoo\0" */ enet_packet_resize (packet, strlen ("packetfoo") + 1); strcpy (& packet -> data [strlen ("packet")], "foo"); /* Send the packet to the peer over channel id 0. */ /* One could also broadcast the packet by */ /* enet_host_broadcast (host, 0, packet); */ enet_peer_send (peer, 0, packet); ... ... ... /* One could just use enet_host_service() instead. */ enet_host_flush (host); @endcode @section Disconnecting Disconnecting an ENet peer Peers may be gently disconnected with enet_peer_disconnect(). A disconnect request will be sent to the foreign host, and ENet will wait for an acknowledgement from the foreign host before finally disconnecting. An event of type ENET_EVENT_TYPE_DISCONNECT will be generated once the disconnection succeeds. Normally timeouts apply to the disconnect acknowledgement, and so if no acknowledgement is received after a length of time the peer will be forcefully disconnected. enet_peer_reset() will forcefully disconnect a peer. The foreign host will get no notification of a disconnect and will time out on the foreign host. No event is generated. @code ENetEvent event; enet_peer_disconnect (peer, 0); /* Allow up to 3 seconds for the disconnect to succeed * and drop any packets received packets. */ while (enet_host_service (client, & event, 3000) > 0) { switch (event.type) { case ENET_EVENT_TYPE_RECEIVE: enet_packet_destroy (event.packet); break; case ENET_EVENT_TYPE_DISCONNECT: puts ("Disconnection succeeded."); return; ... ... ... } } /* We've arrived here, so the disconnect attempt didn't */ /* succeed yet. Force the connection down. */ enet_peer_reset (peer); ... ... ... @endcode @section Connecting Connecting to an ENet host A connection to a foreign host is initiated with enet_host_connect(). It accepts the address of a foreign host to connect to, and the number of channels that should be allocated for communication. If N channels are allocated for use, their channel ids will be numbered 0 through N-1. A peer representing the connection attempt is returned, or NULL if there were no available peers over which to initiate the connection. When the connection attempt succeeds, an event of type ENET_EVENT_TYPE_CONNECT will be generated. If the connection attempt times out or otherwise fails, an event of type ENET_EVENT_TYPE_DISCONNECT will be generated. @code ENetAddress address; ENetEvent event; ENetPeer *peer; /* Connect to some.server.net:1234. */ enet_address_set_host (& address, "some.server.net"); address.port = 1234; /* Initiate the connection, allocating the two channels 0 and 1. */ peer = enet_host_connect (client, & address, 2, 0); if (peer == NULL) { fprintf (stderr, "No available peers for initiating an ENet connection.\n"); exit (EXIT_FAILURE); } /* Wait up to 5 seconds for the connection attempt to succeed. */ if (enet_host_service (client, & event, 5000) > 0 && event.type == ENET_EVENT_TYPE_CONNECT) { puts ("Connection to some.server.net:1234 succeeded."); ... ... ... } else { /* Either the 5 seconds are up or a disconnect event was */ /* received. Reset the peer in the event the 5 seconds */ /* had run out without any significant event. */ enet_peer_reset (peer); puts ("Connection to some.server.net:1234 failed."); } ... ... ... @endcode */ sauerbraten-0.0.20130203.dfsg/enet/compress.c0000644000175000017500000005144611404010271020327 0ustar vincentvincent/** @file compress.c @brief An adaptive order-2 PPM range coder */ #define ENET_BUILDING_LIB 1 #include #include "enet/enet.h" typedef struct _ENetSymbol { /* binary indexed tree of symbols */ enet_uint8 value; enet_uint8 count; enet_uint16 under; enet_uint16 left, right; /* context defined by this symbol */ enet_uint16 symbols; enet_uint16 escapes; enet_uint16 total; enet_uint16 parent; } ENetSymbol; /* adaptation constants tuned aggressively for small packet sizes rather than large file compression */ enum { ENET_RANGE_CODER_TOP = 1<<24, ENET_RANGE_CODER_BOTTOM = 1<<16, ENET_CONTEXT_SYMBOL_DELTA = 3, ENET_CONTEXT_SYMBOL_MINIMUM = 1, ENET_CONTEXT_ESCAPE_MINIMUM = 1, ENET_SUBCONTEXT_ORDER = 2, ENET_SUBCONTEXT_SYMBOL_DELTA = 2, ENET_SUBCONTEXT_ESCAPE_DELTA = 5 }; /* context exclusion roughly halves compression speed, so disable for now */ #undef ENET_CONTEXT_EXCLUSION typedef struct _ENetRangeCoder { /* only allocate enough symbols for reasonable MTUs, would need to be larger for large file compression */ ENetSymbol symbols[4096]; } ENetRangeCoder; void * enet_range_coder_create (void) { ENetRangeCoder * rangeCoder = (ENetRangeCoder *) enet_malloc (sizeof (ENetRangeCoder)); if (rangeCoder == NULL) return NULL; return rangeCoder; } void enet_range_coder_destroy (void * context) { ENetRangeCoder * rangeCoder = (ENetRangeCoder *) context; if (rangeCoder == NULL) return; enet_free (rangeCoder); } #define ENET_SYMBOL_CREATE(symbol, value_, count_) \ { \ symbol = & rangeCoder -> symbols [nextSymbol ++]; \ symbol -> value = value_; \ symbol -> count = count_; \ symbol -> under = count_; \ symbol -> left = 0; \ symbol -> right = 0; \ symbol -> symbols = 0; \ symbol -> escapes = 0; \ symbol -> total = 0; \ symbol -> parent = 0; \ } #define ENET_CONTEXT_CREATE(context, escapes_, minimum) \ { \ ENET_SYMBOL_CREATE (context, 0, 0); \ (context) -> escapes = escapes_; \ (context) -> total = escapes_ + 256*minimum; \ (context) -> symbols = 0; \ } static enet_uint16 enet_symbol_rescale (ENetSymbol * symbol) { enet_uint16 total = 0; for (;;) { symbol -> count -= symbol->count >> 1; symbol -> under = symbol -> count; if (symbol -> left) symbol -> under += enet_symbol_rescale (symbol + symbol -> left); total += symbol -> under; if (! symbol -> right) break; symbol += symbol -> right; } return total; } #define ENET_CONTEXT_RESCALE(context, minimum) \ { \ (context) -> total = (context) -> symbols ? enet_symbol_rescale ((context) + (context) -> symbols) : 0; \ (context) -> escapes -= (context) -> escapes >> 1; \ (context) -> total += (context) -> escapes + 256*minimum; \ } #define ENET_RANGE_CODER_OUTPUT(value) \ { \ if (outData >= outEnd) \ return 0; \ * outData ++ = value; \ } #define ENET_RANGE_CODER_ENCODE(under, count, total) \ { \ encodeRange /= (total); \ encodeLow += (under) * encodeRange; \ encodeRange *= (count); \ for (;;) \ { \ if((encodeLow ^ (encodeLow + encodeRange)) >= ENET_RANGE_CODER_TOP) \ { \ if(encodeRange >= ENET_RANGE_CODER_BOTTOM) break; \ encodeRange = -encodeLow & (ENET_RANGE_CODER_BOTTOM - 1); \ } \ ENET_RANGE_CODER_OUTPUT (encodeLow >> 24); \ encodeRange <<= 8; \ encodeLow <<= 8; \ } \ } #define ENET_RANGE_CODER_FLUSH \ { \ while (encodeLow) \ { \ ENET_RANGE_CODER_OUTPUT (encodeLow >> 24); \ encodeLow <<= 8; \ } \ } #define ENET_RANGE_CODER_FREE_SYMBOLS \ { \ if (nextSymbol >= sizeof (rangeCoder -> symbols) / sizeof (ENetSymbol) - ENET_SUBCONTEXT_ORDER ) \ { \ nextSymbol = 0; \ ENET_CONTEXT_CREATE (root, ENET_CONTEXT_ESCAPE_MINIMUM, ENET_CONTEXT_SYMBOL_MINIMUM); \ predicted = 0; \ order = 0; \ } \ } #define ENET_CONTEXT_ENCODE(context, symbol_, value_, under_, count_, update, minimum) \ { \ under_ = value*minimum; \ count_ = minimum; \ if (! (context) -> symbols) \ { \ ENET_SYMBOL_CREATE (symbol_, value_, update); \ (context) -> symbols = symbol_ - (context); \ } \ else \ { \ ENetSymbol * node = (context) + (context) -> symbols; \ for (;;) \ { \ if (value_ < node -> value) \ { \ node -> under += update; \ if (node -> left) { node += node -> left; continue; } \ ENET_SYMBOL_CREATE (symbol_, value_, update); \ node -> left = symbol_ - node; \ } \ else \ if (value_ > node -> value) \ { \ under_ += node -> under; \ if (node -> right) { node += node -> right; continue; } \ ENET_SYMBOL_CREATE (symbol_, value_, update); \ node -> right = symbol_ - node; \ } \ else \ { \ count_ += node -> count; \ under_ += node -> under - node -> count; \ node -> under += update; \ node -> count += update; \ symbol_ = node; \ } \ break; \ } \ } \ } #ifdef ENET_CONTEXT_EXCLUSION static const ENetSymbol emptyContext = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; #define ENET_CONTEXT_WALK(context, body) \ { \ const ENetSymbol * node = (context) + (context) -> symbols; \ const ENetSymbol * stack [256]; \ size_t stackSize = 0; \ while (node -> left) \ { \ stack [stackSize ++] = node; \ node += node -> left; \ } \ for (;;) \ { \ body; \ if (node -> right) \ { \ node += node -> right; \ while (node -> left) \ { \ stack [stackSize ++] = node; \ node += node -> left; \ } \ } \ else \ if (stackSize <= 0) \ break; \ else \ node = stack [-- stackSize]; \ } \ } #define ENET_CONTEXT_ENCODE_EXCLUDE(context, value_, under, total, minimum) \ ENET_CONTEXT_WALK(context, { \ if (node -> value != value_) \ { \ enet_uint16 parentCount = rangeCoder -> symbols [node -> parent].count + minimum; \ if (node -> value < value_) \ under -= parentCount; \ total -= parentCount; \ } \ }) #endif size_t enet_range_coder_compress (void * context, const ENetBuffer * inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 * outData, size_t outLimit) { ENetRangeCoder * rangeCoder = (ENetRangeCoder *) context; enet_uint8 * outStart = outData, * outEnd = & outData [outLimit]; const enet_uint8 * inData, * inEnd; enet_uint32 encodeLow = 0, encodeRange = ~0; ENetSymbol * root; enet_uint16 predicted = 0; size_t order = 0, nextSymbol = 0; if (rangeCoder == NULL || inBufferCount <= 0 || inLimit <= 0) return 0; inData = (const enet_uint8 *) inBuffers -> data; inEnd = & inData [inBuffers -> dataLength]; inBuffers ++; inBufferCount --; ENET_CONTEXT_CREATE (root, ENET_CONTEXT_ESCAPE_MINIMUM, ENET_CONTEXT_SYMBOL_MINIMUM); for (;;) { ENetSymbol * subcontext, * symbol; #ifdef ENET_CONTEXT_EXCLUSION const ENetSymbol * childContext = & emptyContext; #endif enet_uint8 value; enet_uint16 count, under, * parent = & predicted, total; if (inData >= inEnd) { if (inBufferCount <= 0) break; inData = (const enet_uint8 *) inBuffers -> data; inEnd = & inData [inBuffers -> dataLength]; inBuffers ++; inBufferCount --; } value = * inData ++; for (subcontext = & rangeCoder -> symbols [predicted]; subcontext != root; #ifdef ENET_CONTEXT_EXCLUSION childContext = subcontext, #endif subcontext = & rangeCoder -> symbols [subcontext -> parent]) { ENET_CONTEXT_ENCODE (subcontext, symbol, value, under, count, ENET_SUBCONTEXT_SYMBOL_DELTA, 0); * parent = symbol - rangeCoder -> symbols; parent = & symbol -> parent; total = subcontext -> total; #ifdef ENET_CONTEXT_EXCLUSION if (childContext -> total > ENET_SUBCONTEXT_SYMBOL_DELTA + ENET_SUBCONTEXT_ESCAPE_DELTA) ENET_CONTEXT_ENCODE_EXCLUDE (childContext, value, under, total, 0); #endif if (count > 0) { ENET_RANGE_CODER_ENCODE (subcontext -> escapes + under, count, total); } else { if (subcontext -> escapes > 0 && subcontext -> escapes < total) ENET_RANGE_CODER_ENCODE (0, subcontext -> escapes, total); subcontext -> escapes += ENET_SUBCONTEXT_ESCAPE_DELTA; subcontext -> total += ENET_SUBCONTEXT_ESCAPE_DELTA; } subcontext -> total += ENET_SUBCONTEXT_SYMBOL_DELTA; if (count > 0xFF - 2*ENET_SUBCONTEXT_SYMBOL_DELTA || subcontext -> total > ENET_RANGE_CODER_BOTTOM - 0x100) ENET_CONTEXT_RESCALE (subcontext, 0); if (count > 0) goto nextInput; } ENET_CONTEXT_ENCODE (root, symbol, value, under, count, ENET_CONTEXT_SYMBOL_DELTA, ENET_CONTEXT_SYMBOL_MINIMUM); * parent = symbol - rangeCoder -> symbols; parent = & symbol -> parent; total = root -> total; #ifdef ENET_CONTEXT_EXCLUSION if (childContext -> total > ENET_SUBCONTEXT_SYMBOL_DELTA + ENET_SUBCONTEXT_ESCAPE_DELTA) ENET_CONTEXT_ENCODE_EXCLUDE (childContext, value, under, total, ENET_CONTEXT_SYMBOL_MINIMUM); #endif ENET_RANGE_CODER_ENCODE (root -> escapes + under, count, total); root -> total += ENET_CONTEXT_SYMBOL_DELTA; if (count > 0xFF - 2*ENET_CONTEXT_SYMBOL_DELTA + ENET_CONTEXT_SYMBOL_MINIMUM || root -> total > ENET_RANGE_CODER_BOTTOM - 0x100) ENET_CONTEXT_RESCALE (root, ENET_CONTEXT_SYMBOL_MINIMUM); nextInput: if (order >= ENET_SUBCONTEXT_ORDER) predicted = rangeCoder -> symbols [predicted].parent; else order ++; ENET_RANGE_CODER_FREE_SYMBOLS; } ENET_RANGE_CODER_FLUSH; return (size_t) (outData - outStart); } #define ENET_RANGE_CODER_SEED \ { \ if (inData < inEnd) decodeCode |= * inData ++ << 24; \ if (inData < inEnd) decodeCode |= * inData ++ << 16; \ if (inData < inEnd) decodeCode |= * inData ++ << 8; \ if (inData < inEnd) decodeCode |= * inData ++; \ } #define ENET_RANGE_CODER_READ(total) ((decodeCode - decodeLow) / (decodeRange /= (total))) #define ENET_RANGE_CODER_DECODE(under, count, total) \ { \ decodeLow += (under) * decodeRange; \ decodeRange *= (count); \ for (;;) \ { \ if((decodeLow ^ (decodeLow + decodeRange)) >= ENET_RANGE_CODER_TOP) \ { \ if(decodeRange >= ENET_RANGE_CODER_BOTTOM) break; \ decodeRange = -decodeLow & (ENET_RANGE_CODER_BOTTOM - 1); \ } \ decodeCode <<= 8; \ if (inData < inEnd) \ decodeCode |= * inData ++; \ decodeRange <<= 8; \ decodeLow <<= 8; \ } \ } #define ENET_CONTEXT_DECODE(context, symbol_, code, value_, under_, count_, update, minimum, createRoot, visitNode, createRight, createLeft) \ { \ under_ = 0; \ count_ = minimum; \ if (! (context) -> symbols) \ { \ createRoot; \ } \ else \ { \ ENetSymbol * node = (context) + (context) -> symbols; \ for (;;) \ { \ enet_uint16 after = under_ + node -> under + (node -> value + 1)*minimum, before = node -> count + minimum; \ visitNode; \ if (code >= after) \ { \ under_ += node -> under; \ if (node -> right) { node += node -> right; continue; } \ createRight; \ } \ else \ if (code < after - before) \ { \ node -> under += update; \ if (node -> left) { node += node -> left; continue; } \ createLeft; \ } \ else \ { \ value_ = node -> value; \ count_ += node -> count; \ under_ = after - before; \ node -> under += update; \ node -> count += update; \ symbol_ = node; \ } \ break; \ } \ } \ } #define ENET_CONTEXT_TRY_DECODE(context, symbol_, code, value_, under_, count_, update, minimum, exclude) \ ENET_CONTEXT_DECODE (context, symbol_, code, value_, under_, count_, update, minimum, return 0, exclude (node -> value, after, before), return 0, return 0) #define ENET_CONTEXT_ROOT_DECODE(context, symbol_, code, value_, under_, count_, update, minimum, exclude) \ ENET_CONTEXT_DECODE (context, symbol_, code, value_, under_, count_, update, minimum, \ { \ value_ = code / minimum; \ under_ = code - code%minimum; \ ENET_SYMBOL_CREATE (symbol_, value_, update); \ (context) -> symbols = symbol_ - (context); \ }, \ exclude (node -> value, after, before), \ { \ value_ = node->value + 1 + (code - after)/minimum; \ under_ = code - (code - after)%minimum; \ ENET_SYMBOL_CREATE (symbol_, value_, update); \ node -> right = symbol_ - node; \ }, \ { \ value_ = node->value - 1 - (after - before - code - 1)/minimum; \ under_ = code - (after - before - code - 1)%minimum; \ ENET_SYMBOL_CREATE (symbol_, value_, update); \ node -> left = symbol_ - node; \ }) \ #ifdef ENET_CONTEXT_EXCLUSION typedef struct _ENetExclude { enet_uint8 value; enet_uint16 under; } ENetExclude; #define ENET_CONTEXT_DECODE_EXCLUDE(context, total, minimum) \ { \ enet_uint16 under = 0; \ nextExclude = excludes; \ ENET_CONTEXT_WALK (context, { \ under += rangeCoder -> symbols [node -> parent].count + minimum; \ nextExclude -> value = node -> value; \ nextExclude -> under = under; \ nextExclude ++; \ }); \ total -= under; \ } #define ENET_CONTEXT_EXCLUDED(value_, after, before) \ { \ size_t low = 0, high = nextExclude - excludes; \ for(;;) \ { \ size_t mid = (low + high) >> 1; \ const ENetExclude * exclude = & excludes [mid]; \ if (value_ < exclude -> value) \ { \ if (low + 1 < high) \ { \ high = mid; \ continue; \ } \ if (exclude > excludes) \ after -= exclude [-1].under; \ } \ else \ { \ if (value_ > exclude -> value) \ { \ if (low + 1 < high) \ { \ low = mid; \ continue; \ } \ } \ else \ before = 0; \ after -= exclude -> under; \ } \ break; \ } \ } #endif #define ENET_CONTEXT_NOT_EXCLUDED(value_, after, before) size_t enet_range_coder_decompress (void * context, const enet_uint8 * inData, size_t inLimit, enet_uint8 * outData, size_t outLimit) { ENetRangeCoder * rangeCoder = (ENetRangeCoder *) context; enet_uint8 * outStart = outData, * outEnd = & outData [outLimit]; const enet_uint8 * inEnd = & inData [inLimit]; enet_uint32 decodeLow = 0, decodeCode = 0, decodeRange = ~0; ENetSymbol * root; enet_uint16 predicted = 0; size_t order = 0, nextSymbol = 0; #ifdef ENET_CONTEXT_EXCLUSION ENetExclude excludes [256]; ENetExclude * nextExclude = excludes; #endif if (rangeCoder == NULL || inLimit <= 0) return 0; ENET_CONTEXT_CREATE (root, ENET_CONTEXT_ESCAPE_MINIMUM, ENET_CONTEXT_SYMBOL_MINIMUM); ENET_RANGE_CODER_SEED; for (;;) { ENetSymbol * subcontext, * symbol, * patch; #ifdef ENET_CONTEXT_EXCLUSION const ENetSymbol * childContext = & emptyContext; #endif enet_uint8 value = 0; enet_uint16 code, under, count, bottom, * parent = & predicted, total; for (subcontext = & rangeCoder -> symbols [predicted]; subcontext != root; #ifdef ENET_CONTEXT_EXCLUSION childContext = subcontext, #endif subcontext = & rangeCoder -> symbols [subcontext -> parent]) { if (subcontext -> escapes <= 0) continue; total = subcontext -> total; #ifdef ENET_CONTEXT_EXCLUSION if (childContext -> total > 0) ENET_CONTEXT_DECODE_EXCLUDE (childContext, total, 0); #endif if (subcontext -> escapes >= total) continue; code = ENET_RANGE_CODER_READ (total); if (code < subcontext -> escapes) { ENET_RANGE_CODER_DECODE (0, subcontext -> escapes, total); continue; } code -= subcontext -> escapes; #ifdef ENET_CONTEXT_EXCLUSION if (childContext -> total > 0) { ENET_CONTEXT_TRY_DECODE (subcontext, symbol, code, value, under, count, ENET_SUBCONTEXT_SYMBOL_DELTA, 0, ENET_CONTEXT_EXCLUDED); } else #endif { ENET_CONTEXT_TRY_DECODE (subcontext, symbol, code, value, under, count, ENET_SUBCONTEXT_SYMBOL_DELTA, 0, ENET_CONTEXT_NOT_EXCLUDED); } bottom = symbol - rangeCoder -> symbols; ENET_RANGE_CODER_DECODE (subcontext -> escapes + under, count, total); subcontext -> total += ENET_SUBCONTEXT_SYMBOL_DELTA; if (count > 0xFF - 2*ENET_SUBCONTEXT_SYMBOL_DELTA || subcontext -> total > ENET_RANGE_CODER_BOTTOM - 0x100) ENET_CONTEXT_RESCALE (subcontext, 0); goto patchContexts; } total = root -> total; #ifdef ENET_CONTEXT_EXCLUSION if (childContext -> total > 0) ENET_CONTEXT_DECODE_EXCLUDE (childContext, total, ENET_CONTEXT_SYMBOL_MINIMUM); #endif code = ENET_RANGE_CODER_READ (total); if (code < root -> escapes) { ENET_RANGE_CODER_DECODE (0, root -> escapes, total); break; } code -= root -> escapes; #ifdef ENET_CONTEXT_EXCLUSION if (childContext -> total > 0) { ENET_CONTEXT_ROOT_DECODE (root, symbol, code, value, under, count, ENET_CONTEXT_SYMBOL_DELTA, ENET_CONTEXT_SYMBOL_MINIMUM, ENET_CONTEXT_EXCLUDED); } else #endif { ENET_CONTEXT_ROOT_DECODE (root, symbol, code, value, under, count, ENET_CONTEXT_SYMBOL_DELTA, ENET_CONTEXT_SYMBOL_MINIMUM, ENET_CONTEXT_NOT_EXCLUDED); } bottom = symbol - rangeCoder -> symbols; ENET_RANGE_CODER_DECODE (root -> escapes + under, count, total); root -> total += ENET_CONTEXT_SYMBOL_DELTA; if (count > 0xFF - 2*ENET_CONTEXT_SYMBOL_DELTA + ENET_CONTEXT_SYMBOL_MINIMUM || root -> total > ENET_RANGE_CODER_BOTTOM - 0x100) ENET_CONTEXT_RESCALE (root, ENET_CONTEXT_SYMBOL_MINIMUM); patchContexts: for (patch = & rangeCoder -> symbols [predicted]; patch != subcontext; patch = & rangeCoder -> symbols [patch -> parent]) { ENET_CONTEXT_ENCODE (patch, symbol, value, under, count, ENET_SUBCONTEXT_SYMBOL_DELTA, 0); * parent = symbol - rangeCoder -> symbols; parent = & symbol -> parent; if (count <= 0) { patch -> escapes += ENET_SUBCONTEXT_ESCAPE_DELTA; patch -> total += ENET_SUBCONTEXT_ESCAPE_DELTA; } patch -> total += ENET_SUBCONTEXT_SYMBOL_DELTA; if (count > 0xFF - 2*ENET_SUBCONTEXT_SYMBOL_DELTA || patch -> total > ENET_RANGE_CODER_BOTTOM - 0x100) ENET_CONTEXT_RESCALE (patch, 0); } * parent = bottom; ENET_RANGE_CODER_OUTPUT (value); if (order >= ENET_SUBCONTEXT_ORDER) predicted = rangeCoder -> symbols [predicted].parent; else order ++; ENET_RANGE_CODER_FREE_SYMBOLS; } return (size_t) (outData - outStart); } /** @defgroup host ENet host functions @{ */ /** Sets the packet compressor the host should use to the default range coder. @param host host to enable the range coder for @returns 0 on success, < 0 on failure */ int enet_host_compress_with_range_coder (ENetHost * host) { ENetCompressor compressor; memset (& compressor, 0, sizeof (compressor)); compressor.context = enet_range_coder_create(); if (compressor.context == NULL) return -1; compressor.compress = enet_range_coder_compress; compressor.decompress = enet_range_coder_decompress; compressor.destroy = enet_range_coder_destroy; enet_host_compress (host, & compressor); return 0; } /** @} */ sauerbraten-0.0.20130203.dfsg/enet/install-sh0000755000175000017500000003325611761204106020343 0ustar vincentvincent#!/bin/sh # install - install a program, script, or datafile scriptversion=2011-01-19.21; # UTC # This originates from X11R5 (mit/util/scripts/install.sh), which was # later released in X11R6 (xc/config/util/install.sh) with the # following copyright and license. # # Copyright (C) 1994 X Consortium # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- # TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # Except as contained in this notice, the name of the X Consortium shall not # be used in advertising or otherwise to promote the sale, use or other deal- # ings in this Software without prior written authorization from the X Consor- # tium. # # # FSF changes to this file are in the public domain. # # Calling this script install-sh is preferred over install.sh, to prevent # `make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written # from scratch. nl=' ' IFS=" "" $nl" # set DOITPROG to echo to test this script # Don't use :- since 4.3BSD and earlier shells don't like it. doit=${DOITPROG-} if test -z "$doit"; then doit_exec=exec else doit_exec=$doit fi # Put in absolute file names if you don't have them in your path; # or use environment vars. chgrpprog=${CHGRPPROG-chgrp} chmodprog=${CHMODPROG-chmod} chownprog=${CHOWNPROG-chown} cmpprog=${CMPPROG-cmp} cpprog=${CPPROG-cp} mkdirprog=${MKDIRPROG-mkdir} mvprog=${MVPROG-mv} rmprog=${RMPROG-rm} stripprog=${STRIPPROG-strip} posix_glob='?' initialize_posix_glob=' test "$posix_glob" != "?" || { if (set -f) 2>/dev/null; then posix_glob= else posix_glob=: fi } ' posix_mkdir= # Desired mode of installed file. mode=0755 chgrpcmd= chmodcmd=$chmodprog chowncmd= mvcmd=$mvprog rmcmd="$rmprog -f" stripcmd= src= dst= dir_arg= dst_arg= copy_on_change=false no_target_directory= usage="\ Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE or: $0 [OPTION]... SRCFILES... DIRECTORY or: $0 [OPTION]... -t DIRECTORY SRCFILES... or: $0 [OPTION]... -d DIRECTORIES... In the 1st form, copy SRCFILE to DSTFILE. In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. In the 4th, create DIRECTORIES. Options: --help display this help and exit. --version display version info and exit. -c (ignored) -C install only if different (preserve the last data modification time) -d create directories instead of installing files. -g GROUP $chgrpprog installed files to GROUP. -m MODE $chmodprog installed files to MODE. -o USER $chownprog installed files to USER. -s $stripprog installed files. -t DIRECTORY install into DIRECTORY. -T report an error if DSTFILE is a directory. Environment variables override the default commands: CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG " while test $# -ne 0; do case $1 in -c) ;; -C) copy_on_change=true;; -d) dir_arg=true;; -g) chgrpcmd="$chgrpprog $2" shift;; --help) echo "$usage"; exit $?;; -m) mode=$2 case $mode in *' '* | *' '* | *' '* | *'*'* | *'?'* | *'['*) echo "$0: invalid mode: $mode" >&2 exit 1;; esac shift;; -o) chowncmd="$chownprog $2" shift;; -s) stripcmd=$stripprog;; -t) dst_arg=$2 # Protect names problematic for `test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac shift;; -T) no_target_directory=true;; --version) echo "$0 $scriptversion"; exit $?;; --) shift break;; -*) echo "$0: invalid option: $1" >&2 exit 1;; *) break;; esac shift done if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then # When -d is used, all remaining arguments are directories to create. # When -t is used, the destination is already specified. # Otherwise, the last argument is the destination. Remove it from $@. for arg do if test -n "$dst_arg"; then # $@ is not empty: it contains at least $arg. set fnord "$@" "$dst_arg" shift # fnord fi shift # arg dst_arg=$arg # Protect names problematic for `test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac done fi if test $# -eq 0; then if test -z "$dir_arg"; then echo "$0: no input file specified." >&2 exit 1 fi # It's OK to call `install-sh -d' without argument. # This can happen when creating conditional directories. exit 0 fi if test -z "$dir_arg"; then do_exit='(exit $ret); exit $ret' trap "ret=129; $do_exit" 1 trap "ret=130; $do_exit" 2 trap "ret=141; $do_exit" 13 trap "ret=143; $do_exit" 15 # Set umask so as not to create temps with too-generous modes. # However, 'strip' requires both read and write access to temps. case $mode in # Optimize common cases. *644) cp_umask=133;; *755) cp_umask=22;; *[0-7]) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw='% 200' fi cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; *) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw=,u+rw fi cp_umask=$mode$u_plus_rw;; esac fi for src do # Protect names problematic for `test' and other utilities. case $src in -* | [=\(\)!]) src=./$src;; esac if test -n "$dir_arg"; then dst=$src dstdir=$dst test -d "$dstdir" dstdir_status=$? else # Waiting for this to be detected by the "$cpprog $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if test ! -f "$src" && test ! -d "$src"; then echo "$0: $src does not exist." >&2 exit 1 fi if test -z "$dst_arg"; then echo "$0: no destination specified." >&2 exit 1 fi dst=$dst_arg # If destination is a directory, append the input filename; won't work # if double slashes aren't ignored. if test -d "$dst"; then if test -n "$no_target_directory"; then echo "$0: $dst_arg: Is a directory" >&2 exit 1 fi dstdir=$dst dst=$dstdir/`basename "$src"` dstdir_status=0 else # Prefer dirname, but fall back on a substitute if dirname fails. dstdir=` (dirname "$dst") 2>/dev/null || expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$dst" : 'X\(//\)[^/]' \| \ X"$dst" : 'X\(//\)$' \| \ X"$dst" : 'X\(/\)' \| . 2>/dev/null || echo X"$dst" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q' ` test -d "$dstdir" dstdir_status=$? fi fi obsolete_mkdir_used=false if test $dstdir_status != 0; then case $posix_mkdir in '') # Create intermediate dirs using mode 755 as modified by the umask. # This is like FreeBSD 'install' as of 1997-10-28. umask=`umask` case $stripcmd.$umask in # Optimize common cases. *[2367][2367]) mkdir_umask=$umask;; .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; *[0-7]) mkdir_umask=`expr $umask + 22 \ - $umask % 100 % 40 + $umask % 20 \ - $umask % 10 % 4 + $umask % 2 `;; *) mkdir_umask=$umask,go-w;; esac # With -d, create the new directory with the user-specified mode. # Otherwise, rely on $mkdir_umask. if test -n "$dir_arg"; then mkdir_mode=-m$mode else mkdir_mode= fi posix_mkdir=false case $umask in *[123567][0-7][0-7]) # POSIX mkdir -p sets u+wx bits regardless of umask, which # is incompatible with FreeBSD 'install' when (umask & 300) != 0. ;; *) tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 if (umask $mkdir_umask && exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 then if test -z "$dir_arg" || { # Check for POSIX incompatibilities with -m. # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or # other-writeable bit of parent directory when it shouldn't. # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. ls_ld_tmpdir=`ls -ld "$tmpdir"` case $ls_ld_tmpdir in d????-?r-*) different_mode=700;; d????-?--*) different_mode=755;; *) false;; esac && $mkdirprog -m$different_mode -p -- "$tmpdir" && { ls_ld_tmpdir_1=`ls -ld "$tmpdir"` test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" } } then posix_mkdir=: fi rmdir "$tmpdir/d" "$tmpdir" else # Remove any dirs left behind by ancient mkdir implementations. rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null fi trap '' 0;; esac;; esac if $posix_mkdir && ( umask $mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" ) then : else # The umask is ridiculous, or mkdir does not conform to POSIX, # or it failed possibly due to a race condition. Create the # directory the slow way, step by step, checking for races as we go. case $dstdir in /*) prefix='/';; [-=\(\)!]*) prefix='./';; *) prefix='';; esac eval "$initialize_posix_glob" oIFS=$IFS IFS=/ $posix_glob set -f set fnord $dstdir shift $posix_glob set +f IFS=$oIFS prefixes= for d do test X"$d" = X && continue prefix=$prefix$d if test -d "$prefix"; then prefixes= else if $posix_mkdir; then (umask=$mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break # Don't fail if two instances are running concurrently. test -d "$prefix" || exit 1 else case $prefix in *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; *) qprefix=$prefix;; esac prefixes="$prefixes '$qprefix'" fi fi prefix=$prefix/ done if test -n "$prefixes"; then # Don't fail if two instances are running concurrently. (umask $mkdir_umask && eval "\$doit_exec \$mkdirprog $prefixes") || test -d "$dstdir" || exit 1 obsolete_mkdir_used=true fi fi fi if test -n "$dir_arg"; then { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 else # Make a couple of temp file names in the proper directory. dsttmp=$dstdir/_inst.$$_ rmtmp=$dstdir/_rm.$$_ # Trap to clean up those temp files at exit. trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 # Copy the file name to the temp name. (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && # and set any options; do chmod last to preserve setuid bits. # # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $cpprog $src $dsttmp" command. # { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && # If -C, don't bother to copy if it wouldn't change the file. if $copy_on_change && old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && eval "$initialize_posix_glob" && $posix_glob set -f && set X $old && old=:$2:$4:$5:$6 && set X $new && new=:$2:$4:$5:$6 && $posix_glob set +f && test "$old" = "$new" && $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 then rm -f "$dsttmp" else # Rename the file to the real destination. $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || # The rename failed, perhaps because mv can't rename something else # to itself, or perhaps because mv is so ancient that it does not # support -f. { # Now remove or move aside any old file at destination location. # We try this two ways since rm can't unlink itself on some # systems and the destination file might be busy for other # reasons. In this case, the final cleanup might fail but the new # file should still install successfully. { test ! -f "$dst" || $doit $rmcmd -f "$dst" 2>/dev/null || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; } } || { echo "$0: cannot unlink or rename $dst" >&2 (exit 1); exit 1 } } && # Now rename the file to the real destination. $doit $mvcmd "$dsttmp" "$dst" } fi || exit 1 trap '' 0 fi done # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: sauerbraten-0.0.20130203.dfsg/enet/configure.ac0000644000175000017500000000173612061673417020634 0ustar vincentvincentAC_INIT([libenet], [1.3.6]) AC_CONFIG_SRCDIR([include/enet/enet.h]) AM_INIT_AUTOMAKE([foreign]) AM_MAINTAINER_MODE([enable]) AC_CONFIG_MACRO_DIR([m4]) AC_PROG_CC AC_PROG_LIBTOOL AC_CHECK_FUNC(gethostbyaddr_r, [AC_DEFINE(HAS_GETHOSTBYADDR_R)]) AC_CHECK_FUNC(gethostbyname_r, [AC_DEFINE(HAS_GETHOSTBYNAME_R)]) AC_CHECK_FUNC(poll, [AC_DEFINE(HAS_POLL)]) AC_CHECK_FUNC(fcntl, [AC_DEFINE(HAS_FCNTL)]) AC_CHECK_FUNC(inet_pton, [AC_DEFINE(HAS_INET_PTON)]) AC_CHECK_FUNC(inet_ntop, [AC_DEFINE(HAS_INET_NTOP)]) AC_CHECK_MEMBER(struct msghdr.msg_flags, [AC_DEFINE(HAS_MSGHDR_FLAGS)], , [#include ]) AC_CHECK_TYPE(socklen_t, [AC_DEFINE(HAS_SOCKLEN_T)], , #include #include ) AC_EGREP_HEADER(MSG_MAXIOVLEN, /usr/include/sys/socket.h, AC_DEFINE(ENET_BUFFER_MAXIMUM, [MSG_MAXIOVLEN])) AC_EGREP_HEADER(MSG_MAXIOVLEN, socket.h, AC_DEFINE(ENET_BUFFER_MAXIMUM, [MSG_MAXIOVLEN])) AC_CONFIG_FILES([Makefile libenet.pc]) AC_OUTPUT sauerbraten-0.0.20130203.dfsg/enet/protocol.c0000644000175000017500000020766112061673417020360 0ustar vincentvincent/** @file protocol.c @brief ENet protocol functions */ #include #include #define ENET_BUILDING_LIB 1 #include "enet/utility.h" #include "enet/time.h" #include "enet/enet.h" static size_t commandSizes [ENET_PROTOCOL_COMMAND_COUNT] = { 0, sizeof (ENetProtocolAcknowledge), sizeof (ENetProtocolConnect), sizeof (ENetProtocolVerifyConnect), sizeof (ENetProtocolDisconnect), sizeof (ENetProtocolPing), sizeof (ENetProtocolSendReliable), sizeof (ENetProtocolSendUnreliable), sizeof (ENetProtocolSendFragment), sizeof (ENetProtocolSendUnsequenced), sizeof (ENetProtocolBandwidthLimit), sizeof (ENetProtocolThrottleConfigure), sizeof (ENetProtocolSendFragment) }; size_t enet_protocol_command_size (enet_uint8 commandNumber) { return commandSizes [commandNumber & ENET_PROTOCOL_COMMAND_MASK]; } static int enet_protocol_dispatch_incoming_commands (ENetHost * host, ENetEvent * event) { while (! enet_list_empty (& host -> dispatchQueue)) { ENetPeer * peer = (ENetPeer *) enet_list_remove (enet_list_begin (& host -> dispatchQueue)); peer -> needsDispatch = 0; switch (peer -> state) { case ENET_PEER_STATE_CONNECTION_PENDING: case ENET_PEER_STATE_CONNECTION_SUCCEEDED: peer -> state = ENET_PEER_STATE_CONNECTED; event -> type = ENET_EVENT_TYPE_CONNECT; event -> peer = peer; event -> data = peer -> eventData; return 1; case ENET_PEER_STATE_ZOMBIE: host -> recalculateBandwidthLimits = 1; event -> type = ENET_EVENT_TYPE_DISCONNECT; event -> peer = peer; event -> data = peer -> eventData; enet_peer_reset (peer); return 1; case ENET_PEER_STATE_CONNECTED: if (enet_list_empty (& peer -> dispatchedCommands)) continue; event -> packet = enet_peer_receive (peer, & event -> channelID); if (event -> packet == NULL) continue; event -> type = ENET_EVENT_TYPE_RECEIVE; event -> peer = peer; if (! enet_list_empty (& peer -> dispatchedCommands)) { peer -> needsDispatch = 1; enet_list_insert (enet_list_end (& host -> dispatchQueue), & peer -> dispatchList); } return 1; default: break; } } return 0; } static void enet_protocol_dispatch_state (ENetHost * host, ENetPeer * peer, ENetPeerState state) { peer -> state = state; if (! peer -> needsDispatch) { enet_list_insert (enet_list_end (& host -> dispatchQueue), & peer -> dispatchList); peer -> needsDispatch = 1; } } static void enet_protocol_notify_connect (ENetHost * host, ENetPeer * peer, ENetEvent * event) { host -> recalculateBandwidthLimits = 1; if (event != NULL) { peer -> state = ENET_PEER_STATE_CONNECTED; event -> type = ENET_EVENT_TYPE_CONNECT; event -> peer = peer; event -> data = peer -> eventData; } else enet_protocol_dispatch_state (host, peer, peer -> state == ENET_PEER_STATE_CONNECTING ? ENET_PEER_STATE_CONNECTION_SUCCEEDED : ENET_PEER_STATE_CONNECTION_PENDING); } static void enet_protocol_notify_disconnect (ENetHost * host, ENetPeer * peer, ENetEvent * event) { if (peer -> state >= ENET_PEER_STATE_CONNECTION_PENDING) host -> recalculateBandwidthLimits = 1; if (peer -> state != ENET_PEER_STATE_CONNECTING && peer -> state < ENET_PEER_STATE_CONNECTION_SUCCEEDED) enet_peer_reset (peer); else if (event != NULL) { event -> type = ENET_EVENT_TYPE_DISCONNECT; event -> peer = peer; event -> data = 0; enet_peer_reset (peer); } else { peer -> eventData = 0; enet_protocol_dispatch_state (host, peer, ENET_PEER_STATE_ZOMBIE); } } static void enet_protocol_remove_sent_unreliable_commands (ENetPeer * peer) { ENetOutgoingCommand * outgoingCommand; while (! enet_list_empty (& peer -> sentUnreliableCommands)) { outgoingCommand = (ENetOutgoingCommand *) enet_list_front (& peer -> sentUnreliableCommands); enet_list_remove (& outgoingCommand -> outgoingCommandList); if (outgoingCommand -> packet != NULL) { -- outgoingCommand -> packet -> referenceCount; if (outgoingCommand -> packet -> referenceCount == 0) enet_packet_destroy (outgoingCommand -> packet); } enet_free (outgoingCommand); } } static ENetProtocolCommand enet_protocol_remove_sent_reliable_command (ENetPeer * peer, enet_uint16 reliableSequenceNumber, enet_uint8 channelID) { ENetOutgoingCommand * outgoingCommand = NULL; ENetListIterator currentCommand; ENetProtocolCommand commandNumber; int wasSent = 1; for (currentCommand = enet_list_begin (& peer -> sentReliableCommands); currentCommand != enet_list_end (& peer -> sentReliableCommands); currentCommand = enet_list_next (currentCommand)) { outgoingCommand = (ENetOutgoingCommand *) currentCommand; if (outgoingCommand -> reliableSequenceNumber == reliableSequenceNumber && outgoingCommand -> command.header.channelID == channelID) break; } if (currentCommand == enet_list_end (& peer -> sentReliableCommands)) { for (currentCommand = enet_list_begin (& peer -> outgoingReliableCommands); currentCommand != enet_list_end (& peer -> outgoingReliableCommands); currentCommand = enet_list_next (currentCommand)) { outgoingCommand = (ENetOutgoingCommand *) currentCommand; if (outgoingCommand -> sendAttempts < 1) return ENET_PROTOCOL_COMMAND_NONE; if (outgoingCommand -> reliableSequenceNumber == reliableSequenceNumber && outgoingCommand -> command.header.channelID == channelID) break; } if (currentCommand == enet_list_end (& peer -> outgoingReliableCommands)) return ENET_PROTOCOL_COMMAND_NONE; wasSent = 0; } if (outgoingCommand == NULL) return ENET_PROTOCOL_COMMAND_NONE; if (channelID < peer -> channelCount) { ENetChannel * channel = & peer -> channels [channelID]; enet_uint16 reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE; if (channel -> reliableWindows [reliableWindow] > 0) { -- channel -> reliableWindows [reliableWindow]; if (! channel -> reliableWindows [reliableWindow]) channel -> usedReliableWindows &= ~ (1 << reliableWindow); } } commandNumber = (ENetProtocolCommand) (outgoingCommand -> command.header.command & ENET_PROTOCOL_COMMAND_MASK); enet_list_remove (& outgoingCommand -> outgoingCommandList); if (outgoingCommand -> packet != NULL) { if (wasSent) peer -> reliableDataInTransit -= outgoingCommand -> fragmentLength; -- outgoingCommand -> packet -> referenceCount; if (outgoingCommand -> packet -> referenceCount == 0) enet_packet_destroy (outgoingCommand -> packet); } enet_free (outgoingCommand); if (enet_list_empty (& peer -> sentReliableCommands)) return commandNumber; outgoingCommand = (ENetOutgoingCommand *) enet_list_front (& peer -> sentReliableCommands); peer -> nextTimeout = outgoingCommand -> sentTime + outgoingCommand -> roundTripTimeout; return commandNumber; } static ENetPeer * enet_protocol_handle_connect (ENetHost * host, ENetProtocolHeader * header, ENetProtocol * command) { enet_uint8 incomingSessionID, outgoingSessionID; enet_uint32 mtu, windowSize; ENetChannel * channel; size_t channelCount; ENetPeer * currentPeer; ENetProtocol verifyCommand; channelCount = ENET_NET_TO_HOST_32 (command -> connect.channelCount); if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT || channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT) return NULL; for (currentPeer = host -> peers; currentPeer < & host -> peers [host -> peerCount]; ++ currentPeer) { if (currentPeer -> state != ENET_PEER_STATE_DISCONNECTED && currentPeer -> address.host == host -> receivedAddress.host && currentPeer -> address.port == host -> receivedAddress.port && currentPeer -> connectID == command -> connect.connectID) return NULL; } for (currentPeer = host -> peers; currentPeer < & host -> peers [host -> peerCount]; ++ currentPeer) { if (currentPeer -> state == ENET_PEER_STATE_DISCONNECTED) break; } if (currentPeer >= & host -> peers [host -> peerCount]) return NULL; if (channelCount > host -> channelLimit) channelCount = host -> channelLimit; currentPeer -> channels = (ENetChannel *) enet_malloc (channelCount * sizeof (ENetChannel)); if (currentPeer -> channels == NULL) return NULL; currentPeer -> channelCount = channelCount; currentPeer -> state = ENET_PEER_STATE_ACKNOWLEDGING_CONNECT; currentPeer -> connectID = command -> connect.connectID; currentPeer -> address = host -> receivedAddress; currentPeer -> outgoingPeerID = ENET_NET_TO_HOST_16 (command -> connect.outgoingPeerID); currentPeer -> incomingBandwidth = ENET_NET_TO_HOST_32 (command -> connect.incomingBandwidth); currentPeer -> outgoingBandwidth = ENET_NET_TO_HOST_32 (command -> connect.outgoingBandwidth); currentPeer -> packetThrottleInterval = ENET_NET_TO_HOST_32 (command -> connect.packetThrottleInterval); currentPeer -> packetThrottleAcceleration = ENET_NET_TO_HOST_32 (command -> connect.packetThrottleAcceleration); currentPeer -> packetThrottleDeceleration = ENET_NET_TO_HOST_32 (command -> connect.packetThrottleDeceleration); currentPeer -> eventData = ENET_NET_TO_HOST_32 (command -> connect.data); incomingSessionID = command -> connect.incomingSessionID == 0xFF ? currentPeer -> outgoingSessionID : command -> connect.incomingSessionID; incomingSessionID = (incomingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT); if (incomingSessionID == currentPeer -> outgoingSessionID) incomingSessionID = (incomingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT); currentPeer -> outgoingSessionID = incomingSessionID; outgoingSessionID = command -> connect.outgoingSessionID == 0xFF ? currentPeer -> incomingSessionID : command -> connect.outgoingSessionID; outgoingSessionID = (outgoingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT); if (outgoingSessionID == currentPeer -> incomingSessionID) outgoingSessionID = (outgoingSessionID + 1) & (ENET_PROTOCOL_HEADER_SESSION_MASK >> ENET_PROTOCOL_HEADER_SESSION_SHIFT); currentPeer -> incomingSessionID = outgoingSessionID; for (channel = currentPeer -> channels; channel < & currentPeer -> channels [channelCount]; ++ channel) { channel -> outgoingReliableSequenceNumber = 0; channel -> outgoingUnreliableSequenceNumber = 0; channel -> incomingReliableSequenceNumber = 0; channel -> incomingUnreliableSequenceNumber = 0; enet_list_clear (& channel -> incomingReliableCommands); enet_list_clear (& channel -> incomingUnreliableCommands); channel -> usedReliableWindows = 0; memset (channel -> reliableWindows, 0, sizeof (channel -> reliableWindows)); } mtu = ENET_NET_TO_HOST_32 (command -> connect.mtu); if (mtu < ENET_PROTOCOL_MINIMUM_MTU) mtu = ENET_PROTOCOL_MINIMUM_MTU; else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU) mtu = ENET_PROTOCOL_MAXIMUM_MTU; currentPeer -> mtu = mtu; if (host -> outgoingBandwidth == 0 && currentPeer -> incomingBandwidth == 0) currentPeer -> windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; else if (host -> outgoingBandwidth == 0 || currentPeer -> incomingBandwidth == 0) currentPeer -> windowSize = (ENET_MAX (host -> outgoingBandwidth, currentPeer -> incomingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; else currentPeer -> windowSize = (ENET_MIN (host -> outgoingBandwidth, currentPeer -> incomingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; if (currentPeer -> windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) currentPeer -> windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; else if (currentPeer -> windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) currentPeer -> windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; if (host -> incomingBandwidth == 0) windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; else windowSize = (host -> incomingBandwidth / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; if (windowSize > ENET_NET_TO_HOST_32 (command -> connect.windowSize)) windowSize = ENET_NET_TO_HOST_32 (command -> connect.windowSize); if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; else if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; verifyCommand.header.command = ENET_PROTOCOL_COMMAND_VERIFY_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE; verifyCommand.header.channelID = 0xFF; verifyCommand.verifyConnect.outgoingPeerID = ENET_HOST_TO_NET_16 (currentPeer -> incomingPeerID); verifyCommand.verifyConnect.incomingSessionID = incomingSessionID; verifyCommand.verifyConnect.outgoingSessionID = outgoingSessionID; verifyCommand.verifyConnect.mtu = ENET_HOST_TO_NET_32 (currentPeer -> mtu); verifyCommand.verifyConnect.windowSize = ENET_HOST_TO_NET_32 (windowSize); verifyCommand.verifyConnect.channelCount = ENET_HOST_TO_NET_32 (channelCount); verifyCommand.verifyConnect.incomingBandwidth = ENET_HOST_TO_NET_32 (host -> incomingBandwidth); verifyCommand.verifyConnect.outgoingBandwidth = ENET_HOST_TO_NET_32 (host -> outgoingBandwidth); verifyCommand.verifyConnect.packetThrottleInterval = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleInterval); verifyCommand.verifyConnect.packetThrottleAcceleration = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleAcceleration); verifyCommand.verifyConnect.packetThrottleDeceleration = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleDeceleration); verifyCommand.verifyConnect.connectID = currentPeer -> connectID; enet_peer_queue_outgoing_command (currentPeer, & verifyCommand, NULL, 0, 0); return currentPeer; } static int enet_protocol_handle_send_reliable (ENetHost * host, ENetPeer * peer, const ENetProtocol * command, enet_uint8 ** currentData) { ENetPacket * packet; size_t dataLength; if (command -> header.channelID >= peer -> channelCount || (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER)) return -1; dataLength = ENET_NET_TO_HOST_16 (command -> sendReliable.dataLength); * currentData += dataLength; if (dataLength > ENET_PROTOCOL_MAXIMUM_PACKET_SIZE || * currentData < host -> receivedData || * currentData > & host -> receivedData [host -> receivedDataLength]) return -1; packet = enet_packet_create ((const enet_uint8 *) command + sizeof (ENetProtocolSendReliable), dataLength, ENET_PACKET_FLAG_RELIABLE); if (packet == NULL || enet_peer_queue_incoming_command (peer, command, packet, 0) == NULL) return -1; return 0; } static int enet_protocol_handle_send_unsequenced (ENetHost * host, ENetPeer * peer, const ENetProtocol * command, enet_uint8 ** currentData) { ENetPacket * packet; enet_uint32 unsequencedGroup, index; size_t dataLength; if (command -> header.channelID >= peer -> channelCount || (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER)) return -1; dataLength = ENET_NET_TO_HOST_16 (command -> sendUnsequenced.dataLength); * currentData += dataLength; if (dataLength > ENET_PROTOCOL_MAXIMUM_PACKET_SIZE || * currentData < host -> receivedData || * currentData > & host -> receivedData [host -> receivedDataLength]) return -1; unsequencedGroup = ENET_NET_TO_HOST_16 (command -> sendUnsequenced.unsequencedGroup); index = unsequencedGroup % ENET_PEER_UNSEQUENCED_WINDOW_SIZE; if (unsequencedGroup < peer -> incomingUnsequencedGroup) unsequencedGroup += 0x10000; if (unsequencedGroup >= (enet_uint32) peer -> incomingUnsequencedGroup + ENET_PEER_FREE_UNSEQUENCED_WINDOWS * ENET_PEER_UNSEQUENCED_WINDOW_SIZE) return 0; unsequencedGroup &= 0xFFFF; if (unsequencedGroup - index != peer -> incomingUnsequencedGroup) { peer -> incomingUnsequencedGroup = unsequencedGroup - index; memset (peer -> unsequencedWindow, 0, sizeof (peer -> unsequencedWindow)); } else if (peer -> unsequencedWindow [index / 32] & (1 << (index % 32))) return 0; packet = enet_packet_create ((const enet_uint8 *) command + sizeof (ENetProtocolSendUnsequenced), dataLength, ENET_PACKET_FLAG_UNSEQUENCED); if (packet == NULL || enet_peer_queue_incoming_command (peer, command, packet, 0) == NULL) return -1; peer -> unsequencedWindow [index / 32] |= 1 << (index % 32); return 0; } static int enet_protocol_handle_send_unreliable (ENetHost * host, ENetPeer * peer, const ENetProtocol * command, enet_uint8 ** currentData) { ENetPacket * packet; size_t dataLength; if (command -> header.channelID >= peer -> channelCount || (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER)) return -1; dataLength = ENET_NET_TO_HOST_16 (command -> sendUnreliable.dataLength); * currentData += dataLength; if (dataLength > ENET_PROTOCOL_MAXIMUM_PACKET_SIZE || * currentData < host -> receivedData || * currentData > & host -> receivedData [host -> receivedDataLength]) return -1; packet = enet_packet_create ((const enet_uint8 *) command + sizeof (ENetProtocolSendUnreliable), dataLength, 0); if (packet == NULL || enet_peer_queue_incoming_command (peer, command, packet, 0) == NULL) return -1; return 0; } static int enet_protocol_handle_send_fragment (ENetHost * host, ENetPeer * peer, const ENetProtocol * command, enet_uint8 ** currentData) { enet_uint32 fragmentNumber, fragmentCount, fragmentOffset, fragmentLength, startSequenceNumber, totalLength; ENetChannel * channel; enet_uint16 startWindow, currentWindow; ENetListIterator currentCommand; ENetIncomingCommand * startCommand = NULL; if (command -> header.channelID >= peer -> channelCount || (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER)) return -1; fragmentLength = ENET_NET_TO_HOST_16 (command -> sendFragment.dataLength); * currentData += fragmentLength; if (fragmentLength > ENET_PROTOCOL_MAXIMUM_PACKET_SIZE || * currentData < host -> receivedData || * currentData > & host -> receivedData [host -> receivedDataLength]) return -1; channel = & peer -> channels [command -> header.channelID]; startSequenceNumber = ENET_NET_TO_HOST_16 (command -> sendFragment.startSequenceNumber); startWindow = startSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE; currentWindow = channel -> incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE; if (startSequenceNumber < channel -> incomingReliableSequenceNumber) startWindow += ENET_PEER_RELIABLE_WINDOWS; if (startWindow < currentWindow || startWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1) return 0; fragmentNumber = ENET_NET_TO_HOST_32 (command -> sendFragment.fragmentNumber); fragmentCount = ENET_NET_TO_HOST_32 (command -> sendFragment.fragmentCount); fragmentOffset = ENET_NET_TO_HOST_32 (command -> sendFragment.fragmentOffset); totalLength = ENET_NET_TO_HOST_32 (command -> sendFragment.totalLength); if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT || fragmentNumber >= fragmentCount || totalLength > ENET_PROTOCOL_MAXIMUM_PACKET_SIZE || fragmentOffset >= totalLength || fragmentLength > totalLength - fragmentOffset) return -1; for (currentCommand = enet_list_previous (enet_list_end (& channel -> incomingReliableCommands)); currentCommand != enet_list_end (& channel -> incomingReliableCommands); currentCommand = enet_list_previous (currentCommand)) { ENetIncomingCommand * incomingCommand = (ENetIncomingCommand *) currentCommand; if (startSequenceNumber >= channel -> incomingReliableSequenceNumber) { if (incomingCommand -> reliableSequenceNumber < channel -> incomingReliableSequenceNumber) continue; } else if (incomingCommand -> reliableSequenceNumber >= channel -> incomingReliableSequenceNumber) break; if (incomingCommand -> reliableSequenceNumber <= startSequenceNumber) { if (incomingCommand -> reliableSequenceNumber < startSequenceNumber) break; if ((incomingCommand -> command.header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_FRAGMENT || totalLength != incomingCommand -> packet -> dataLength || fragmentCount != incomingCommand -> fragmentCount) return -1; startCommand = incomingCommand; break; } } if (startCommand == NULL) { ENetProtocol hostCommand = * command; ENetPacket * packet = enet_packet_create (NULL, totalLength, ENET_PACKET_FLAG_RELIABLE); if (packet == NULL) return -1; hostCommand.header.reliableSequenceNumber = startSequenceNumber; startCommand = enet_peer_queue_incoming_command (peer, & hostCommand, packet, fragmentCount); if (startCommand == NULL) return -1; } if ((startCommand -> fragments [fragmentNumber / 32] & (1 << (fragmentNumber % 32))) == 0) { -- startCommand -> fragmentsRemaining; startCommand -> fragments [fragmentNumber / 32] |= (1 << (fragmentNumber % 32)); if (fragmentOffset + fragmentLength > startCommand -> packet -> dataLength) fragmentLength = startCommand -> packet -> dataLength - fragmentOffset; memcpy (startCommand -> packet -> data + fragmentOffset, (enet_uint8 *) command + sizeof (ENetProtocolSendFragment), fragmentLength); if (startCommand -> fragmentsRemaining <= 0) enet_peer_dispatch_incoming_reliable_commands (peer, channel); } return 0; } static int enet_protocol_handle_send_unreliable_fragment (ENetHost * host, ENetPeer * peer, const ENetProtocol * command, enet_uint8 ** currentData) { enet_uint32 fragmentNumber, fragmentCount, fragmentOffset, fragmentLength, reliableSequenceNumber, startSequenceNumber, totalLength; enet_uint16 reliableWindow, currentWindow; ENetChannel * channel; ENetListIterator currentCommand; ENetIncomingCommand * startCommand = NULL; if (command -> header.channelID >= peer -> channelCount || (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER)) return -1; fragmentLength = ENET_NET_TO_HOST_16 (command -> sendFragment.dataLength); * currentData += fragmentLength; if (fragmentLength > ENET_PROTOCOL_MAXIMUM_PACKET_SIZE || * currentData < host -> receivedData || * currentData > & host -> receivedData [host -> receivedDataLength]) return -1; channel = & peer -> channels [command -> header.channelID]; reliableSequenceNumber = command -> header.reliableSequenceNumber; startSequenceNumber = ENET_NET_TO_HOST_16 (command -> sendFragment.startSequenceNumber); reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE; currentWindow = channel -> incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE; if (reliableSequenceNumber < channel -> incomingReliableSequenceNumber) reliableWindow += ENET_PEER_RELIABLE_WINDOWS; if (reliableWindow < currentWindow || reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1) return 0; if (reliableSequenceNumber == channel -> incomingReliableSequenceNumber && startSequenceNumber <= channel -> incomingUnreliableSequenceNumber) return 0; fragmentNumber = ENET_NET_TO_HOST_32 (command -> sendFragment.fragmentNumber); fragmentCount = ENET_NET_TO_HOST_32 (command -> sendFragment.fragmentCount); fragmentOffset = ENET_NET_TO_HOST_32 (command -> sendFragment.fragmentOffset); totalLength = ENET_NET_TO_HOST_32 (command -> sendFragment.totalLength); if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT || fragmentNumber >= fragmentCount || totalLength > ENET_PROTOCOL_MAXIMUM_PACKET_SIZE || fragmentOffset >= totalLength || fragmentLength > totalLength - fragmentOffset) return -1; for (currentCommand = enet_list_previous (enet_list_end (& channel -> incomingUnreliableCommands)); currentCommand != enet_list_end (& channel -> incomingUnreliableCommands); currentCommand = enet_list_previous (currentCommand)) { ENetIncomingCommand * incomingCommand = (ENetIncomingCommand *) currentCommand; if (reliableSequenceNumber >= channel -> incomingReliableSequenceNumber) { if (incomingCommand -> reliableSequenceNumber < channel -> incomingReliableSequenceNumber) continue; } else if (incomingCommand -> reliableSequenceNumber >= channel -> incomingReliableSequenceNumber) break; if (incomingCommand -> reliableSequenceNumber < reliableSequenceNumber) break; if (incomingCommand -> reliableSequenceNumber > reliableSequenceNumber) continue; if (incomingCommand -> unreliableSequenceNumber <= startSequenceNumber) { if (incomingCommand -> unreliableSequenceNumber < startSequenceNumber) break; if ((incomingCommand -> command.header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT || totalLength != incomingCommand -> packet -> dataLength || fragmentCount != incomingCommand -> fragmentCount) return -1; startCommand = incomingCommand; break; } } if (startCommand == NULL) { ENetPacket * packet = enet_packet_create (NULL, totalLength, ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT); if (packet == NULL) return -1; startCommand = enet_peer_queue_incoming_command (peer, command, packet, fragmentCount); if (startCommand == NULL) return -1; } if ((startCommand -> fragments [fragmentNumber / 32] & (1 << (fragmentNumber % 32))) == 0) { -- startCommand -> fragmentsRemaining; startCommand -> fragments [fragmentNumber / 32] |= (1 << (fragmentNumber % 32)); if (fragmentOffset + fragmentLength > startCommand -> packet -> dataLength) fragmentLength = startCommand -> packet -> dataLength - fragmentOffset; memcpy (startCommand -> packet -> data + fragmentOffset, (enet_uint8 *) command + sizeof (ENetProtocolSendFragment), fragmentLength); if (startCommand -> fragmentsRemaining <= 0) enet_peer_dispatch_incoming_unreliable_commands (peer, channel); } return 0; } static int enet_protocol_handle_ping (ENetHost * host, ENetPeer * peer, const ENetProtocol * command) { return 0; } static int enet_protocol_handle_bandwidth_limit (ENetHost * host, ENetPeer * peer, const ENetProtocol * command) { peer -> incomingBandwidth = ENET_NET_TO_HOST_32 (command -> bandwidthLimit.incomingBandwidth); peer -> outgoingBandwidth = ENET_NET_TO_HOST_32 (command -> bandwidthLimit.outgoingBandwidth); if (peer -> incomingBandwidth == 0 && host -> outgoingBandwidth == 0) peer -> windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; else peer -> windowSize = (ENET_MIN (peer -> incomingBandwidth, host -> outgoingBandwidth) / ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; if (peer -> windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) peer -> windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; else if (peer -> windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) peer -> windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; return 0; } static int enet_protocol_handle_throttle_configure (ENetHost * host, ENetPeer * peer, const ENetProtocol * command) { peer -> packetThrottleInterval = ENET_NET_TO_HOST_32 (command -> throttleConfigure.packetThrottleInterval); peer -> packetThrottleAcceleration = ENET_NET_TO_HOST_32 (command -> throttleConfigure.packetThrottleAcceleration); peer -> packetThrottleDeceleration = ENET_NET_TO_HOST_32 (command -> throttleConfigure.packetThrottleDeceleration); return 0; } static int enet_protocol_handle_disconnect (ENetHost * host, ENetPeer * peer, const ENetProtocol * command) { if (peer -> state == ENET_PEER_STATE_ZOMBIE || peer -> state == ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT) return 0; enet_peer_reset_queues (peer); if (peer -> state == ENET_PEER_STATE_CONNECTION_SUCCEEDED || peer -> state == ENET_PEER_STATE_DISCONNECTING) enet_protocol_dispatch_state (host, peer, ENET_PEER_STATE_ZOMBIE); else if (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) { if (peer -> state == ENET_PEER_STATE_CONNECTION_PENDING) host -> recalculateBandwidthLimits = 1; enet_peer_reset (peer); } else if (command -> header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) peer -> state = ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT; else enet_protocol_dispatch_state (host, peer, ENET_PEER_STATE_ZOMBIE); if (peer -> state != ENET_PEER_STATE_DISCONNECTED) peer -> eventData = ENET_NET_TO_HOST_32 (command -> disconnect.data); return 0; } static int enet_protocol_handle_acknowledge (ENetHost * host, ENetEvent * event, ENetPeer * peer, const ENetProtocol * command) { enet_uint32 roundTripTime, receivedSentTime, receivedReliableSequenceNumber; ENetProtocolCommand commandNumber; receivedSentTime = ENET_NET_TO_HOST_16 (command -> acknowledge.receivedSentTime); receivedSentTime |= host -> serviceTime & 0xFFFF0000; if ((receivedSentTime & 0x8000) > (host -> serviceTime & 0x8000)) receivedSentTime -= 0x10000; if (ENET_TIME_LESS (host -> serviceTime, receivedSentTime)) return 0; peer -> lastReceiveTime = host -> serviceTime; peer -> earliestTimeout = 0; roundTripTime = ENET_TIME_DIFFERENCE (host -> serviceTime, receivedSentTime); enet_peer_throttle (peer, roundTripTime); peer -> roundTripTimeVariance -= peer -> roundTripTimeVariance / 4; if (roundTripTime >= peer -> roundTripTime) { peer -> roundTripTime += (roundTripTime - peer -> roundTripTime) / 8; peer -> roundTripTimeVariance += (roundTripTime - peer -> roundTripTime) / 4; } else { peer -> roundTripTime -= (peer -> roundTripTime - roundTripTime) / 8; peer -> roundTripTimeVariance += (peer -> roundTripTime - roundTripTime) / 4; } if (peer -> roundTripTime < peer -> lowestRoundTripTime) peer -> lowestRoundTripTime = peer -> roundTripTime; if (peer -> roundTripTimeVariance > peer -> highestRoundTripTimeVariance) peer -> highestRoundTripTimeVariance = peer -> roundTripTimeVariance; if (peer -> packetThrottleEpoch == 0 || ENET_TIME_DIFFERENCE (host -> serviceTime, peer -> packetThrottleEpoch) >= peer -> packetThrottleInterval) { peer -> lastRoundTripTime = peer -> lowestRoundTripTime; peer -> lastRoundTripTimeVariance = peer -> highestRoundTripTimeVariance; peer -> lowestRoundTripTime = peer -> roundTripTime; peer -> highestRoundTripTimeVariance = peer -> roundTripTimeVariance; peer -> packetThrottleEpoch = host -> serviceTime; } receivedReliableSequenceNumber = ENET_NET_TO_HOST_16 (command -> acknowledge.receivedReliableSequenceNumber); commandNumber = enet_protocol_remove_sent_reliable_command (peer, receivedReliableSequenceNumber, command -> header.channelID); switch (peer -> state) { case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT: if (commandNumber != ENET_PROTOCOL_COMMAND_VERIFY_CONNECT) return -1; enet_protocol_notify_connect (host, peer, event); break; case ENET_PEER_STATE_DISCONNECTING: if (commandNumber != ENET_PROTOCOL_COMMAND_DISCONNECT) return -1; enet_protocol_notify_disconnect (host, peer, event); break; case ENET_PEER_STATE_DISCONNECT_LATER: if (enet_list_empty (& peer -> outgoingReliableCommands) && enet_list_empty (& peer -> outgoingUnreliableCommands) && enet_list_empty (& peer -> sentReliableCommands)) enet_peer_disconnect (peer, peer -> eventData); break; default: break; } return 0; } static int enet_protocol_handle_verify_connect (ENetHost * host, ENetEvent * event, ENetPeer * peer, const ENetProtocol * command) { enet_uint32 mtu, windowSize; size_t channelCount; if (peer -> state != ENET_PEER_STATE_CONNECTING) return 0; channelCount = ENET_NET_TO_HOST_32 (command -> verifyConnect.channelCount); if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT || channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT || ENET_NET_TO_HOST_32 (command -> verifyConnect.packetThrottleInterval) != peer -> packetThrottleInterval || ENET_NET_TO_HOST_32 (command -> verifyConnect.packetThrottleAcceleration) != peer -> packetThrottleAcceleration || ENET_NET_TO_HOST_32 (command -> verifyConnect.packetThrottleDeceleration) != peer -> packetThrottleDeceleration || command -> verifyConnect.connectID != peer -> connectID) { peer -> eventData = 0; enet_protocol_dispatch_state (host, peer, ENET_PEER_STATE_ZOMBIE); return -1; } enet_protocol_remove_sent_reliable_command (peer, 1, 0xFF); if (channelCount < peer -> channelCount) peer -> channelCount = channelCount; peer -> outgoingPeerID = ENET_NET_TO_HOST_16 (command -> verifyConnect.outgoingPeerID); peer -> incomingSessionID = command -> verifyConnect.incomingSessionID; peer -> outgoingSessionID = command -> verifyConnect.outgoingSessionID; mtu = ENET_NET_TO_HOST_32 (command -> verifyConnect.mtu); if (mtu < ENET_PROTOCOL_MINIMUM_MTU) mtu = ENET_PROTOCOL_MINIMUM_MTU; else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU) mtu = ENET_PROTOCOL_MAXIMUM_MTU; if (mtu < peer -> mtu) peer -> mtu = mtu; windowSize = ENET_NET_TO_HOST_32 (command -> verifyConnect.windowSize); if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; if (windowSize < peer -> windowSize) peer -> windowSize = windowSize; peer -> incomingBandwidth = ENET_NET_TO_HOST_32 (command -> verifyConnect.incomingBandwidth); peer -> outgoingBandwidth = ENET_NET_TO_HOST_32 (command -> verifyConnect.outgoingBandwidth); enet_protocol_notify_connect (host, peer, event); return 0; } static int enet_protocol_handle_incoming_commands (ENetHost * host, ENetEvent * event) { ENetProtocolHeader * header; ENetProtocol * command; ENetPeer * peer; enet_uint8 * currentData; size_t headerSize; enet_uint16 peerID, flags; enet_uint8 sessionID; if (host -> receivedDataLength < (size_t) & ((ENetProtocolHeader *) 0) -> sentTime) return 0; header = (ENetProtocolHeader *) host -> receivedData; peerID = ENET_NET_TO_HOST_16 (header -> peerID); sessionID = (peerID & ENET_PROTOCOL_HEADER_SESSION_MASK) >> ENET_PROTOCOL_HEADER_SESSION_SHIFT; flags = peerID & ENET_PROTOCOL_HEADER_FLAG_MASK; peerID &= ~ (ENET_PROTOCOL_HEADER_FLAG_MASK | ENET_PROTOCOL_HEADER_SESSION_MASK); headerSize = (flags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME ? sizeof (ENetProtocolHeader) : (size_t) & ((ENetProtocolHeader *) 0) -> sentTime); if (host -> checksum != NULL) headerSize += sizeof (enet_uint32); if (peerID == ENET_PROTOCOL_MAXIMUM_PEER_ID) peer = NULL; else if (peerID >= host -> peerCount) return 0; else { peer = & host -> peers [peerID]; if (peer -> state == ENET_PEER_STATE_DISCONNECTED || peer -> state == ENET_PEER_STATE_ZOMBIE || ((host -> receivedAddress.host != peer -> address.host || host -> receivedAddress.port != peer -> address.port) && peer -> address.host != ENET_HOST_BROADCAST) || (peer -> outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID && sessionID != peer -> incomingSessionID)) return 0; } if (flags & ENET_PROTOCOL_HEADER_FLAG_COMPRESSED) { size_t originalSize; if (host -> compressor.context == NULL || host -> compressor.decompress == NULL) return 0; originalSize = host -> compressor.decompress (host -> compressor.context, host -> receivedData + headerSize, host -> receivedDataLength - headerSize, host -> packetData [1] + headerSize, sizeof (host -> packetData [1]) - headerSize); if (originalSize <= 0 || originalSize > sizeof (host -> packetData [1]) - headerSize) return 0; memcpy (host -> packetData [1], header, headerSize); host -> receivedData = host -> packetData [1]; host -> receivedDataLength = headerSize + originalSize; } if (host -> checksum != NULL) { enet_uint32 * checksum = (enet_uint32 *) & host -> receivedData [headerSize - sizeof (enet_uint32)], desiredChecksum = * checksum; ENetBuffer buffer; * checksum = peer != NULL ? peer -> connectID : 0; buffer.data = host -> receivedData; buffer.dataLength = host -> receivedDataLength; if (host -> checksum (& buffer, 1) != desiredChecksum) return 0; } if (peer != NULL) { peer -> address.host = host -> receivedAddress.host; peer -> address.port = host -> receivedAddress.port; peer -> incomingDataTotal += host -> receivedDataLength; } currentData = host -> receivedData + headerSize; while (currentData < & host -> receivedData [host -> receivedDataLength]) { enet_uint8 commandNumber; size_t commandSize; command = (ENetProtocol *) currentData; if (currentData + sizeof (ENetProtocolCommandHeader) > & host -> receivedData [host -> receivedDataLength]) break; commandNumber = command -> header.command & ENET_PROTOCOL_COMMAND_MASK; if (commandNumber >= ENET_PROTOCOL_COMMAND_COUNT) break; commandSize = commandSizes [commandNumber]; if (commandSize == 0 || currentData + commandSize > & host -> receivedData [host -> receivedDataLength]) break; currentData += commandSize; if (peer == NULL && commandNumber != ENET_PROTOCOL_COMMAND_CONNECT) break; command -> header.reliableSequenceNumber = ENET_NET_TO_HOST_16 (command -> header.reliableSequenceNumber); switch (command -> header.command & ENET_PROTOCOL_COMMAND_MASK) { case ENET_PROTOCOL_COMMAND_ACKNOWLEDGE: if (enet_protocol_handle_acknowledge (host, event, peer, command)) goto commandError; break; case ENET_PROTOCOL_COMMAND_CONNECT: peer = enet_protocol_handle_connect (host, header, command); if (peer == NULL) goto commandError; break; case ENET_PROTOCOL_COMMAND_VERIFY_CONNECT: if (enet_protocol_handle_verify_connect (host, event, peer, command)) goto commandError; break; case ENET_PROTOCOL_COMMAND_DISCONNECT: if (enet_protocol_handle_disconnect (host, peer, command)) goto commandError; break; case ENET_PROTOCOL_COMMAND_PING: if (enet_protocol_handle_ping (host, peer, command)) goto commandError; break; case ENET_PROTOCOL_COMMAND_SEND_RELIABLE: if (enet_protocol_handle_send_reliable (host, peer, command, & currentData)) goto commandError; break; case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE: if (enet_protocol_handle_send_unreliable (host, peer, command, & currentData)) goto commandError; break; case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED: if (enet_protocol_handle_send_unsequenced (host, peer, command, & currentData)) goto commandError; break; case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT: if (enet_protocol_handle_send_fragment (host, peer, command, & currentData)) goto commandError; break; case ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT: if (enet_protocol_handle_bandwidth_limit (host, peer, command)) goto commandError; break; case ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE: if (enet_protocol_handle_throttle_configure (host, peer, command)) goto commandError; break; case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT: if (enet_protocol_handle_send_unreliable_fragment (host, peer, command, & currentData)) goto commandError; break; default: goto commandError; } if (peer != NULL && (command -> header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) != 0) { enet_uint16 sentTime; if (! (flags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME)) break; sentTime = ENET_NET_TO_HOST_16 (header -> sentTime); switch (peer -> state) { case ENET_PEER_STATE_DISCONNECTING: case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT: break; case ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT: if ((command -> header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_DISCONNECT) enet_peer_queue_acknowledgement (peer, command, sentTime); break; default: enet_peer_queue_acknowledgement (peer, command, sentTime); break; } } } commandError: if (event != NULL && event -> type != ENET_EVENT_TYPE_NONE) return 1; return 0; } static int enet_protocol_receive_incoming_commands (ENetHost * host, ENetEvent * event) { for (;;) { int receivedLength; ENetBuffer buffer; buffer.data = host -> packetData [0]; buffer.dataLength = sizeof (host -> packetData [0]); receivedLength = enet_socket_receive (host -> socket, & host -> receivedAddress, & buffer, 1); if (receivedLength < 0) return -1; if (receivedLength == 0) return 0; host -> receivedData = host -> packetData [0]; host -> receivedDataLength = receivedLength; host -> totalReceivedData += receivedLength; host -> totalReceivedPackets ++; if (host -> intercept != NULL) { switch (host -> intercept (host, event)) { case 1: if (event != NULL && event -> type != ENET_EVENT_TYPE_NONE) return 1; continue; case -1: return -1; default: break; } } switch (enet_protocol_handle_incoming_commands (host, event)) { case 1: return 1; case -1: return -1; default: break; } } return -1; } static void enet_protocol_send_acknowledgements (ENetHost * host, ENetPeer * peer) { ENetProtocol * command = & host -> commands [host -> commandCount]; ENetBuffer * buffer = & host -> buffers [host -> bufferCount]; ENetAcknowledgement * acknowledgement; ENetListIterator currentAcknowledgement; currentAcknowledgement = enet_list_begin (& peer -> acknowledgements); while (currentAcknowledgement != enet_list_end (& peer -> acknowledgements)) { if (command >= & host -> commands [sizeof (host -> commands) / sizeof (ENetProtocol)] || buffer >= & host -> buffers [sizeof (host -> buffers) / sizeof (ENetBuffer)] || peer -> mtu - host -> packetSize < sizeof (ENetProtocolAcknowledge)) { host -> continueSending = 1; break; } acknowledgement = (ENetAcknowledgement *) currentAcknowledgement; currentAcknowledgement = enet_list_next (currentAcknowledgement); buffer -> data = command; buffer -> dataLength = sizeof (ENetProtocolAcknowledge); host -> packetSize += buffer -> dataLength; command -> header.command = ENET_PROTOCOL_COMMAND_ACKNOWLEDGE; command -> header.channelID = acknowledgement -> command.header.channelID; command -> acknowledge.receivedReliableSequenceNumber = ENET_HOST_TO_NET_16 (acknowledgement -> command.header.reliableSequenceNumber); command -> acknowledge.receivedSentTime = ENET_HOST_TO_NET_16 (acknowledgement -> sentTime); if ((acknowledgement -> command.header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_DISCONNECT) enet_protocol_dispatch_state (host, peer, ENET_PEER_STATE_ZOMBIE); enet_list_remove (& acknowledgement -> acknowledgementList); enet_free (acknowledgement); ++ command; ++ buffer; } host -> commandCount = command - host -> commands; host -> bufferCount = buffer - host -> buffers; } static void enet_protocol_send_unreliable_outgoing_commands (ENetHost * host, ENetPeer * peer) { ENetProtocol * command = & host -> commands [host -> commandCount]; ENetBuffer * buffer = & host -> buffers [host -> bufferCount]; ENetOutgoingCommand * outgoingCommand; ENetListIterator currentCommand; currentCommand = enet_list_begin (& peer -> outgoingUnreliableCommands); while (currentCommand != enet_list_end (& peer -> outgoingUnreliableCommands)) { size_t commandSize; outgoingCommand = (ENetOutgoingCommand *) currentCommand; commandSize = commandSizes [outgoingCommand -> command.header.command & ENET_PROTOCOL_COMMAND_MASK]; if (command >= & host -> commands [sizeof (host -> commands) / sizeof (ENetProtocol)] || buffer + 1 >= & host -> buffers [sizeof (host -> buffers) / sizeof (ENetBuffer)] || peer -> mtu - host -> packetSize < commandSize || (outgoingCommand -> packet != NULL && peer -> mtu - host -> packetSize < commandSize + outgoingCommand -> fragmentLength)) { host -> continueSending = 1; break; } currentCommand = enet_list_next (currentCommand); if (outgoingCommand -> packet != NULL && outgoingCommand -> fragmentOffset == 0) { peer -> packetThrottleCounter += ENET_PEER_PACKET_THROTTLE_COUNTER; peer -> packetThrottleCounter %= ENET_PEER_PACKET_THROTTLE_SCALE; if (peer -> packetThrottleCounter > peer -> packetThrottle) { enet_uint16 reliableSequenceNumber = outgoingCommand -> reliableSequenceNumber, unreliableSequenceNumber = outgoingCommand -> unreliableSequenceNumber; for (;;) { -- outgoingCommand -> packet -> referenceCount; if (outgoingCommand -> packet -> referenceCount == 0) enet_packet_destroy (outgoingCommand -> packet); enet_list_remove (& outgoingCommand -> outgoingCommandList); enet_free (outgoingCommand); if (currentCommand == enet_list_end (& peer -> outgoingUnreliableCommands)) break; outgoingCommand = (ENetOutgoingCommand *) currentCommand; if (outgoingCommand -> reliableSequenceNumber != reliableSequenceNumber || outgoingCommand -> unreliableSequenceNumber != unreliableSequenceNumber) break; currentCommand = enet_list_next (currentCommand); } continue; } } buffer -> data = command; buffer -> dataLength = commandSize; host -> packetSize += buffer -> dataLength; * command = outgoingCommand -> command; enet_list_remove (& outgoingCommand -> outgoingCommandList); if (outgoingCommand -> packet != NULL) { ++ buffer; buffer -> data = outgoingCommand -> packet -> data + outgoingCommand -> fragmentOffset; buffer -> dataLength = outgoingCommand -> fragmentLength; host -> packetSize += buffer -> dataLength; enet_list_insert (enet_list_end (& peer -> sentUnreliableCommands), outgoingCommand); } else enet_free (outgoingCommand); ++ command; ++ buffer; } host -> commandCount = command - host -> commands; host -> bufferCount = buffer - host -> buffers; if (peer -> state == ENET_PEER_STATE_DISCONNECT_LATER && enet_list_empty (& peer -> outgoingReliableCommands) && enet_list_empty (& peer -> outgoingUnreliableCommands) && enet_list_empty (& peer -> sentReliableCommands)) enet_peer_disconnect (peer, peer -> eventData); } static int enet_protocol_check_timeouts (ENetHost * host, ENetPeer * peer, ENetEvent * event) { ENetOutgoingCommand * outgoingCommand; ENetListIterator currentCommand, insertPosition; currentCommand = enet_list_begin (& peer -> sentReliableCommands); insertPosition = enet_list_begin (& peer -> outgoingReliableCommands); while (currentCommand != enet_list_end (& peer -> sentReliableCommands)) { outgoingCommand = (ENetOutgoingCommand *) currentCommand; currentCommand = enet_list_next (currentCommand); if (ENET_TIME_DIFFERENCE (host -> serviceTime, outgoingCommand -> sentTime) < outgoingCommand -> roundTripTimeout) continue; if (peer -> earliestTimeout == 0 || ENET_TIME_LESS (outgoingCommand -> sentTime, peer -> earliestTimeout)) peer -> earliestTimeout = outgoingCommand -> sentTime; if (peer -> earliestTimeout != 0 && (ENET_TIME_DIFFERENCE (host -> serviceTime, peer -> earliestTimeout) >= peer -> timeoutMaximum || (outgoingCommand -> roundTripTimeout >= outgoingCommand -> roundTripTimeoutLimit && ENET_TIME_DIFFERENCE (host -> serviceTime, peer -> earliestTimeout) >= peer -> timeoutMinimum))) { enet_protocol_notify_disconnect (host, peer, event); return 1; } if (outgoingCommand -> packet != NULL) peer -> reliableDataInTransit -= outgoingCommand -> fragmentLength; ++ peer -> packetsLost; outgoingCommand -> roundTripTimeout *= 2; enet_list_insert (insertPosition, enet_list_remove (& outgoingCommand -> outgoingCommandList)); if (currentCommand == enet_list_begin (& peer -> sentReliableCommands) && ! enet_list_empty (& peer -> sentReliableCommands)) { outgoingCommand = (ENetOutgoingCommand *) currentCommand; peer -> nextTimeout = outgoingCommand -> sentTime + outgoingCommand -> roundTripTimeout; } } return 0; } static int enet_protocol_send_reliable_outgoing_commands (ENetHost * host, ENetPeer * peer) { ENetProtocol * command = & host -> commands [host -> commandCount]; ENetBuffer * buffer = & host -> buffers [host -> bufferCount]; ENetOutgoingCommand * outgoingCommand; ENetListIterator currentCommand; ENetChannel *channel; enet_uint16 reliableWindow; size_t commandSize; int windowExceeded = 0, windowWrap = 0, canPing = 1; currentCommand = enet_list_begin (& peer -> outgoingReliableCommands); while (currentCommand != enet_list_end (& peer -> outgoingReliableCommands)) { outgoingCommand = (ENetOutgoingCommand *) currentCommand; channel = outgoingCommand -> command.header.channelID < peer -> channelCount ? & peer -> channels [outgoingCommand -> command.header.channelID] : NULL; reliableWindow = outgoingCommand -> reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE; if (channel != NULL) { if (! windowWrap && outgoingCommand -> sendAttempts < 1 && ! (outgoingCommand -> reliableSequenceNumber % ENET_PEER_RELIABLE_WINDOW_SIZE) && (channel -> reliableWindows [(reliableWindow + ENET_PEER_RELIABLE_WINDOWS - 1) % ENET_PEER_RELIABLE_WINDOWS] >= ENET_PEER_RELIABLE_WINDOW_SIZE || channel -> usedReliableWindows & ((((1 << ENET_PEER_FREE_RELIABLE_WINDOWS) - 1) << reliableWindow) | (((1 << ENET_PEER_FREE_RELIABLE_WINDOWS) - 1) >> (ENET_PEER_RELIABLE_WINDOW_SIZE - reliableWindow))))) windowWrap = 1; if (windowWrap) { currentCommand = enet_list_next (currentCommand); continue; } } if (outgoingCommand -> packet != NULL) { if (! windowExceeded) { enet_uint32 windowSize = (peer -> packetThrottle * peer -> windowSize) / ENET_PEER_PACKET_THROTTLE_SCALE; if (peer -> reliableDataInTransit + outgoingCommand -> fragmentLength > ENET_MAX (windowSize, peer -> mtu)) windowExceeded = 1; } if (windowExceeded) { currentCommand = enet_list_next (currentCommand); continue; } } canPing = 0; commandSize = commandSizes [outgoingCommand -> command.header.command & ENET_PROTOCOL_COMMAND_MASK]; if (command >= & host -> commands [sizeof (host -> commands) / sizeof (ENetProtocol)] || buffer + 1 >= & host -> buffers [sizeof (host -> buffers) / sizeof (ENetBuffer)] || peer -> mtu - host -> packetSize < commandSize || (outgoingCommand -> packet != NULL && (enet_uint16) (peer -> mtu - host -> packetSize) < (enet_uint16) (commandSize + outgoingCommand -> fragmentLength))) { host -> continueSending = 1; break; } currentCommand = enet_list_next (currentCommand); if (channel != NULL && outgoingCommand -> sendAttempts < 1) { channel -> usedReliableWindows |= 1 << reliableWindow; ++ channel -> reliableWindows [reliableWindow]; } ++ outgoingCommand -> sendAttempts; if (outgoingCommand -> roundTripTimeout == 0) { outgoingCommand -> roundTripTimeout = peer -> roundTripTime + 4 * peer -> roundTripTimeVariance; outgoingCommand -> roundTripTimeoutLimit = peer -> timeoutLimit * outgoingCommand -> roundTripTimeout; } if (enet_list_empty (& peer -> sentReliableCommands)) peer -> nextTimeout = host -> serviceTime + outgoingCommand -> roundTripTimeout; enet_list_insert (enet_list_end (& peer -> sentReliableCommands), enet_list_remove (& outgoingCommand -> outgoingCommandList)); outgoingCommand -> sentTime = host -> serviceTime; buffer -> data = command; buffer -> dataLength = commandSize; host -> packetSize += buffer -> dataLength; host -> headerFlags |= ENET_PROTOCOL_HEADER_FLAG_SENT_TIME; * command = outgoingCommand -> command; if (outgoingCommand -> packet != NULL) { ++ buffer; buffer -> data = outgoingCommand -> packet -> data + outgoingCommand -> fragmentOffset; buffer -> dataLength = outgoingCommand -> fragmentLength; host -> packetSize += outgoingCommand -> fragmentLength; peer -> reliableDataInTransit += outgoingCommand -> fragmentLength; } ++ peer -> packetsSent; ++ command; ++ buffer; } host -> commandCount = command - host -> commands; host -> bufferCount = buffer - host -> buffers; return canPing; } static int enet_protocol_send_outgoing_commands (ENetHost * host, ENetEvent * event, int checkForTimeouts) { enet_uint8 headerData [sizeof (ENetProtocolHeader) + sizeof (enet_uint32)]; ENetProtocolHeader * header = (ENetProtocolHeader *) headerData; ENetPeer * currentPeer; int sentLength; size_t shouldCompress = 0; host -> continueSending = 1; while (host -> continueSending) for (host -> continueSending = 0, currentPeer = host -> peers; currentPeer < & host -> peers [host -> peerCount]; ++ currentPeer) { if (currentPeer -> state == ENET_PEER_STATE_DISCONNECTED || currentPeer -> state == ENET_PEER_STATE_ZOMBIE) continue; host -> headerFlags = 0; host -> commandCount = 0; host -> bufferCount = 1; host -> packetSize = sizeof (ENetProtocolHeader); if (! enet_list_empty (& currentPeer -> acknowledgements)) enet_protocol_send_acknowledgements (host, currentPeer); if (checkForTimeouts != 0 && ! enet_list_empty (& currentPeer -> sentReliableCommands) && ENET_TIME_GREATER_EQUAL (host -> serviceTime, currentPeer -> nextTimeout) && enet_protocol_check_timeouts (host, currentPeer, event) == 1) { if (event != NULL && event -> type != ENET_EVENT_TYPE_NONE) return 1; else continue; } if ((enet_list_empty (& currentPeer -> outgoingReliableCommands) || enet_protocol_send_reliable_outgoing_commands (host, currentPeer)) && enet_list_empty (& currentPeer -> sentReliableCommands) && ENET_TIME_DIFFERENCE (host -> serviceTime, currentPeer -> lastReceiveTime) >= currentPeer -> pingInterval && currentPeer -> mtu - host -> packetSize >= sizeof (ENetProtocolPing)) { enet_peer_ping (currentPeer); enet_protocol_send_reliable_outgoing_commands (host, currentPeer); } if (! enet_list_empty (& currentPeer -> outgoingUnreliableCommands)) enet_protocol_send_unreliable_outgoing_commands (host, currentPeer); if (host -> commandCount == 0) continue; if (currentPeer -> packetLossEpoch == 0) currentPeer -> packetLossEpoch = host -> serviceTime; else if (ENET_TIME_DIFFERENCE (host -> serviceTime, currentPeer -> packetLossEpoch) >= ENET_PEER_PACKET_LOSS_INTERVAL && currentPeer -> packetsSent > 0) { enet_uint32 packetLoss = currentPeer -> packetsLost * ENET_PEER_PACKET_LOSS_SCALE / currentPeer -> packetsSent; #ifdef ENET_DEBUG #ifdef WIN32 printf ( #else fprintf (stderr, #endif "peer %u: %f%%+-%f%% packet loss, %u+-%u ms round trip time, %f%% throttle, %u/%u outgoing, %u/%u incoming\n", currentPeer -> incomingPeerID, currentPeer -> packetLoss / (float) ENET_PEER_PACKET_LOSS_SCALE, currentPeer -> packetLossVariance / (float) ENET_PEER_PACKET_LOSS_SCALE, currentPeer -> roundTripTime, currentPeer -> roundTripTimeVariance, currentPeer -> packetThrottle / (float) ENET_PEER_PACKET_THROTTLE_SCALE, enet_list_size (& currentPeer -> outgoingReliableCommands), enet_list_size (& currentPeer -> outgoingUnreliableCommands), currentPeer -> channels != NULL ? enet_list_size (& currentPeer -> channels -> incomingReliableCommands) : 0, currentPeer -> channels != NULL ? enet_list_size (& currentPeer -> channels -> incomingUnreliableCommands) : 0); #endif currentPeer -> packetLossVariance -= currentPeer -> packetLossVariance / 4; if (packetLoss >= currentPeer -> packetLoss) { currentPeer -> packetLoss += (packetLoss - currentPeer -> packetLoss) / 8; currentPeer -> packetLossVariance += (packetLoss - currentPeer -> packetLoss) / 4; } else { currentPeer -> packetLoss -= (currentPeer -> packetLoss - packetLoss) / 8; currentPeer -> packetLossVariance += (currentPeer -> packetLoss - packetLoss) / 4; } currentPeer -> packetLossEpoch = host -> serviceTime; currentPeer -> packetsSent = 0; currentPeer -> packetsLost = 0; } host -> buffers -> data = headerData; if (host -> headerFlags & ENET_PROTOCOL_HEADER_FLAG_SENT_TIME) { header -> sentTime = ENET_HOST_TO_NET_16 (host -> serviceTime & 0xFFFF); host -> buffers -> dataLength = sizeof (ENetProtocolHeader); } else host -> buffers -> dataLength = (size_t) & ((ENetProtocolHeader *) 0) -> sentTime; shouldCompress = 0; if (host -> compressor.context != NULL && host -> compressor.compress != NULL) { size_t originalSize = host -> packetSize - sizeof(ENetProtocolHeader), compressedSize = host -> compressor.compress (host -> compressor.context, & host -> buffers [1], host -> bufferCount - 1, originalSize, host -> packetData [1], originalSize); if (compressedSize > 0 && compressedSize < originalSize) { host -> headerFlags |= ENET_PROTOCOL_HEADER_FLAG_COMPRESSED; shouldCompress = compressedSize; #ifdef ENET_DEBUG_COMPRESS #ifdef WIN32 printf ( #else fprintf (stderr, #endif "peer %u: compressed %u -> %u (%u%%)\n", currentPeer -> incomingPeerID, originalSize, compressedSize, (compressedSize * 100) / originalSize); #endif } } if (currentPeer -> outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID) host -> headerFlags |= currentPeer -> outgoingSessionID << ENET_PROTOCOL_HEADER_SESSION_SHIFT; header -> peerID = ENET_HOST_TO_NET_16 (currentPeer -> outgoingPeerID | host -> headerFlags); if (host -> checksum != NULL) { enet_uint32 * checksum = (enet_uint32 *) & headerData [host -> buffers -> dataLength]; * checksum = currentPeer -> outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID ? currentPeer -> connectID : 0; host -> buffers -> dataLength += sizeof (enet_uint32); * checksum = host -> checksum (host -> buffers, host -> bufferCount); } if (shouldCompress > 0) { host -> buffers [1].data = host -> packetData [1]; host -> buffers [1].dataLength = shouldCompress; host -> bufferCount = 2; } currentPeer -> lastSendTime = host -> serviceTime; sentLength = enet_socket_send (host -> socket, & currentPeer -> address, host -> buffers, host -> bufferCount); enet_protocol_remove_sent_unreliable_commands (currentPeer); if (sentLength < 0) return -1; host -> totalSentData += sentLength; host -> totalSentPackets ++; } return 0; } /** Sends any queued packets on the host specified to its designated peers. @param host host to flush @remarks this function need only be used in circumstances where one wishes to send queued packets earlier than in a call to enet_host_service(). @ingroup host */ void enet_host_flush (ENetHost * host) { host -> serviceTime = enet_time_get (); enet_protocol_send_outgoing_commands (host, NULL, 0); } /** Checks for any queued events on the host and dispatches one if available. @param host host to check for events @param event an event structure where event details will be placed if available @retval > 0 if an event was dispatched @retval 0 if no events are available @retval < 0 on failure @ingroup host */ int enet_host_check_events (ENetHost * host, ENetEvent * event) { if (event == NULL) return -1; event -> type = ENET_EVENT_TYPE_NONE; event -> peer = NULL; event -> packet = NULL; return enet_protocol_dispatch_incoming_commands (host, event); } /** Waits for events on the host specified and shuttles packets between the host and its peers. @param host host to service @param event an event structure where event details will be placed if one occurs if event == NULL then no events will be delivered @param timeout number of milliseconds that ENet should wait for events @retval > 0 if an event occurred within the specified time limit @retval 0 if no event occurred @retval < 0 on failure @remarks enet_host_service should be called fairly regularly for adequate performance @ingroup host */ int enet_host_service (ENetHost * host, ENetEvent * event, enet_uint32 timeout) { enet_uint32 waitCondition; if (event != NULL) { event -> type = ENET_EVENT_TYPE_NONE; event -> peer = NULL; event -> packet = NULL; switch (enet_protocol_dispatch_incoming_commands (host, event)) { case 1: return 1; case -1: perror ("Error dispatching incoming packets"); return -1; default: break; } } host -> serviceTime = enet_time_get (); timeout += host -> serviceTime; do { if (ENET_TIME_DIFFERENCE (host -> serviceTime, host -> bandwidthThrottleEpoch) >= ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL) enet_host_bandwidth_throttle (host); switch (enet_protocol_send_outgoing_commands (host, event, 1)) { case 1: return 1; case -1: perror ("Error sending outgoing packets"); return -1; default: break; } switch (enet_protocol_receive_incoming_commands (host, event)) { case 1: return 1; case -1: perror ("Error receiving incoming packets"); return -1; default: break; } switch (enet_protocol_send_outgoing_commands (host, event, 1)) { case 1: return 1; case -1: perror ("Error sending outgoing packets"); return -1; default: break; } if (event != NULL) { switch (enet_protocol_dispatch_incoming_commands (host, event)) { case 1: return 1; case -1: perror ("Error dispatching incoming packets"); return -1; default: break; } } host -> serviceTime = enet_time_get (); if (ENET_TIME_GREATER_EQUAL (host -> serviceTime, timeout)) return 0; waitCondition = ENET_SOCKET_WAIT_RECEIVE; if (enet_socket_wait (host -> socket, & waitCondition, ENET_TIME_DIFFERENCE (timeout, host -> serviceTime)) != 0) return -1; host -> serviceTime = enet_time_get (); } while (waitCondition == ENET_SOCKET_WAIT_RECEIVE); return 0; } sauerbraten-0.0.20130203.dfsg/enet/missing0000755000175000017500000002415211761204106017731 0ustar vincentvincent#! /bin/sh # Common stub for a few missing GNU programs while installing. scriptversion=2012-01-06.13; # UTC # Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2005, 2006, # 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc. # Originally by Fran,cois Pinard , 1996. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program 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 General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. if test $# -eq 0; then echo 1>&2 "Try \`$0 --help' for more information" exit 1 fi run=: sed_output='s/.* --output[ =]\([^ ]*\).*/\1/p' sed_minuso='s/.* -o \([^ ]*\).*/\1/p' # In the cases where this matters, `missing' is being run in the # srcdir already. if test -f configure.ac; then configure_ac=configure.ac else configure_ac=configure.in fi msg="missing on your system" case $1 in --run) # Try to run requested program, and just exit if it succeeds. run= shift "$@" && exit 0 # Exit code 63 means version mismatch. This often happens # when the user try to use an ancient version of a tool on # a file that requires a minimum version. In this case we # we should proceed has if the program had been absent, or # if --run hadn't been passed. if test $? = 63; then run=: msg="probably too old" fi ;; -h|--h|--he|--hel|--help) echo "\ $0 [OPTION]... PROGRAM [ARGUMENT]... Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an error status if there is no known handling for PROGRAM. Options: -h, --help display this help and exit -v, --version output version information and exit --run try to run the given command, and emulate it if it fails Supported PROGRAM values: aclocal touch file \`aclocal.m4' autoconf touch file \`configure' autoheader touch file \`config.h.in' autom4te touch the output file, or create a stub one automake touch all \`Makefile.in' files bison create \`y.tab.[ch]', if possible, from existing .[ch] flex create \`lex.yy.c', if possible, from existing .c help2man touch the output file lex create \`lex.yy.c', if possible, from existing .c makeinfo touch the output file yacc create \`y.tab.[ch]', if possible, from existing .[ch] Version suffixes to PROGRAM as well as the prefixes \`gnu-', \`gnu', and \`g' are ignored when checking the name. Send bug reports to ." exit $? ;; -v|--v|--ve|--ver|--vers|--versi|--versio|--version) echo "missing $scriptversion (GNU Automake)" exit $? ;; -*) echo 1>&2 "$0: Unknown \`$1' option" echo 1>&2 "Try \`$0 --help' for more information" exit 1 ;; esac # normalize program name to check for. program=`echo "$1" | sed ' s/^gnu-//; t s/^gnu//; t s/^g//; t'` # Now exit if we have it, but it failed. Also exit now if we # don't have it and --version was passed (most likely to detect # the program). This is about non-GNU programs, so use $1 not # $program. case $1 in lex*|yacc*) # Not GNU programs, they don't have --version. ;; *) if test -z "$run" && ($1 --version) > /dev/null 2>&1; then # We have it, but it failed. exit 1 elif test "x$2" = "x--version" || test "x$2" = "x--help"; then # Could not run --version or --help. This is probably someone # running `$TOOL --version' or `$TOOL --help' to check whether # $TOOL exists and not knowing $TOOL uses missing. exit 1 fi ;; esac # If it does not exist, or fails to run (possibly an outdated version), # try to emulate it. case $program in aclocal*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified \`acinclude.m4' or \`${configure_ac}'. You might want to install the \`Automake' and \`Perl' packages. Grab them from any GNU archive site." touch aclocal.m4 ;; autoconf*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified \`${configure_ac}'. You might want to install the \`Autoconf' and \`GNU m4' packages. Grab them from any GNU archive site." touch configure ;; autoheader*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified \`acconfig.h' or \`${configure_ac}'. You might want to install the \`Autoconf' and \`GNU m4' packages. Grab them from any GNU archive site." files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}` test -z "$files" && files="config.h" touch_files= for f in $files; do case $f in *:*) touch_files="$touch_files "`echo "$f" | sed -e 's/^[^:]*://' -e 's/:.*//'`;; *) touch_files="$touch_files $f.in";; esac done touch $touch_files ;; automake*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'. You might want to install the \`Automake' and \`Perl' packages. Grab them from any GNU archive site." find . -type f -name Makefile.am -print | sed 's/\.am$/.in/' | while read f; do touch "$f"; done ;; autom4te*) echo 1>&2 "\ WARNING: \`$1' is needed, but is $msg. You might have modified some files without having the proper tools for further handling them. You can get \`$1' as part of \`Autoconf' from any GNU archive site." file=`echo "$*" | sed -n "$sed_output"` test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` if test -f "$file"; then touch $file else test -z "$file" || exec >$file echo "#! /bin/sh" echo "# Created by GNU Automake missing as a replacement of" echo "# $ $@" echo "exit 0" chmod +x $file exit 1 fi ;; bison*|yacc*) echo 1>&2 "\ WARNING: \`$1' $msg. You should only need it if you modified a \`.y' file. You may need the \`Bison' package in order for those modifications to take effect. You can get \`Bison' from any GNU archive site." rm -f y.tab.c y.tab.h if test $# -ne 1; then eval LASTARG=\${$#} case $LASTARG in *.y) SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'` if test -f "$SRCFILE"; then cp "$SRCFILE" y.tab.c fi SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'` if test -f "$SRCFILE"; then cp "$SRCFILE" y.tab.h fi ;; esac fi if test ! -f y.tab.h; then echo >y.tab.h fi if test ! -f y.tab.c; then echo 'main() { return 0; }' >y.tab.c fi ;; lex*|flex*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified a \`.l' file. You may need the \`Flex' package in order for those modifications to take effect. You can get \`Flex' from any GNU archive site." rm -f lex.yy.c if test $# -ne 1; then eval LASTARG=\${$#} case $LASTARG in *.l) SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'` if test -f "$SRCFILE"; then cp "$SRCFILE" lex.yy.c fi ;; esac fi if test ! -f lex.yy.c; then echo 'main() { return 0; }' >lex.yy.c fi ;; help2man*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified a dependency of a manual page. You may need the \`Help2man' package in order for those modifications to take effect. You can get \`Help2man' from any GNU archive site." file=`echo "$*" | sed -n "$sed_output"` test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` if test -f "$file"; then touch $file else test -z "$file" || exec >$file echo ".ab help2man is required to generate this page" exit $? fi ;; makeinfo*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified a \`.texi' or \`.texinfo' file, or any other file indirectly affecting the aspect of the manual. The spurious call might also be the consequence of using a buggy \`make' (AIX, DU, IRIX). You might want to install the \`Texinfo' package or the \`GNU make' package. Grab either from any GNU archive site." # The file to touch is that specified with -o ... file=`echo "$*" | sed -n "$sed_output"` test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` if test -z "$file"; then # ... or it is the one specified with @setfilename ... infile=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'` file=`sed -n ' /^@setfilename/{ s/.* \([^ ]*\) *$/\1/ p q }' $infile` # ... or it is derived from the source name (dir/f.texi becomes f.info) test -z "$file" && file=`echo "$infile" | sed 's,.*/,,;s,.[^.]*$,,'`.info fi # If the file does not exist, the user really needs makeinfo; # let's fail without touching anything. test -f $file || exit 1 touch $file ;; *) echo 1>&2 "\ WARNING: \`$1' is needed, and is $msg. You might have modified some files without having the proper tools for further handling them. Check the \`README' file, it often tells you about the needed prerequisites for installing this package. You may also peek at any GNU archive site, in case some other package would contain this missing \`$1' program." exit 1 ;; esac exit 0 # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: sauerbraten-0.0.20130203.dfsg/enet/list.c0000644000175000017500000000305311424165077017457 0ustar vincentvincent/** @file list.c @brief ENet linked list functions */ #define ENET_BUILDING_LIB 1 #include "enet/enet.h" /** @defgroup list ENet linked list utility functions @ingroup private @{ */ void enet_list_clear (ENetList * list) { list -> sentinel.next = & list -> sentinel; list -> sentinel.previous = & list -> sentinel; } ENetListIterator enet_list_insert (ENetListIterator position, void * data) { ENetListIterator result = (ENetListIterator) data; result -> previous = position -> previous; result -> next = position; result -> previous -> next = result; position -> previous = result; return result; } void * enet_list_remove (ENetListIterator position) { position -> previous -> next = position -> next; position -> next -> previous = position -> previous; return position; } ENetListIterator enet_list_move (ENetListIterator position, void * dataFirst, void * dataLast) { ENetListIterator first = (ENetListIterator) dataFirst, last = (ENetListIterator) dataLast; first -> previous -> next = last -> next; last -> next -> previous = first -> previous; first -> previous = position -> previous; last -> next = position; first -> previous -> next = first; position -> previous = last; return first; } size_t enet_list_size (ENetList * list) { size_t size = 0; ENetListIterator position; for (position = enet_list_begin (list); position != enet_list_end (list); position = enet_list_next (position)) ++ size; return size; } /** @} */ sauerbraten-0.0.20130203.dfsg/enet/Doxyfile0000644000175000017500000011503311112171364020036 0ustar vincentvincent# Doxyfile 1.2.18 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project # # All text after a hash (#) is considered a comment and will be ignored # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" ") #--------------------------------------------------------------------------- # General configuration options #--------------------------------------------------------------------------- # The PROJECT_NAME tag is a single word (or a sequence of words surrounded # by quotes) that should identify the project. PROJECT_NAME = enet # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = docs # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Brazilian, Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, Dutch, # Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en # (Japanese with english messages), Korean, Norwegian, Polish, Portuguese, # Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish and Ukrainian. OUTPUT_LANGUAGE = English # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = NO # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these class will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = NO # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all inherited # members of a class in the documentation of that class as if those members were # ordinary class members. Constructors, destructors and assignment operators of # the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. It is allowed to use relative paths in the argument list. STRIP_FROM_PATH = # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower case letters. If set to YES upper case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # users are adviced to set this option to NO. CASE_SENSE_NAMES = YES # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful is your file systems # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like the Qt-style comments (thus requiring an # explict @brief command for a brief description. JAVADOC_AUTOBRIEF = YES # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the DETAILS_AT_TOP tag is set to YES then Doxygen # will output the detailed description near the top, like JavaDoc. # If set to NO, the detailed description appears after the member # documentation. DETAILS_AT_TOP = YES # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # reimplements. INHERIT_DOCS = YES # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 8 # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or define consist of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and defines in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. # For instance some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = YES # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java sources # only. Doxygen will then generate output that is more tailored for Java. # For instance namespaces will be presented as packages, qualified scopes # will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = . include/enet docs # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx *.hpp # *.h++ *.idl *.odl FILE_PATTERNS = *.c *.h *.dox # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. EXCLUDE = Tests # The EXCLUDE_SYMLINKS tag can be used select whether or not files or directories # that are symbolic links (a Unix filesystem feature) are excluded from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. EXCLUDE_PATTERNS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. INPUT_FILTER = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # If the REFERENCED_BY_RELATION tag is set to YES (the default) # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES (the default) # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = YES # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet HTML_STYLESHEET = # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compressed HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output dir. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non empty doxygen will try to run # the html help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the Html help documentation and to the tree view. TOC_EXPAND = NO # The DISABLE_INDEX tag can be used to turn on/off the condensed index at # top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. DISABLE_INDEX = NO # This tag can be used to set the number of enum values (range [1..20]) # that doxygen will group on one line in the generated HTML documentation. ENUM_VALUES_PER_LINE = 4 # If the GENERATE_TREEVIEW tag is set to YES, a side panel will be # generated containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript and frames is required (for instance Mozilla, Netscape 4.0+, # or Internet explorer 4.0+). Note that for large projects the tree generation # can take a very long time. In such cases it is better to disable this feature. # Windows users are probably better off using the HTML help feature. GENERATE_TREEVIEW = NO # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be invoked. If left blank `latex' will be used as the default command name. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, a4wide, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = NO # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = NO # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimised for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load stylesheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assigments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_XML = NO # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = NO # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_PREDEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. PREDEFINED = FORCE_DOXYGEN # If the MACRO_EXPANSION and EXPAND_PREDEF_ONLY tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all function-like macros that are alone # on a line, have an all uppercase name, and do not end with a semicolon. Such # function macros are typically used for boiler-plate code, and will confuse the # parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::addtions related to external references #--------------------------------------------------------------------------- # The TAGFILES tag can be used to specify one or more tagfiles. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in Html, RTF and LaTeX) for classes with base or # super classes. Setting the tag to NO turns the diagrams off. Note that this # option is superceded by the HAVE_DOT option below. This is only a fallback. It is # recommended to install and use dot, since it yield more powerful graphs. CLASS_DIAGRAMS = YES # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = NO # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # the CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are png, jpg, or gif # If left blank png will be used. DOT_IMAGE_FORMAT = png # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found on the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MAX_DOT_GRAPH_WIDTH tag can be used to set the maximum allowed width # (in pixels) of the graphs generated by dot. If a graph becomes larger than # this value, doxygen will try to truncate the graph, so that it fits within # the specified constraint. Beware that most browsers cannot cope with very # large images. MAX_DOT_GRAPH_WIDTH = 1024 # The MAX_DOT_GRAPH_HEIGHT tag can be used to set the maximum allows height # (in pixels) of the graphs generated by dot. If a graph becomes larger than # this value, doxygen will try to truncate the graph, so that it fits within # the specified constraint. Beware that most browsers cannot cope with very # large images. MAX_DOT_GRAPH_HEIGHT = 1024 # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermedate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES #--------------------------------------------------------------------------- # Configuration::addtions related to the search engine #--------------------------------------------------------------------------- # The SEARCHENGINE tag specifies whether or not a search engine should be # used. If set to NO the values of all tags below this one will be ignored. SEARCHENGINE = NO # The CGI_NAME tag should be the name of the CGI script that # starts the search engine (doxysearch) with the correct parameters. # A script with this name will be generated by doxygen. CGI_NAME = search.cgi # The CGI_URL tag should be the absolute URL to the directory where the # cgi binaries are located. See the documentation of your http daemon for # details. CGI_URL = # The DOC_URL tag should be the absolute URL to the directory where the # documentation is located. If left blank the absolute path to the # documentation, with file:// prepended to it, will be used. DOC_URL = # The DOC_ABSPATH tag should be the absolute path to the directory where the # documentation is located. If left blank the directory on the local machine # will be used. DOC_ABSPATH = # The BIN_ABSPATH tag must point to the directory where the doxysearch binary # is installed. BIN_ABSPATH = /usr/local/bin/ # The EXT_DOC_PATHS tag can be used to specify one or more paths to # documentation generated for other projects. This allows doxysearch to search # the documentation for these projects as well. EXT_DOC_PATHS = sauerbraten-0.0.20130203.dfsg/enet/aclocal.m40000644000175000017500000010774612006035707020207 0ustar vincentvincent# generated automatically by aclocal 1.11.6 -*- Autoconf -*- # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, # 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, # Inc. # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.69],, [m4_warning([this file was generated for autoconf 2.69. You have another version of autoconf. It may work, but is not guaranteed to. If you have problems, you may need to regenerate the build system entirely. To do so, use the procedure documented by the package, typically `autoreconf'.])]) # Copyright (C) 2002, 2003, 2005, 2006, 2007, 2008, 2011 Free Software # Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 1 # AM_AUTOMAKE_VERSION(VERSION) # ---------------------------- # Automake X.Y traces this macro to ensure aclocal.m4 has been # generated from the m4 files accompanying Automake X.Y. # (This private macro should not be called outside this file.) AC_DEFUN([AM_AUTOMAKE_VERSION], [am__api_version='1.11' dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to dnl require some minimum version. Point them to the right macro. m4_if([$1], [1.11.6], [], [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl ]) # _AM_AUTOCONF_VERSION(VERSION) # ----------------------------- # aclocal traces this macro to find the Autoconf version. # This is a private macro too. Using m4_define simplifies # the logic in aclocal, which can simply ignore this definition. m4_define([_AM_AUTOCONF_VERSION], []) # AM_SET_CURRENT_AUTOMAKE_VERSION # ------------------------------- # Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. # This function is AC_REQUIREd by AM_INIT_AUTOMAKE. AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], [AM_AUTOMAKE_VERSION([1.11.6])dnl m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl _AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) # AM_AUX_DIR_EXPAND -*- Autoconf -*- # Copyright (C) 2001, 2003, 2005, 2011 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 1 # For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets # $ac_aux_dir to `$srcdir/foo'. In other projects, it is set to # `$srcdir', `$srcdir/..', or `$srcdir/../..'. # # Of course, Automake must honor this variable whenever it calls a # tool from the auxiliary directory. The problem is that $srcdir (and # therefore $ac_aux_dir as well) can be either absolute or relative, # depending on how configure is run. This is pretty annoying, since # it makes $ac_aux_dir quite unusable in subdirectories: in the top # source directory, any form will work fine, but in subdirectories a # relative path needs to be adjusted first. # # $ac_aux_dir/missing # fails when called from a subdirectory if $ac_aux_dir is relative # $top_srcdir/$ac_aux_dir/missing # fails if $ac_aux_dir is absolute, # fails when called from a subdirectory in a VPATH build with # a relative $ac_aux_dir # # The reason of the latter failure is that $top_srcdir and $ac_aux_dir # are both prefixed by $srcdir. In an in-source build this is usually # harmless because $srcdir is `.', but things will broke when you # start a VPATH build or use an absolute $srcdir. # # So we could use something similar to $top_srcdir/$ac_aux_dir/missing, # iff we strip the leading $srcdir from $ac_aux_dir. That would be: # am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"` # and then we would define $MISSING as # MISSING="\${SHELL} $am_aux_dir/missing" # This will work as long as MISSING is not called from configure, because # unfortunately $(top_srcdir) has no meaning in configure. # However there are other variables, like CC, which are often used in # configure, and could therefore not use this "fixed" $ac_aux_dir. # # Another solution, used here, is to always expand $ac_aux_dir to an # absolute PATH. The drawback is that using absolute paths prevent a # configured tree to be moved without reconfiguration. AC_DEFUN([AM_AUX_DIR_EXPAND], [dnl Rely on autoconf to set up CDPATH properly. AC_PREREQ([2.50])dnl # expand $ac_aux_dir to an absolute path am_aux_dir=`cd $ac_aux_dir && pwd` ]) # AM_CONDITIONAL -*- Autoconf -*- # Copyright (C) 1997, 2000, 2001, 2003, 2004, 2005, 2006, 2008 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 9 # AM_CONDITIONAL(NAME, SHELL-CONDITION) # ------------------------------------- # Define a conditional. AC_DEFUN([AM_CONDITIONAL], [AC_PREREQ(2.52)dnl ifelse([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl AC_SUBST([$1_TRUE])dnl AC_SUBST([$1_FALSE])dnl _AM_SUBST_NOTMAKE([$1_TRUE])dnl _AM_SUBST_NOTMAKE([$1_FALSE])dnl m4_define([_AM_COND_VALUE_$1], [$2])dnl if $2; then $1_TRUE= $1_FALSE='#' else $1_TRUE='#' $1_FALSE= fi AC_CONFIG_COMMANDS_PRE( [if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then AC_MSG_ERROR([[conditional "$1" was never defined. Usually this means the macro was only invoked conditionally.]]) fi])]) # Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2009, # 2010, 2011 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 12 # There are a few dirty hacks below to avoid letting `AC_PROG_CC' be # written in clear, in which case automake, when reading aclocal.m4, # will think it sees a *use*, and therefore will trigger all it's # C support machinery. Also note that it means that autoscan, seeing # CC etc. in the Makefile, will ask for an AC_PROG_CC use... # _AM_DEPENDENCIES(NAME) # ---------------------- # See how the compiler implements dependency checking. # NAME is "CC", "CXX", "GCJ", or "OBJC". # We try a few techniques and use that to set a single cache variable. # # We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was # modified to invoke _AM_DEPENDENCIES(CC); we would have a circular # dependency, and given that the user is not expected to run this macro, # just rely on AC_PROG_CC. AC_DEFUN([_AM_DEPENDENCIES], [AC_REQUIRE([AM_SET_DEPDIR])dnl AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl AC_REQUIRE([AM_MAKE_INCLUDE])dnl AC_REQUIRE([AM_DEP_TRACK])dnl ifelse([$1], CC, [depcc="$CC" am_compiler_list=], [$1], CXX, [depcc="$CXX" am_compiler_list=], [$1], OBJC, [depcc="$OBJC" am_compiler_list='gcc3 gcc'], [$1], UPC, [depcc="$UPC" am_compiler_list=], [$1], GCJ, [depcc="$GCJ" am_compiler_list='gcc3 gcc'], [depcc="$$1" am_compiler_list=]) AC_CACHE_CHECK([dependency style of $depcc], [am_cv_$1_dependencies_compiler_type], [if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named `D' -- because `-MD' means `put the output # in D'. rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_$1_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` fi am__universal=false m4_case([$1], [CC], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac], [CXX], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac]) for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with # Solaris 8's {/usr,}/bin/sh. touch sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with `-c' and `-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle `-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # after this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok `-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_$1_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_$1_dependencies_compiler_type=none fi ]) AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type]) AM_CONDITIONAL([am__fastdep$1], [ test "x$enable_dependency_tracking" != xno \ && test "$am_cv_$1_dependencies_compiler_type" = gcc3]) ]) # AM_SET_DEPDIR # ------------- # Choose a directory name for dependency files. # This macro is AC_REQUIREd in _AM_DEPENDENCIES AC_DEFUN([AM_SET_DEPDIR], [AC_REQUIRE([AM_SET_LEADING_DOT])dnl AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl ]) # AM_DEP_TRACK # ------------ AC_DEFUN([AM_DEP_TRACK], [AC_ARG_ENABLE(dependency-tracking, [ --disable-dependency-tracking speeds up one-time build --enable-dependency-tracking do not reject slow dependency extractors]) if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) AC_SUBST([AMDEPBACKSLASH])dnl _AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl AC_SUBST([am__nodep])dnl _AM_SUBST_NOTMAKE([am__nodep])dnl ]) # Generate code to set up dependency tracking. -*- Autoconf -*- # Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2008 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. #serial 5 # _AM_OUTPUT_DEPENDENCY_COMMANDS # ------------------------------ AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], [{ # Autoconf 2.62 quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named `Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`AS_DIRNAME("$mf")` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running `make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # When using ansi2knr, U may be empty or an underscore; expand it U=`sed -n 's/^U = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`AS_DIRNAME(["$file"])` AS_MKDIR_P([$dirpart/$fdir]) # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done } ])# _AM_OUTPUT_DEPENDENCY_COMMANDS # AM_OUTPUT_DEPENDENCY_COMMANDS # ----------------------------- # This macro should only be invoked once -- use via AC_REQUIRE. # # This code is only required when automatic dependency tracking # is enabled. FIXME. This creates each `.P' file that we will # need in order to bootstrap the dependency handling code. AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], [AC_CONFIG_COMMANDS([depfiles], [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS], [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"]) ]) # Do all the work for Automake. -*- Autoconf -*- # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, # 2005, 2006, 2008, 2009 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 16 # This macro actually does too much. Some checks are only needed if # your package does certain things. But this isn't really a big deal. # AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) # AM_INIT_AUTOMAKE([OPTIONS]) # ----------------------------------------------- # The call with PACKAGE and VERSION arguments is the old style # call (pre autoconf-2.50), which is being phased out. PACKAGE # and VERSION should now be passed to AC_INIT and removed from # the call to AM_INIT_AUTOMAKE. # We support both call styles for the transition. After # the next Automake release, Autoconf can make the AC_INIT # arguments mandatory, and then we can depend on a new Autoconf # release and drop the old call support. AC_DEFUN([AM_INIT_AUTOMAKE], [AC_PREREQ([2.62])dnl dnl Autoconf wants to disallow AM_ names. We explicitly allow dnl the ones we care about. m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl AC_REQUIRE([AC_PROG_INSTALL])dnl if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl # test to see if srcdir already configured if test -f $srcdir/config.status; then AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi AC_SUBST([CYGPATH_W]) # Define the identity of the package. dnl Distinguish between old-style and new-style calls. m4_ifval([$2], [m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl AC_SUBST([PACKAGE], [$1])dnl AC_SUBST([VERSION], [$2])], [_AM_SET_OPTIONS([$1])dnl dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. m4_if(m4_ifdef([AC_PACKAGE_NAME], 1)m4_ifdef([AC_PACKAGE_VERSION], 1), 11,, [m4_fatal([AC_INIT should be called with package and version arguments])])dnl AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl _AM_IF_OPTION([no-define],, [AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of package]) AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version number of package])])dnl # Some tools Automake needs. AC_REQUIRE([AM_SANITY_CHECK])dnl AC_REQUIRE([AC_ARG_PROGRAM])dnl AM_MISSING_PROG(ACLOCAL, aclocal-${am__api_version}) AM_MISSING_PROG(AUTOCONF, autoconf) AM_MISSING_PROG(AUTOMAKE, automake-${am__api_version}) AM_MISSING_PROG(AUTOHEADER, autoheader) AM_MISSING_PROG(MAKEINFO, makeinfo) AC_REQUIRE([AM_PROG_INSTALL_SH])dnl AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl AC_REQUIRE([AM_PROG_MKDIR_P])dnl # We need awk for the "check" target. The system "awk" is bad on # some platforms. AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([AC_PROG_MAKE_SET])dnl AC_REQUIRE([AM_SET_LEADING_DOT])dnl _AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], [_AM_PROG_TAR([v7])])]) _AM_IF_OPTION([no-dependencies],, [AC_PROVIDE_IFELSE([AC_PROG_CC], [_AM_DEPENDENCIES(CC)], [define([AC_PROG_CC], defn([AC_PROG_CC])[_AM_DEPENDENCIES(CC)])])dnl AC_PROVIDE_IFELSE([AC_PROG_CXX], [_AM_DEPENDENCIES(CXX)], [define([AC_PROG_CXX], defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJC], [_AM_DEPENDENCIES(OBJC)], [define([AC_PROG_OBJC], defn([AC_PROG_OBJC])[_AM_DEPENDENCIES(OBJC)])])dnl ]) _AM_IF_OPTION([silent-rules], [AC_REQUIRE([AM_SILENT_RULES])])dnl dnl The `parallel-tests' driver may need to know about EXEEXT, so add the dnl `am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen. This macro dnl is hooked onto _AC_COMPILER_EXEEXT early, see below. AC_CONFIG_COMMANDS_PRE(dnl [m4_provide_if([_AM_COMPILER_EXEEXT], [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl ]) dnl Hook into `_AC_COMPILER_EXEEXT' early to learn its expansion. Do not dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further dnl mangled by Autoconf and run in a shell conditional statement. m4_define([_AC_COMPILER_EXEEXT], m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])]) # When config.status generates a header, we must update the stamp-h file. # This file resides in the same directory as the config header # that is generated. The stamp files are numbered to have different names. # Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the # loop where config.status creates the headers, so we can generate # our stamp files there. AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], [# Compute $1's index in $config_headers. _am_arg=$1 _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) # Copyright (C) 2001, 2003, 2005, 2008, 2011 Free Software Foundation, # Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 1 # AM_PROG_INSTALL_SH # ------------------ # Define $install_sh. AC_DEFUN([AM_PROG_INSTALL_SH], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl if test x"${install_sh}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi AC_SUBST(install_sh)]) # Copyright (C) 2003, 2005 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 2 # Check whether the underlying file-system supports filenames # with a leading dot. For instance MS-DOS doesn't. AC_DEFUN([AM_SET_LEADING_DOT], [rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null AC_SUBST([am__leading_dot])]) # Add --enable-maintainer-mode option to configure. -*- Autoconf -*- # From Jim Meyering # Copyright (C) 1996, 1998, 2000, 2001, 2002, 2003, 2004, 2005, 2008, # 2011 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 5 # AM_MAINTAINER_MODE([DEFAULT-MODE]) # ---------------------------------- # Control maintainer-specific portions of Makefiles. # Default is to disable them, unless `enable' is passed literally. # For symmetry, `disable' may be passed as well. Anyway, the user # can override the default with the --enable/--disable switch. AC_DEFUN([AM_MAINTAINER_MODE], [m4_case(m4_default([$1], [disable]), [enable], [m4_define([am_maintainer_other], [disable])], [disable], [m4_define([am_maintainer_other], [enable])], [m4_define([am_maintainer_other], [enable]) m4_warn([syntax], [unexpected argument to AM@&t@_MAINTAINER_MODE: $1])]) AC_MSG_CHECKING([whether to enable maintainer-specific portions of Makefiles]) dnl maintainer-mode's default is 'disable' unless 'enable' is passed AC_ARG_ENABLE([maintainer-mode], [ --][am_maintainer_other][-maintainer-mode am_maintainer_other make rules and dependencies not useful (and sometimes confusing) to the casual installer], [USE_MAINTAINER_MODE=$enableval], [USE_MAINTAINER_MODE=]m4_if(am_maintainer_other, [enable], [no], [yes])) AC_MSG_RESULT([$USE_MAINTAINER_MODE]) AM_CONDITIONAL([MAINTAINER_MODE], [test $USE_MAINTAINER_MODE = yes]) MAINT=$MAINTAINER_MODE_TRUE AC_SUBST([MAINT])dnl ] ) AU_DEFUN([jm_MAINTAINER_MODE], [AM_MAINTAINER_MODE]) # Check to see how 'make' treats includes. -*- Autoconf -*- # Copyright (C) 2001, 2002, 2003, 2005, 2009 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 4 # AM_MAKE_INCLUDE() # ----------------- # Check to see how make treats includes. AC_DEFUN([AM_MAKE_INCLUDE], [am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo this is the am__doit target .PHONY: am__doit END # If we don't find an include directive, just comment out the code. AC_MSG_CHECKING([for style of include used by $am_make]) am__include="#" am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf # Ignore all kinds of additional output from `make'. case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=include am__quote= _am_result=GNU ;; esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=.include am__quote="\"" _am_result=BSD ;; esac fi AC_SUBST([am__include]) AC_SUBST([am__quote]) AC_MSG_RESULT([$_am_result]) rm -f confinc confmf ]) # Fake the existence of programs that GNU maintainers use. -*- Autoconf -*- # Copyright (C) 1997, 1999, 2000, 2001, 2003, 2004, 2005, 2008 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 6 # AM_MISSING_PROG(NAME, PROGRAM) # ------------------------------ AC_DEFUN([AM_MISSING_PROG], [AC_REQUIRE([AM_MISSING_HAS_RUN]) $1=${$1-"${am_missing_run}$2"} AC_SUBST($1)]) # AM_MISSING_HAS_RUN # ------------------ # Define MISSING if not defined so far and test if it supports --run. # If it does, set am_missing_run to use it, otherwise, to nothing. AC_DEFUN([AM_MISSING_HAS_RUN], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([missing])dnl if test x"${MISSING+set}" != xset; then case $am_aux_dir in *\ * | *\ *) MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; *) MISSING="\${SHELL} $am_aux_dir/missing" ;; esac fi # Use eval to expand $SHELL if eval "$MISSING --run true"; then am_missing_run="$MISSING --run " else am_missing_run= AC_MSG_WARN([`missing' script is too old or missing]) fi ]) # Copyright (C) 2003, 2004, 2005, 2006, 2011 Free Software Foundation, # Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 1 # AM_PROG_MKDIR_P # --------------- # Check for `mkdir -p'. AC_DEFUN([AM_PROG_MKDIR_P], [AC_PREREQ([2.60])dnl AC_REQUIRE([AC_PROG_MKDIR_P])dnl dnl Automake 1.8 to 1.9.6 used to define mkdir_p. We now use MKDIR_P, dnl while keeping a definition of mkdir_p for backward compatibility. dnl @MKDIR_P@ is magic: AC_OUTPUT adjusts its value for each Makefile. dnl However we cannot define mkdir_p as $(MKDIR_P) for the sake of dnl Makefile.ins that do not define MKDIR_P, so we do our own dnl adjustment using top_builddir (which is defined more often than dnl MKDIR_P). AC_SUBST([mkdir_p], ["$MKDIR_P"])dnl case $mkdir_p in [[\\/$]]* | ?:[[\\/]]*) ;; */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; esac ]) # Helper functions for option handling. -*- Autoconf -*- # Copyright (C) 2001, 2002, 2003, 2005, 2008, 2010 Free Software # Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 5 # _AM_MANGLE_OPTION(NAME) # ----------------------- AC_DEFUN([_AM_MANGLE_OPTION], [[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) # _AM_SET_OPTION(NAME) # -------------------- # Set option NAME. Presently that only means defining a flag for this option. AC_DEFUN([_AM_SET_OPTION], [m4_define(_AM_MANGLE_OPTION([$1]), 1)]) # _AM_SET_OPTIONS(OPTIONS) # ------------------------ # OPTIONS is a space-separated list of Automake options. AC_DEFUN([_AM_SET_OPTIONS], [m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) # _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET]) # ------------------------------------------- # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. AC_DEFUN([_AM_IF_OPTION], [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) # Check to make sure that the build environment is sane. -*- Autoconf -*- # Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005, 2008 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 5 # AM_SANITY_CHECK # --------------- AC_DEFUN([AM_SANITY_CHECK], [AC_MSG_CHECKING([whether build environment is sane]) # Just in case sleep 1 echo timestamp > conftest.file # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[[\\\"\#\$\&\'\`$am_lf]]*) AC_MSG_ERROR([unsafe absolute working directory name]);; esac case $srcdir in *[[\\\"\#\$\&\'\`$am_lf\ \ ]]*) AC_MSG_ERROR([unsafe srcdir value: `$srcdir']);; esac # Do `set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` if test "$[*]" = "X"; then # -L didn't work. set X `ls -t "$srcdir/configure" conftest.file` fi rm -f conftest.file if test "$[*]" != "X $srcdir/configure conftest.file" \ && test "$[*]" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken alias in your environment]) fi test "$[2]" = conftest.file ) then # Ok. : else AC_MSG_ERROR([newly created file is older than distributed files! Check your system clock]) fi AC_MSG_RESULT(yes)]) # Copyright (C) 2001, 2003, 2005, 2011 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 1 # AM_PROG_INSTALL_STRIP # --------------------- # One issue with vendor `install' (even GNU) is that you can't # specify the program used to strip binaries. This is especially # annoying in cross-compiling environments, where the build's strip # is unlikely to handle the host's binaries. # Fortunately install-sh will honor a STRIPPROG variable, so we # always use install-sh in `make install-strip', and initialize # STRIPPROG with the value of the STRIP variable (set by the user). AC_DEFUN([AM_PROG_INSTALL_STRIP], [AC_REQUIRE([AM_PROG_INSTALL_SH])dnl # Installed binaries are usually stripped using `strip' when the user # run `make install-strip'. However `strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the `STRIP' environment variable to overrule this program. dnl Don't test for $cross_compiling = yes, because it might be `maybe'. if test "$cross_compiling" != no; then AC_CHECK_TOOL([STRIP], [strip], :) fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" AC_SUBST([INSTALL_STRIP_PROGRAM])]) # Copyright (C) 2006, 2008, 2010 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 3 # _AM_SUBST_NOTMAKE(VARIABLE) # --------------------------- # Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in. # This macro is traced by Automake. AC_DEFUN([_AM_SUBST_NOTMAKE]) # AM_SUBST_NOTMAKE(VARIABLE) # -------------------------- # Public sister of _AM_SUBST_NOTMAKE. AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)]) # Check how to create a tarball. -*- Autoconf -*- # Copyright (C) 2004, 2005, 2012 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 2 # _AM_PROG_TAR(FORMAT) # -------------------- # Check how to create a tarball in format FORMAT. # FORMAT should be one of `v7', `ustar', or `pax'. # # Substitute a variable $(am__tar) that is a command # writing to stdout a FORMAT-tarball containing the directory # $tardir. # tardir=directory && $(am__tar) > result.tar # # Substitute a variable $(am__untar) that extract such # a tarball read from stdin. # $(am__untar) < result.tar AC_DEFUN([_AM_PROG_TAR], [# Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AC_SUBST([AMTAR], ['$${TAR-tar}']) m4_if([$1], [v7], [am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'], [m4_case([$1], [ustar],, [pax],, [m4_fatal([Unknown tar format])]) AC_MSG_CHECKING([how to create a $1 tar archive]) # Loop over all known methods to create a tar archive until one works. _am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' _am_tools=${am_cv_prog_tar_$1-$_am_tools} # Do not fold the above two line into one, because Tru64 sh and # Solaris sh will not grok spaces in the rhs of `-'. for _am_tool in $_am_tools do case $_am_tool in gnutar) for _am_tar in tar gnutar gtar; do AM_RUN_LOG([$_am_tar --version]) && break done am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"' am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"' am__untar="$_am_tar -xf -" ;; plaintar) # Must skip GNU tar: if it does not support --format= it doesn't create # ustar tarball either. (tar --version) >/dev/null 2>&1 && continue am__tar='tar chf - "$$tardir"' am__tar_='tar chf - "$tardir"' am__untar='tar xf -' ;; pax) am__tar='pax -L -x $1 -w "$$tardir"' am__tar_='pax -L -x $1 -w "$tardir"' am__untar='pax -r' ;; cpio) am__tar='find "$$tardir" -print | cpio -o -H $1 -L' am__tar_='find "$tardir" -print | cpio -o -H $1 -L' am__untar='cpio -i -H $1 -d' ;; none) am__tar=false am__tar_=false am__untar=false ;; esac # If the value was cached, stop now. We just wanted to have am__tar # and am__untar set. test -n "${am_cv_prog_tar_$1}" && break # tar/untar a dummy directory, and stop if the command works rm -rf conftest.dir mkdir conftest.dir echo GrepMe > conftest.dir/file AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar]) rm -rf conftest.dir if test -s conftest.tar; then AM_RUN_LOG([$am__untar /dev/null 2>&1 && break fi done rm -rf conftest.dir AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool]) AC_MSG_RESULT([$am_cv_prog_tar_$1])]) AC_SUBST([am__tar]) AC_SUBST([am__untar]) ]) # _AM_PROG_TAR m4_include([m4/libtool.m4]) m4_include([m4/ltoptions.m4]) m4_include([m4/ltsugar.m4]) m4_include([m4/ltversion.m4]) m4_include([m4/lt~obsolete.m4]) sauerbraten-0.0.20130203.dfsg/enet/Makefile.am0000644000175000017500000000122512061673417020373 0ustar vincentvincentpkgconfigdir = $(libdir)/pkgconfig nodist_pkgconfig_DATA = libenet.pc enetincludedir=$(includedir)/enet enetinclude_HEADERS = \ include/enet/callbacks.h \ include/enet/enet.h \ include/enet/list.h \ include/enet/protocol.h \ include/enet/time.h \ include/enet/types.h \ include/enet/unix.h \ include/enet/utility.h \ include/enet/win32.h lib_LTLIBRARIES = libenet.la libenet_la_SOURCES = callbacks.c compress.c host.c list.c packet.c peer.c protocol.c unix.c win32.c # see info '(libtool) Updating version info' before making a release libenet_la_LDFLAGS = $(AM_LDFLAGS) -version-info 3:0:1 INCLUDES = -I$(top_srcdir)/include ACLOCAL_AMFLAGS = -Im4 sauerbraten-0.0.20130203.dfsg/enet/config.guess0000755000175000017500000012743211761204106020657 0ustar vincentvincent#! /bin/sh # Attempt to guess a canonical system name. # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, # 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, # 2011, 2012 Free Software Foundation, Inc. timestamp='2012-02-10' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Originally written by Per Bothner. Please send patches (context # diff format) to and include a ChangeLog # entry. # # This script attempts to guess a canonical system name similar to # config.sub. If it succeeds, it prints the system name on stdout, and # exits with 0. Otherwise, it exits with 1. # # You can get the latest version of this script from: # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] Output the configuration name of the system \`$me' is run on. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; * ) break ;; esac done if test $# != 0; then echo "$me: too many arguments$help" >&2 exit 1 fi trap 'exit 1' 1 2 15 # CC_FOR_BUILD -- compiler used by this script. Note that the use of a # compiler to aid in system detection is discouraged as it requires # temporary files to be created and, as you can see below, it is a # headache to deal with in a portable fashion. # Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still # use `HOST_CC' if defined, but it is deprecated. # Portable tmp directory creation inspired by the Autoconf team. set_cc_for_build=' trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; : ${TMPDIR=/tmp} ; { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; dummy=$tmp/dummy ; tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; case $CC_FOR_BUILD,$HOST_CC,$CC in ,,) echo "int x;" > $dummy.c ; for c in cc gcc c89 c99 ; do if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then CC_FOR_BUILD="$c"; break ; fi ; done ; if test x"$CC_FOR_BUILD" = x ; then CC_FOR_BUILD=no_compiler_found ; fi ;; ,,*) CC_FOR_BUILD=$CC ;; ,*,*) CC_FOR_BUILD=$HOST_CC ;; esac ; set_cc_for_build= ;' # This is needed to find uname on a Pyramid OSx when run in the BSD universe. # (ghazi@noc.rutgers.edu 1994-08-24) if (test -f /.attbin/uname) >/dev/null 2>&1 ; then PATH=$PATH:/.attbin ; export PATH fi UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown # Note: order is significant - the case branches are not exclusive. case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in *:NetBSD:*:*) # NetBSD (nbsd) targets should (where applicable) match one or # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently # switched to ELF, *-*-netbsd* would select the old # object file format. This provides both forward # compatibility and a consistent mechanism for selecting the # object file format. # # Note: NetBSD doesn't particularly care about the vendor # portion of the name. We always set it to "unknown". sysctl="sysctl -n hw.machine_arch" UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ /usr/sbin/$sysctl 2>/dev/null || echo unknown)` case "${UNAME_MACHINE_ARCH}" in armeb) machine=armeb-unknown ;; arm*) machine=arm-unknown ;; sh3el) machine=shl-unknown ;; sh3eb) machine=sh-unknown ;; sh5el) machine=sh5le-unknown ;; *) machine=${UNAME_MACHINE_ARCH}-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently, or will in the future. case "${UNAME_MACHINE_ARCH}" in arm*|i386|m68k|ns32k|sh3*|sparc|vax) eval $set_cc_for_build if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ELF__ then # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). # Return netbsd for either. FIX? os=netbsd else os=netbsdelf fi ;; *) os=netbsd ;; esac # The OS release # Debian GNU/NetBSD machines have a different userland, and # thus, need a distinct triplet. However, they do not need # kernel version information, so it can be replaced with a # suitable tag, in the style of linux-gnu. case "${UNAME_VERSION}" in Debian*) release='-gnu' ;; *) release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` ;; esac # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. echo "${machine}-${os}${release}" exit ;; *:OpenBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} exit ;; *:ekkoBSD:*:*) echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} exit ;; *:SolidBSD:*:*) echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} exit ;; macppc:MirBSD:*:*) echo powerpc-unknown-mirbsd${UNAME_RELEASE} exit ;; *:MirBSD:*:*) echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} exit ;; alpha:OSF1:*:*) case $UNAME_RELEASE in *4.0) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` ;; *5.*) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` ;; esac # According to Compaq, /usr/sbin/psrinfo has been available on # OSF/1 and Tru64 systems produced since 1995. I hope that # covers most systems running today. This code pipes the CPU # types through head -n 1, so we only detect the type of CPU 0. ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` case "$ALPHA_CPU_TYPE" in "EV4 (21064)") UNAME_MACHINE="alpha" ;; "EV4.5 (21064)") UNAME_MACHINE="alpha" ;; "LCA4 (21066/21068)") UNAME_MACHINE="alpha" ;; "EV5 (21164)") UNAME_MACHINE="alphaev5" ;; "EV5.6 (21164A)") UNAME_MACHINE="alphaev56" ;; "EV5.6 (21164PC)") UNAME_MACHINE="alphapca56" ;; "EV5.7 (21164PC)") UNAME_MACHINE="alphapca57" ;; "EV6 (21264)") UNAME_MACHINE="alphaev6" ;; "EV6.7 (21264A)") UNAME_MACHINE="alphaev67" ;; "EV6.8CB (21264C)") UNAME_MACHINE="alphaev68" ;; "EV6.8AL (21264B)") UNAME_MACHINE="alphaev68" ;; "EV6.8CX (21264D)") UNAME_MACHINE="alphaev68" ;; "EV6.9A (21264/EV69A)") UNAME_MACHINE="alphaev69" ;; "EV7 (21364)") UNAME_MACHINE="alphaev7" ;; "EV7.9 (21364A)") UNAME_MACHINE="alphaev79" ;; esac # A Pn.n version is a patched version. # A Vn.n version is a released version. # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` # Reset EXIT trap before exiting to avoid spurious non-zero exit code. exitcode=$? trap '' 0 exit $exitcode ;; Alpha\ *:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # Should we change UNAME_MACHINE based on the output of uname instead # of the specific Alpha model? echo alpha-pc-interix exit ;; 21064:Windows_NT:50:3) echo alpha-dec-winnt3.5 exit ;; Amiga*:UNIX_System_V:4.0:*) echo m68k-unknown-sysv4 exit ;; *:[Aa]miga[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-amigaos exit ;; *:[Mm]orph[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-morphos exit ;; *:OS/390:*:*) echo i370-ibm-openedition exit ;; *:z/VM:*:*) echo s390-ibm-zvmoe exit ;; *:OS400:*:*) echo powerpc-ibm-os400 exit ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) echo arm-acorn-riscix${UNAME_RELEASE} exit ;; arm:riscos:*:*|arm:RISCOS:*:*) echo arm-unknown-riscos exit ;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) echo hppa1.1-hitachi-hiuxmpp exit ;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. if test "`(/bin/universe) 2>/dev/null`" = att ; then echo pyramid-pyramid-sysv3 else echo pyramid-pyramid-bsd fi exit ;; NILE*:*:*:dcosx) echo pyramid-pyramid-svr4 exit ;; DRS?6000:unix:4.0:6*) echo sparc-icl-nx6 exit ;; DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) case `/usr/bin/uname -p` in sparc) echo sparc-icl-nx7; exit ;; esac ;; s390x:SunOS:*:*) echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4H:SunOS:5.*:*) echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) echo i386-pc-auroraux${UNAME_RELEASE} exit ;; i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) eval $set_cc_for_build SUN_ARCH="i386" # If there is a compiler, see if it is configured for 64-bit objects. # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. # This test works for both compilers. if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then SUN_ARCH="x86_64" fi fi echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:*:*) case "`/usr/bin/arch -k`" in Series*|S4*) UNAME_RELEASE=`uname -v` ;; esac # Japanese Language versions have a version number like `4.1.3-JL'. echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` exit ;; sun3*:SunOS:*:*) echo m68k-sun-sunos${UNAME_RELEASE} exit ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 case "`/bin/arch`" in sun3) echo m68k-sun-sunos${UNAME_RELEASE} ;; sun4) echo sparc-sun-sunos${UNAME_RELEASE} ;; esac exit ;; aushp:SunOS:*:*) echo sparc-auspex-sunos${UNAME_RELEASE} exit ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor # > m68000). The system name ranges from "MiNT" over "FreeMiNT" # to the lowercase version "mint" (or "freemint"). Finally # the system name "TOS" denotes a system which is actually not # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) echo m68k-milan-mint${UNAME_RELEASE} exit ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) echo m68k-hades-mint${UNAME_RELEASE} exit ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) echo m68k-unknown-mint${UNAME_RELEASE} exit ;; m68k:machten:*:*) echo m68k-apple-machten${UNAME_RELEASE} exit ;; powerpc:machten:*:*) echo powerpc-apple-machten${UNAME_RELEASE} exit ;; RISC*:Mach:*:*) echo mips-dec-mach_bsd4.3 exit ;; RISC*:ULTRIX:*:*) echo mips-dec-ultrix${UNAME_RELEASE} exit ;; VAX*:ULTRIX*:*:*) echo vax-dec-ultrix${UNAME_RELEASE} exit ;; 2020:CLIX:*:* | 2430:CLIX:*:*) echo clipper-intergraph-clix${UNAME_RELEASE} exit ;; mips:*:*:UMIPS | mips:*:*:RISCos) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #ifdef __cplusplus #include /* for printf() prototype */ int main (int argc, char *argv[]) { #else int main (argc, argv) int argc; char *argv[]; { #endif #if defined (host_mips) && defined (MIPSEB) #if defined (SYSTYPE_SYSV) printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_SVR4) printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); #endif #endif exit (-1); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && SYSTEM_NAME=`$dummy $dummyarg` && { echo "$SYSTEM_NAME"; exit; } echo mips-mips-riscos${UNAME_RELEASE} exit ;; Motorola:PowerMAX_OS:*:*) echo powerpc-motorola-powermax exit ;; Motorola:*:4.3:PL8-*) echo powerpc-harris-powermax exit ;; Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) echo powerpc-harris-powermax exit ;; Night_Hawk:Power_UNIX:*:*) echo powerpc-harris-powerunix exit ;; m88k:CX/UX:7*:*) echo m88k-harris-cxux7 exit ;; m88k:*:4*:R4*) echo m88k-motorola-sysv4 exit ;; m88k:*:3*:R3*) echo m88k-motorola-sysv3 exit ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] then if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ [ ${TARGET_BINARY_INTERFACE}x = x ] then echo m88k-dg-dgux${UNAME_RELEASE} else echo m88k-dg-dguxbcs${UNAME_RELEASE} fi else echo i586-dg-dgux${UNAME_RELEASE} fi exit ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) echo m88k-dolphin-sysv3 exit ;; M88*:*:R3*:*) # Delta 88k system running SVR3 echo m88k-motorola-sysv3 exit ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) echo m88k-tektronix-sysv3 exit ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) echo m68k-tektronix-bsd exit ;; *:IRIX*:*:*) echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` exit ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) echo i386-ibm-aix exit ;; ia64:AIX:*:*) if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} exit ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include main() { if (!__power_pc()) exit(1); puts("powerpc-ibm-aix3.2.5"); exit(0); } EOF if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` then echo "$SYSTEM_NAME" else echo rs6000-ibm-aix3.2.5 fi elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then echo rs6000-ibm-aix3.2.4 else echo rs6000-ibm-aix3.2 fi exit ;; *:AIX:*:[4567]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc fi if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${IBM_ARCH}-ibm-aix${IBM_REV} exit ;; *:AIX:*:*) echo rs6000-ibm-aix exit ;; ibmrt:4.4BSD:*|romp-ibm:BSD:*) echo romp-ibm-bsd4.4 exit ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to exit ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) echo rs6000-bull-bosx exit ;; DPX/2?00:B.O.S.:*:*) echo m68k-bull-sysv3 exit ;; 9000/[34]??:4.3bsd:1.*:*) echo m68k-hp-bsd exit ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) echo m68k-hp-bsd4.4 exit ;; 9000/[34678]??:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` case "${UNAME_MACHINE}" in 9000/31? ) HP_ARCH=m68000 ;; 9000/[34]?? ) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) if [ -x /usr/bin/getconf ]; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` case "${sc_cpu_version}" in 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 532) # CPU_PA_RISC2_0 case "${sc_kernel_bits}" in 32) HP_ARCH="hppa2.0n" ;; 64) HP_ARCH="hppa2.0w" ;; '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 esac ;; esac fi if [ "${HP_ARCH}" = "" ]; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #define _HPUX_SOURCE #include #include int main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); #endif long cpu = sysconf (_SC_CPU_VERSION); switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0"); break; case CPU_PA_RISC1_1: puts ("hppa1.1"); break; case CPU_PA_RISC2_0: #if defined(_SC_KERNEL_BITS) switch (bits) { case 64: puts ("hppa2.0w"); break; case 32: puts ("hppa2.0n"); break; default: puts ("hppa2.0"); break; } break; #else /* !defined(_SC_KERNEL_BITS) */ puts ("hppa2.0"); break; #endif default: puts ("hppa1.0"); break; } exit (0); } EOF (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac if [ ${HP_ARCH} = "hppa2.0w" ] then eval $set_cc_for_build # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler # generating 64-bit code. GNU and HP use different nomenclature: # # $ CC_FOR_BUILD=cc ./config.guess # => hppa2.0w-hp-hpux11.23 # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess # => hppa64-hp-hpux11.23 if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | grep -q __LP64__ then HP_ARCH="hppa2.0w" else HP_ARCH="hppa64" fi fi echo ${HP_ARCH}-hp-hpux${HPUX_REV} exit ;; ia64:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` echo ia64-hp-hpux${HPUX_REV} exit ;; 3050*:HI-UX:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include int main () { long cpu = sysconf (_SC_CPU_VERSION); /* The order matters, because CPU_IS_HP_MC68K erroneously returns true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct results, however. */ if (CPU_IS_PA_RISC (cpu)) { switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; default: puts ("hppa-hitachi-hiuxwe2"); break; } } else if (CPU_IS_HP_MC68K (cpu)) puts ("m68k-hitachi-hiuxwe2"); else puts ("unknown-hitachi-hiuxwe2"); exit (0); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && { echo "$SYSTEM_NAME"; exit; } echo unknown-hitachi-hiuxwe2 exit ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) echo hppa1.1-hp-bsd exit ;; 9000/8??:4.3bsd:*:*) echo hppa1.0-hp-bsd exit ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) echo hppa1.0-hp-mpeix exit ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) echo hppa1.1-hp-osf exit ;; hp8??:OSF1:*:*) echo hppa1.0-hp-osf exit ;; i*86:OSF1:*:*) if [ -x /usr/sbin/sysversion ] ; then echo ${UNAME_MACHINE}-unknown-osf1mk else echo ${UNAME_MACHINE}-unknown-osf1 fi exit ;; parisc*:Lites*:*:*) echo hppa1.1-hp-lites exit ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) echo c1-convex-bsd exit ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) echo c34-convex-bsd exit ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) echo c38-convex-bsd exit ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) echo c4-convex-bsd exit ;; CRAY*Y-MP:*:*:*) echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*[A-Z]90:*:*:*) echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' exit ;; CRAY*TS:*:*:*) echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*T3E:*:*:*) echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*SV1:*:*:*) echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; *:UNICOS/mp:*:*) echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; 5000:UNIX_System_V:4.*:*) FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} exit ;; sparc*:BSD/OS:*:*) echo sparc-unknown-bsdi${UNAME_RELEASE} exit ;; *:BSD/OS:*:*) echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} exit ;; *:FreeBSD:*:*) UNAME_PROCESSOR=`/usr/bin/uname -p` case ${UNAME_PROCESSOR} in amd64) echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; *) echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; esac exit ;; i*:CYGWIN*:*) echo ${UNAME_MACHINE}-pc-cygwin exit ;; *:MINGW*:*) echo ${UNAME_MACHINE}-pc-mingw32 exit ;; i*:MSYS*:*) echo ${UNAME_MACHINE}-pc-msys exit ;; i*:windows32*:*) # uname -m includes "-pc" on this system. echo ${UNAME_MACHINE}-mingw32 exit ;; i*:PW*:*) echo ${UNAME_MACHINE}-pc-pw32 exit ;; *:Interix*:*) case ${UNAME_MACHINE} in x86) echo i586-pc-interix${UNAME_RELEASE} exit ;; authenticamd | genuineintel | EM64T) echo x86_64-unknown-interix${UNAME_RELEASE} exit ;; IA64) echo ia64-unknown-interix${UNAME_RELEASE} exit ;; esac ;; [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) echo i${UNAME_MACHINE}-pc-mks exit ;; 8664:Windows_NT:*) echo x86_64-pc-mks exit ;; i*:Windows_NT*:* | Pentium*:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we # UNAME_MACHINE based on the output of uname instead of i386? echo i586-pc-interix exit ;; i*:UWIN*:*) echo ${UNAME_MACHINE}-pc-uwin exit ;; amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) echo x86_64-unknown-cygwin exit ;; p*:CYGWIN*:*) echo powerpcle-unknown-cygwin exit ;; prep*:SunOS:5.*:*) echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; *:GNU:*:*) # the GNU system echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` exit ;; *:GNU/*:*:*) # other systems with GNU libc and userland echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu exit ;; i*86:Minix:*:*) echo ${UNAME_MACHINE}-pc-minix exit ;; aarch64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; aarch64_be:Linux:*:*) UNAME_MACHINE=aarch64_be echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in EV5) UNAME_MACHINE=alphaev5 ;; EV56) UNAME_MACHINE=alphaev56 ;; PCA56) UNAME_MACHINE=alphapca56 ;; PCA57) UNAME_MACHINE=alphapca56 ;; EV6) UNAME_MACHINE=alphaev6 ;; EV67) UNAME_MACHINE=alphaev67 ;; EV68*) UNAME_MACHINE=alphaev68 ;; esac objdump --private-headers /bin/sh | grep -q ld.so.1 if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} exit ;; arm*:Linux:*:*) eval $set_cc_for_build if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_EABI__ then echo ${UNAME_MACHINE}-unknown-linux-gnu else if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then echo ${UNAME_MACHINE}-unknown-linux-gnueabi else echo ${UNAME_MACHINE}-unknown-linux-gnueabihf fi fi exit ;; avr32*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; cris:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-gnu exit ;; crisv32:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-gnu exit ;; frv:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; hexagon:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; i*86:Linux:*:*) LIBC=gnu eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #ifdef __dietlibc__ LIBC=dietlibc #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'` echo "${UNAME_MACHINE}-pc-linux-${LIBC}" exit ;; ia64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; m32r*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; m68*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; mips:Linux:*:* | mips64:Linux:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #undef CPU #undef ${UNAME_MACHINE} #undef ${UNAME_MACHINE}el #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) CPU=${UNAME_MACHINE}el #else #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) CPU=${UNAME_MACHINE} #else CPU= #endif #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } ;; or32:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; padre:Linux:*:*) echo sparc-unknown-linux-gnu exit ;; parisc64:Linux:*:* | hppa64:Linux:*:*) echo hppa64-unknown-linux-gnu exit ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in PA7*) echo hppa1.1-unknown-linux-gnu ;; PA8*) echo hppa2.0-unknown-linux-gnu ;; *) echo hppa-unknown-linux-gnu ;; esac exit ;; ppc64:Linux:*:*) echo powerpc64-unknown-linux-gnu exit ;; ppc:Linux:*:*) echo powerpc-unknown-linux-gnu exit ;; s390:Linux:*:* | s390x:Linux:*:*) echo ${UNAME_MACHINE}-ibm-linux exit ;; sh64*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; sh*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; sparc:Linux:*:* | sparc64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; tile*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; vax:Linux:*:*) echo ${UNAME_MACHINE}-dec-linux-gnu exit ;; x86_64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; xtensa*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. echo i386-sequent-sysv4 exit ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} exit ;; i*86:OS/2:*:*) # If we were able to find `uname', then EMX Unix compatibility # is probably installed. echo ${UNAME_MACHINE}-pc-os2-emx exit ;; i*86:XTS-300:*:STOP) echo ${UNAME_MACHINE}-unknown-stop exit ;; i*86:atheos:*:*) echo ${UNAME_MACHINE}-unknown-atheos exit ;; i*86:syllable:*:*) echo ${UNAME_MACHINE}-pc-syllable exit ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) echo i386-unknown-lynxos${UNAME_RELEASE} exit ;; i*86:*DOS:*:*) echo ${UNAME_MACHINE}-pc-msdosdjgpp exit ;; i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} else echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} fi exit ;; i*86:*:5:[678]*) # UnixWare 7.x, OpenUNIX and OpenServer 6. case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} exit ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ && UNAME_MACHINE=i586 (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ && UNAME_MACHINE=i686 (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 echo ${UNAME_MACHINE}-pc-sco$UNAME_REL else echo ${UNAME_MACHINE}-pc-sysv32 fi exit ;; pc:*:*:*) # Left here for compatibility: # uname -m prints for DJGPP always 'pc', but it prints nothing about # the processor, so we play safe by assuming i586. # Note: whatever this is, it MUST be the same as what config.sub # prints for the "djgpp" host, or else GDB configury will decide that # this is a cross-build. echo i586-pc-msdosdjgpp exit ;; Intel:Mach:3*:*) echo i386-pc-mach3 exit ;; paragon:*:*:*) echo i860-intel-osf1 exit ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 fi exit ;; mini*:CTIX:SYS*5:*) # "miniframe" echo m68010-convergent-sysv exit ;; mc68k:UNIX:SYSTEM5:3.51m) echo m68k-convergent-sysv exit ;; M680?0:D-NIX:5.3:*) echo m68k-diab-dnix exit ;; M68*:*:R3V[5678]*:*) test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4; exit; } ;; NCR*:*:4.2:* | MPRAS*:*:4.2:*) OS_REL='.3' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) echo m68k-unknown-lynxos${UNAME_RELEASE} exit ;; mc68030:UNIX_System_V:4.*:*) echo m68k-atari-sysv4 exit ;; TSUNAMI:LynxOS:2.*:*) echo sparc-unknown-lynxos${UNAME_RELEASE} exit ;; rs6000:LynxOS:2.*:*) echo rs6000-unknown-lynxos${UNAME_RELEASE} exit ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) echo powerpc-unknown-lynxos${UNAME_RELEASE} exit ;; SM[BE]S:UNIX_SV:*:*) echo mips-dde-sysv${UNAME_RELEASE} exit ;; RM*:ReliantUNIX-*:*:*) echo mips-sni-sysv4 exit ;; RM*:SINIX-*:*:*) echo mips-sni-sysv4 exit ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` echo ${UNAME_MACHINE}-sni-sysv4 else echo ns32k-sni-sysv fi exit ;; PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort # says echo i586-unisys-sysv4 exit ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm echo hppa1.1-stratus-sysv4 exit ;; *:*:*:FTX*) # From seanf@swdc.stratus.com. echo i860-stratus-sysv4 exit ;; i*86:VOS:*:*) # From Paul.Green@stratus.com. echo ${UNAME_MACHINE}-stratus-vos exit ;; *:VOS:*:*) # From Paul.Green@stratus.com. echo hppa1.1-stratus-vos exit ;; mc68*:A/UX:*:*) echo m68k-apple-aux${UNAME_RELEASE} exit ;; news*:NEWS-OS:6*:*) echo mips-sony-newsos6 exit ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if [ -d /usr/nec ]; then echo mips-nec-sysv${UNAME_RELEASE} else echo mips-unknown-sysv${UNAME_RELEASE} fi exit ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. echo powerpc-be-beos exit ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. echo powerpc-apple-beos exit ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. echo i586-pc-beos exit ;; BePC:Haiku:*:*) # Haiku running on Intel PC compatible. echo i586-pc-haiku exit ;; SX-4:SUPER-UX:*:*) echo sx4-nec-superux${UNAME_RELEASE} exit ;; SX-5:SUPER-UX:*:*) echo sx5-nec-superux${UNAME_RELEASE} exit ;; SX-6:SUPER-UX:*:*) echo sx6-nec-superux${UNAME_RELEASE} exit ;; SX-7:SUPER-UX:*:*) echo sx7-nec-superux${UNAME_RELEASE} exit ;; SX-8:SUPER-UX:*:*) echo sx8-nec-superux${UNAME_RELEASE} exit ;; SX-8R:SUPER-UX:*:*) echo sx8r-nec-superux${UNAME_RELEASE} exit ;; Power*:Rhapsody:*:*) echo powerpc-apple-rhapsody${UNAME_RELEASE} exit ;; *:Rhapsody:*:*) echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} exit ;; *:Darwin:*:*) UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown case $UNAME_PROCESSOR in i386) eval $set_cc_for_build if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then UNAME_PROCESSOR="x86_64" fi fi ;; unknown) UNAME_PROCESSOR=powerpc ;; esac echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} exit ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) UNAME_PROCESSOR=`uname -p` if test "$UNAME_PROCESSOR" = "x86"; then UNAME_PROCESSOR=i386 UNAME_MACHINE=pc fi echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} exit ;; *:QNX:*:4*) echo i386-pc-qnx exit ;; NEO-?:NONSTOP_KERNEL:*:*) echo neo-tandem-nsk${UNAME_RELEASE} exit ;; NSE-?:NONSTOP_KERNEL:*:*) echo nse-tandem-nsk${UNAME_RELEASE} exit ;; NSR-?:NONSTOP_KERNEL:*:*) echo nsr-tandem-nsk${UNAME_RELEASE} exit ;; *:NonStop-UX:*:*) echo mips-compaq-nonstopux exit ;; BS2000:POSIX*:*:*) echo bs2000-siemens-sysv exit ;; DS/*:UNIX_System_V:*:*) echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} exit ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 # operating systems. if test "$cputype" = "386"; then UNAME_MACHINE=i386 else UNAME_MACHINE="$cputype" fi echo ${UNAME_MACHINE}-unknown-plan9 exit ;; *:TOPS-10:*:*) echo pdp10-unknown-tops10 exit ;; *:TENEX:*:*) echo pdp10-unknown-tenex exit ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) echo pdp10-dec-tops20 exit ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) echo pdp10-xkl-tops20 exit ;; *:TOPS-20:*:*) echo pdp10-unknown-tops20 exit ;; *:ITS:*:*) echo pdp10-unknown-its exit ;; SEI:*:*:SEIUX) echo mips-sei-seiux${UNAME_RELEASE} exit ;; *:DragonFly:*:*) echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit ;; *:*VMS:*:*) UNAME_MACHINE=`(uname -p) 2>/dev/null` case "${UNAME_MACHINE}" in A*) echo alpha-dec-vms ; exit ;; I*) echo ia64-dec-vms ; exit ;; V*) echo vax-dec-vms ; exit ;; esac ;; *:XENIX:*:SysV) echo i386-pc-xenix exit ;; i*86:skyos:*:*) echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' exit ;; i*86:rdos:*:*) echo ${UNAME_MACHINE}-pc-rdos exit ;; i*86:AROS:*:*) echo ${UNAME_MACHINE}-pc-aros exit ;; x86_64:VMkernel:*:*) echo ${UNAME_MACHINE}-unknown-esx exit ;; esac #echo '(No uname command or uname output not recognized.)' 1>&2 #echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 eval $set_cc_for_build cat >$dummy.c < # include #endif main () { #if defined (sony) #if defined (MIPSEB) /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, I don't know.... */ printf ("mips-sony-bsd\n"); exit (0); #else #include printf ("m68k-sony-newsos%s\n", #ifdef NEWSOS4 "4" #else "" #endif ); exit (0); #endif #endif #if defined (__arm) && defined (__acorn) && defined (__unix) printf ("arm-acorn-riscix\n"); exit (0); #endif #if defined (hp300) && !defined (hpux) printf ("m68k-hp-bsd\n"); exit (0); #endif #if defined (NeXT) #if !defined (__ARCHITECTURE__) #define __ARCHITECTURE__ "m68k" #endif int version; version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; if (version < 4) printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); else printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); exit (0); #endif #if defined (MULTIMAX) || defined (n16) #if defined (UMAXV) printf ("ns32k-encore-sysv\n"); exit (0); #else #if defined (CMU) printf ("ns32k-encore-mach\n"); exit (0); #else printf ("ns32k-encore-bsd\n"); exit (0); #endif #endif #endif #if defined (__386BSD__) printf ("i386-pc-bsd\n"); exit (0); #endif #if defined (sequent) #if defined (i386) printf ("i386-sequent-dynix\n"); exit (0); #endif #if defined (ns32000) printf ("ns32k-sequent-dynix\n"); exit (0); #endif #endif #if defined (_SEQUENT_) struct utsname un; uname(&un); if (strncmp(un.version, "V2", 2) == 0) { printf ("i386-sequent-ptx2\n"); exit (0); } if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ printf ("i386-sequent-ptx1\n"); exit (0); } printf ("i386-sequent-ptx\n"); exit (0); #endif #if defined (vax) # if !defined (ultrix) # include # if defined (BSD) # if BSD == 43 printf ("vax-dec-bsd4.3\n"); exit (0); # else # if BSD == 199006 printf ("vax-dec-bsd4.3reno\n"); exit (0); # else printf ("vax-dec-bsd\n"); exit (0); # endif # endif # else printf ("vax-dec-bsd\n"); exit (0); # endif # else printf ("vax-dec-ultrix\n"); exit (0); # endif #endif #if defined (alliant) && defined (i860) printf ("i860-alliant-bsd\n"); exit (0); #endif exit (1); } EOF $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && { echo "$SYSTEM_NAME"; exit; } # Apollos put the system type in the environment. test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } # Convex versions that predate uname can use getsysinfo(1) if [ -x /usr/convex/getsysinfo ] then case `getsysinfo -f cpu_type` in c1*) echo c1-convex-bsd exit ;; c2*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; c34*) echo c34-convex-bsd exit ;; c38*) echo c38-convex-bsd exit ;; c4*) echo c4-convex-bsd exit ;; esac fi cat >&2 < in order to provide the needed information to handle your system. config.guess timestamp = $timestamp uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` /bin/uname -X = `(/bin/uname -X) 2>/dev/null` hostinfo = `(hostinfo) 2>/dev/null` /bin/universe = `(/bin/universe) 2>/dev/null` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` /bin/arch = `(/bin/arch) 2>/dev/null` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` UNAME_MACHINE = ${UNAME_MACHINE} UNAME_RELEASE = ${UNAME_RELEASE} UNAME_SYSTEM = ${UNAME_SYSTEM} UNAME_VERSION = ${UNAME_VERSION} EOF exit 1 # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: sauerbraten-0.0.20130203.dfsg/enet/m4/0000755000175000017500000000000012100771037016646 5ustar vincentvincentsauerbraten-0.0.20130203.dfsg/enet/m4/.keep0000644000175000017500000000000011373036002017556 0ustar vincentvincentsauerbraten-0.0.20130203.dfsg/enet/m4/ltsugar.m40000644000175000017500000001042411373267550020605 0ustar vincentvincent# ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*- # # Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc. # Written by Gary V. Vaughan, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 6 ltsugar.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])]) # lt_join(SEP, ARG1, [ARG2...]) # ----------------------------- # Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their # associated separator. # Needed until we can rely on m4_join from Autoconf 2.62, since all earlier # versions in m4sugar had bugs. m4_define([lt_join], [m4_if([$#], [1], [], [$#], [2], [[$2]], [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])]) m4_define([_lt_join], [m4_if([$#$2], [2], [], [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])]) # lt_car(LIST) # lt_cdr(LIST) # ------------ # Manipulate m4 lists. # These macros are necessary as long as will still need to support # Autoconf-2.59 which quotes differently. m4_define([lt_car], [[$1]]) m4_define([lt_cdr], [m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])], [$#], 1, [], [m4_dquote(m4_shift($@))])]) m4_define([lt_unquote], $1) # lt_append(MACRO-NAME, STRING, [SEPARATOR]) # ------------------------------------------ # Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'. # Note that neither SEPARATOR nor STRING are expanded; they are appended # to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked). # No SEPARATOR is output if MACRO-NAME was previously undefined (different # than defined and empty). # # This macro is needed until we can rely on Autoconf 2.62, since earlier # versions of m4sugar mistakenly expanded SEPARATOR but not STRING. m4_define([lt_append], [m4_define([$1], m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])]) # lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...]) # ---------------------------------------------------------- # Produce a SEP delimited list of all paired combinations of elements of # PREFIX-LIST with SUFFIX1 through SUFFIXn. Each element of the list # has the form PREFIXmINFIXSUFFIXn. # Needed until we can rely on m4_combine added in Autoconf 2.62. m4_define([lt_combine], [m4_if(m4_eval([$# > 3]), [1], [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl [[m4_foreach([_Lt_prefix], [$2], [m4_foreach([_Lt_suffix], ]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[, [_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])]) # lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ]) # ----------------------------------------------------------------------- # Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited # by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ. m4_define([lt_if_append_uniq], [m4_ifdef([$1], [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1], [lt_append([$1], [$2], [$3])$4], [$5])], [lt_append([$1], [$2], [$3])$4])]) # lt_dict_add(DICT, KEY, VALUE) # ----------------------------- m4_define([lt_dict_add], [m4_define([$1($2)], [$3])]) # lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE) # -------------------------------------------- m4_define([lt_dict_add_subkey], [m4_define([$1($2:$3)], [$4])]) # lt_dict_fetch(DICT, KEY, [SUBKEY]) # ---------------------------------- m4_define([lt_dict_fetch], [m4_ifval([$3], m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]), m4_ifdef([$1($2)], [m4_defn([$1($2)])]))]) # lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE]) # ----------------------------------------------------------------- m4_define([lt_if_dict_fetch], [m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4], [$5], [$6])]) # lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...]) # -------------------------------------------------------------- m4_define([lt_dict_filter], [m4_if([$5], [], [], [lt_join(m4_quote(m4_default([$4], [[, ]])), lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]), [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl ]) sauerbraten-0.0.20130203.dfsg/enet/m4/ltversion.m40000644000175000017500000000126211665001547021145 0ustar vincentvincent# ltversion.m4 -- version numbers -*- Autoconf -*- # # Copyright (C) 2004 Free Software Foundation, Inc. # Written by Scott James Remnant, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # @configure_input@ # serial 3337 ltversion.m4 # This file is part of GNU Libtool m4_define([LT_PACKAGE_VERSION], [2.4.2]) m4_define([LT_PACKAGE_REVISION], [1.3337]) AC_DEFUN([LTVERSION_VERSION], [macro_version='2.4.2' macro_revision='1.3337' _LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?]) _LT_DECL(, macro_revision, 0) ]) sauerbraten-0.0.20130203.dfsg/enet/m4/ltoptions.m40000644000175000017500000003007311665001547021155 0ustar vincentvincent# Helper functions for option handling. -*- Autoconf -*- # # Copyright (C) 2004, 2005, 2007, 2008, 2009 Free Software Foundation, # Inc. # Written by Gary V. Vaughan, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 7 ltoptions.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])]) # _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME) # ------------------------------------------ m4_define([_LT_MANGLE_OPTION], [[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])]) # _LT_SET_OPTION(MACRO-NAME, OPTION-NAME) # --------------------------------------- # Set option OPTION-NAME for macro MACRO-NAME, and if there is a # matching handler defined, dispatch to it. Other OPTION-NAMEs are # saved as a flag. m4_define([_LT_SET_OPTION], [m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]), _LT_MANGLE_DEFUN([$1], [$2]), [m4_warning([Unknown $1 option `$2'])])[]dnl ]) # _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET]) # ------------------------------------------------------------ # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. m4_define([_LT_IF_OPTION], [m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])]) # _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET) # ------------------------------------------------------- # Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME # are set. m4_define([_LT_UNLESS_OPTIONS], [m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option), [m4_define([$0_found])])])[]dnl m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3 ])[]dnl ]) # _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST) # ---------------------------------------- # OPTION-LIST is a space-separated list of Libtool options associated # with MACRO-NAME. If any OPTION has a matching handler declared with # LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about # the unknown option and exit. m4_defun([_LT_SET_OPTIONS], [# Set options m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), [_LT_SET_OPTION([$1], _LT_Option)]) m4_if([$1],[LT_INIT],[ dnl dnl Simply set some default values (i.e off) if boolean options were not dnl specified: _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no ]) _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no ]) dnl dnl If no reference was made to various pairs of opposing options, then dnl we run the default mode handler for the pair. For example, if neither dnl `shared' nor `disable-shared' was passed, we enable building of shared dnl archives by default: _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED]) _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC]) _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC]) _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install], [_LT_ENABLE_FAST_INSTALL]) ]) ])# _LT_SET_OPTIONS ## --------------------------------- ## ## Macros to handle LT_INIT options. ## ## --------------------------------- ## # _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME) # ----------------------------------------- m4_define([_LT_MANGLE_DEFUN], [[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])]) # LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE) # ----------------------------------------------- m4_define([LT_OPTION_DEFINE], [m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl ])# LT_OPTION_DEFINE # dlopen # ------ LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes ]) AU_DEFUN([AC_LIBTOOL_DLOPEN], [_LT_SET_OPTION([LT_INIT], [dlopen]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `dlopen' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], []) # win32-dll # --------- # Declare package support for building win32 dll's. LT_OPTION_DEFINE([LT_INIT], [win32-dll], [enable_win32_dll=yes case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*) AC_CHECK_TOOL(AS, as, false) AC_CHECK_TOOL(DLLTOOL, dlltool, false) AC_CHECK_TOOL(OBJDUMP, objdump, false) ;; esac test -z "$AS" && AS=as _LT_DECL([], [AS], [1], [Assembler program])dnl test -z "$DLLTOOL" && DLLTOOL=dlltool _LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl test -z "$OBJDUMP" && OBJDUMP=objdump _LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl ])# win32-dll AU_DEFUN([AC_LIBTOOL_WIN32_DLL], [AC_REQUIRE([AC_CANONICAL_HOST])dnl _LT_SET_OPTION([LT_INIT], [win32-dll]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `win32-dll' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], []) # _LT_ENABLE_SHARED([DEFAULT]) # ---------------------------- # implement the --enable-shared flag, and supports the `shared' and # `disable-shared' LT_INIT options. # DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. m4_define([_LT_ENABLE_SHARED], [m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([shared], [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@], [build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_shared=yes ;; no) enable_shared=no ;; *) enable_shared=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_shared=yes fi done IFS="$lt_save_ifs" ;; esac], [enable_shared=]_LT_ENABLE_SHARED_DEFAULT) _LT_DECL([build_libtool_libs], [enable_shared], [0], [Whether or not to build shared libraries]) ])# _LT_ENABLE_SHARED LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])]) # Old names: AC_DEFUN([AC_ENABLE_SHARED], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared]) ]) AC_DEFUN([AC_DISABLE_SHARED], [_LT_SET_OPTION([LT_INIT], [disable-shared]) ]) AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)]) AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_ENABLE_SHARED], []) dnl AC_DEFUN([AM_DISABLE_SHARED], []) # _LT_ENABLE_STATIC([DEFAULT]) # ---------------------------- # implement the --enable-static flag, and support the `static' and # `disable-static' LT_INIT options. # DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. m4_define([_LT_ENABLE_STATIC], [m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([static], [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@], [build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_static=yes ;; no) enable_static=no ;; *) enable_static=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_static=yes fi done IFS="$lt_save_ifs" ;; esac], [enable_static=]_LT_ENABLE_STATIC_DEFAULT) _LT_DECL([build_old_libs], [enable_static], [0], [Whether or not to build static libraries]) ])# _LT_ENABLE_STATIC LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])]) # Old names: AC_DEFUN([AC_ENABLE_STATIC], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static]) ]) AC_DEFUN([AC_DISABLE_STATIC], [_LT_SET_OPTION([LT_INIT], [disable-static]) ]) AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)]) AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_ENABLE_STATIC], []) dnl AC_DEFUN([AM_DISABLE_STATIC], []) # _LT_ENABLE_FAST_INSTALL([DEFAULT]) # ---------------------------------- # implement the --enable-fast-install flag, and support the `fast-install' # and `disable-fast-install' LT_INIT options. # DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. m4_define([_LT_ENABLE_FAST_INSTALL], [m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([fast-install], [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@], [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_fast_install=yes ;; no) enable_fast_install=no ;; *) enable_fast_install=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_fast_install=yes fi done IFS="$lt_save_ifs" ;; esac], [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT) _LT_DECL([fast_install], [enable_fast_install], [0], [Whether or not to optimize for fast installation])dnl ])# _LT_ENABLE_FAST_INSTALL LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])]) # Old names: AU_DEFUN([AC_ENABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `fast-install' option into LT_INIT's first parameter.]) ]) AU_DEFUN([AC_DISABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], [disable-fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `disable-fast-install' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], []) dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], []) # _LT_WITH_PIC([MODE]) # -------------------- # implement the --with-pic flag, and support the `pic-only' and `no-pic' # LT_INIT options. # MODE is either `yes' or `no'. If omitted, it defaults to `both'. m4_define([_LT_WITH_PIC], [AC_ARG_WITH([pic], [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@], [try to use only PIC/non-PIC objects @<:@default=use both@:>@])], [lt_p=${PACKAGE-default} case $withval in yes|no) pic_mode=$withval ;; *) pic_mode=default # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for lt_pkg in $withval; do IFS="$lt_save_ifs" if test "X$lt_pkg" = "X$lt_p"; then pic_mode=yes fi done IFS="$lt_save_ifs" ;; esac], [pic_mode=default]) test -z "$pic_mode" && pic_mode=m4_default([$1], [default]) _LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl ])# _LT_WITH_PIC LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])]) LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])]) # Old name: AU_DEFUN([AC_LIBTOOL_PICMODE], [_LT_SET_OPTION([LT_INIT], [pic-only]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `pic-only' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_PICMODE], []) ## ----------------- ## ## LTDL_INIT Options ## ## ----------------- ## m4_define([_LTDL_MODE], []) LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive], [m4_define([_LTDL_MODE], [nonrecursive])]) LT_OPTION_DEFINE([LTDL_INIT], [recursive], [m4_define([_LTDL_MODE], [recursive])]) LT_OPTION_DEFINE([LTDL_INIT], [subproject], [m4_define([_LTDL_MODE], [subproject])]) m4_define([_LTDL_TYPE], []) LT_OPTION_DEFINE([LTDL_INIT], [installable], [m4_define([_LTDL_TYPE], [installable])]) LT_OPTION_DEFINE([LTDL_INIT], [convenience], [m4_define([_LTDL_TYPE], [convenience])]) sauerbraten-0.0.20130203.dfsg/enet/m4/lt~obsolete.m40000644000175000017500000001375611665001547021505 0ustar vincentvincent# lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*- # # Copyright (C) 2004, 2005, 2007, 2009 Free Software Foundation, Inc. # Written by Scott James Remnant, 2004. # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 5 lt~obsolete.m4 # These exist entirely to fool aclocal when bootstrapping libtool. # # In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN) # which have later been changed to m4_define as they aren't part of the # exported API, or moved to Autoconf or Automake where they belong. # # The trouble is, aclocal is a bit thick. It'll see the old AC_DEFUN # in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us # using a macro with the same name in our local m4/libtool.m4 it'll # pull the old libtool.m4 in (it doesn't see our shiny new m4_define # and doesn't know about Autoconf macros at all.) # # So we provide this file, which has a silly filename so it's always # included after everything else. This provides aclocal with the # AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything # because those macros already exist, or will be overwritten later. # We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. # # Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here. # Yes, that means every name once taken will need to remain here until # we give up compatibility with versions before 1.7, at which point # we need to keep only those names which we still refer to. # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])]) m4_ifndef([AC_LIBTOOL_LINKER_OPTION], [AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])]) m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP])]) m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])]) m4_ifndef([_LT_AC_SHELL_INIT], [AC_DEFUN([_LT_AC_SHELL_INIT])]) m4_ifndef([_LT_AC_SYS_LIBPATH_AIX], [AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])]) m4_ifndef([_LT_PROG_LTMAIN], [AC_DEFUN([_LT_PROG_LTMAIN])]) m4_ifndef([_LT_AC_TAGVAR], [AC_DEFUN([_LT_AC_TAGVAR])]) m4_ifndef([AC_LTDL_ENABLE_INSTALL], [AC_DEFUN([AC_LTDL_ENABLE_INSTALL])]) m4_ifndef([AC_LTDL_PREOPEN], [AC_DEFUN([AC_LTDL_PREOPEN])]) m4_ifndef([_LT_AC_SYS_COMPILER], [AC_DEFUN([_LT_AC_SYS_COMPILER])]) m4_ifndef([_LT_AC_LOCK], [AC_DEFUN([_LT_AC_LOCK])]) m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE], [AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])]) m4_ifndef([_LT_AC_TRY_DLOPEN_SELF], [AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])]) m4_ifndef([AC_LIBTOOL_PROG_CC_C_O], [AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])]) m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])]) m4_ifndef([AC_LIBTOOL_OBJDIR], [AC_DEFUN([AC_LIBTOOL_OBJDIR])]) m4_ifndef([AC_LTDL_OBJDIR], [AC_DEFUN([AC_LTDL_OBJDIR])]) m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])]) m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP], [AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])]) m4_ifndef([AC_PATH_MAGIC], [AC_DEFUN([AC_PATH_MAGIC])]) m4_ifndef([AC_PROG_LD_GNU], [AC_DEFUN([AC_PROG_LD_GNU])]) m4_ifndef([AC_PROG_LD_RELOAD_FLAG], [AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])]) m4_ifndef([AC_DEPLIBS_CHECK_METHOD], [AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])]) m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])]) m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])]) m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])]) m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS], [AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])]) m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP], [AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])]) m4_ifndef([LT_AC_PROG_EGREP], [AC_DEFUN([LT_AC_PROG_EGREP])]) m4_ifndef([LT_AC_PROG_SED], [AC_DEFUN([LT_AC_PROG_SED])]) m4_ifndef([_LT_CC_BASENAME], [AC_DEFUN([_LT_CC_BASENAME])]) m4_ifndef([_LT_COMPILER_BOILERPLATE], [AC_DEFUN([_LT_COMPILER_BOILERPLATE])]) m4_ifndef([_LT_LINKER_BOILERPLATE], [AC_DEFUN([_LT_LINKER_BOILERPLATE])]) m4_ifndef([_AC_PROG_LIBTOOL], [AC_DEFUN([_AC_PROG_LIBTOOL])]) m4_ifndef([AC_LIBTOOL_SETUP], [AC_DEFUN([AC_LIBTOOL_SETUP])]) m4_ifndef([_LT_AC_CHECK_DLFCN], [AC_DEFUN([_LT_AC_CHECK_DLFCN])]) m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER], [AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])]) m4_ifndef([_LT_AC_TAGCONFIG], [AC_DEFUN([_LT_AC_TAGCONFIG])]) m4_ifndef([AC_DISABLE_FAST_INSTALL], [AC_DEFUN([AC_DISABLE_FAST_INSTALL])]) m4_ifndef([_LT_AC_LANG_CXX], [AC_DEFUN([_LT_AC_LANG_CXX])]) m4_ifndef([_LT_AC_LANG_F77], [AC_DEFUN([_LT_AC_LANG_F77])]) m4_ifndef([_LT_AC_LANG_GCJ], [AC_DEFUN([_LT_AC_LANG_GCJ])]) m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])]) m4_ifndef([_LT_AC_LANG_C_CONFIG], [AC_DEFUN([_LT_AC_LANG_C_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])]) m4_ifndef([_LT_AC_LANG_CXX_CONFIG], [AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])]) m4_ifndef([_LT_AC_LANG_F77_CONFIG], [AC_DEFUN([_LT_AC_LANG_F77_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])]) m4_ifndef([_LT_AC_LANG_GCJ_CONFIG], [AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])]) m4_ifndef([_LT_AC_LANG_RC_CONFIG], [AC_DEFUN([_LT_AC_LANG_RC_CONFIG])]) m4_ifndef([AC_LIBTOOL_CONFIG], [AC_DEFUN([AC_LIBTOOL_CONFIG])]) m4_ifndef([_LT_AC_FILE_LTDLL_C], [AC_DEFUN([_LT_AC_FILE_LTDLL_C])]) m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS], [AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])]) m4_ifndef([_LT_AC_PROG_CXXCPP], [AC_DEFUN([_LT_AC_PROG_CXXCPP])]) m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS], [AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])]) m4_ifndef([_LT_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])]) m4_ifndef([_LT_PROG_F77], [AC_DEFUN([_LT_PROG_F77])]) m4_ifndef([_LT_PROG_FC], [AC_DEFUN([_LT_PROG_FC])]) m4_ifndef([_LT_PROG_CXX], [AC_DEFUN([_LT_PROG_CXX])]) sauerbraten-0.0.20130203.dfsg/enet/m4/libtool.m40000644000175000017500000105754212006035707020574 0ustar vincentvincent# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*- # # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. m4_define([_LT_COPYING], [dnl # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is part of GNU Libtool. # # GNU Libtool is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, or # obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ]) # serial 57 LT_INIT # LT_PREREQ(VERSION) # ------------------ # Complain and exit if this libtool version is less that VERSION. m4_defun([LT_PREREQ], [m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1, [m4_default([$3], [m4_fatal([Libtool version $1 or higher is required], 63)])], [$2])]) # _LT_CHECK_BUILDDIR # ------------------ # Complain if the absolute build directory name contains unusual characters m4_defun([_LT_CHECK_BUILDDIR], [case `pwd` in *\ * | *\ *) AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;; esac ]) # LT_INIT([OPTIONS]) # ------------------ AC_DEFUN([LT_INIT], [AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl AC_BEFORE([$0], [LT_LANG])dnl AC_BEFORE([$0], [LT_OUTPUT])dnl AC_BEFORE([$0], [LTDL_INIT])dnl m4_require([_LT_CHECK_BUILDDIR])dnl dnl Autoconf doesn't catch unexpanded LT_ macros by default: m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4 dnl unless we require an AC_DEFUNed macro: AC_REQUIRE([LTOPTIONS_VERSION])dnl AC_REQUIRE([LTSUGAR_VERSION])dnl AC_REQUIRE([LTVERSION_VERSION])dnl AC_REQUIRE([LTOBSOLETE_VERSION])dnl m4_require([_LT_PROG_LTMAIN])dnl _LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}]) dnl Parse OPTIONS _LT_SET_OPTIONS([$0], [$1]) # This can be used to rebuild libtool when needed LIBTOOL_DEPS="$ltmain" # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' AC_SUBST(LIBTOOL)dnl _LT_SETUP # Only expand once: m4_define([LT_INIT]) ])# LT_INIT # Old names: AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT]) AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_PROG_LIBTOOL], []) dnl AC_DEFUN([AM_PROG_LIBTOOL], []) # _LT_CC_BASENAME(CC) # ------------------- # Calculate cc_basename. Skip known compiler wrappers and cross-prefix. m4_defun([_LT_CC_BASENAME], [for cc_temp in $1""; do case $cc_temp in compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;; distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;; \-*) ;; *) break;; esac done cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` ]) # _LT_FILEUTILS_DEFAULTS # ---------------------- # It is okay to use these file commands and assume they have been set # sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'. m4_defun([_LT_FILEUTILS_DEFAULTS], [: ${CP="cp -f"} : ${MV="mv -f"} : ${RM="rm -f"} ])# _LT_FILEUTILS_DEFAULTS # _LT_SETUP # --------- m4_defun([_LT_SETUP], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl AC_REQUIRE([_LT_PREPARE_SED_QUOTE_VARS])dnl AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl _LT_DECL([], [PATH_SEPARATOR], [1], [The PATH separator for the build system])dnl dnl _LT_DECL([], [host_alias], [0], [The host system])dnl _LT_DECL([], [host], [0])dnl _LT_DECL([], [host_os], [0])dnl dnl _LT_DECL([], [build_alias], [0], [The build system])dnl _LT_DECL([], [build], [0])dnl _LT_DECL([], [build_os], [0])dnl dnl AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([LT_PATH_LD])dnl AC_REQUIRE([LT_PATH_NM])dnl dnl AC_REQUIRE([AC_PROG_LN_S])dnl test -z "$LN_S" && LN_S="ln -s" _LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl dnl AC_REQUIRE([LT_CMD_MAX_LEN])dnl _LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl _LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_CHECK_SHELL_FEATURES])dnl m4_require([_LT_PATH_CONVERSION_FUNCTIONS])dnl m4_require([_LT_CMD_RELOAD])dnl m4_require([_LT_CHECK_MAGIC_METHOD])dnl m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl m4_require([_LT_CMD_OLD_ARCHIVE])dnl m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl m4_require([_LT_WITH_SYSROOT])dnl _LT_CONFIG_LIBTOOL_INIT([ # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes INIT. if test -n "\${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi ]) if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi _LT_CHECK_OBJDIR m4_require([_LT_TAG_COMPILER])dnl case $host_os in aix3*) # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi ;; esac # Global variables: ofile=libtool can_build_shared=yes # All known linkers require a `.a' archive for static linking (except MSVC, # which needs '.lib'). libext=a with_gnu_ld="$lt_cv_prog_gnu_ld" old_CC="$CC" old_CFLAGS="$CFLAGS" # Set sane defaults for various variables test -z "$CC" && CC=cc test -z "$LTCC" && LTCC=$CC test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS test -z "$LD" && LD=ld test -z "$ac_objext" && ac_objext=o _LT_CC_BASENAME([$compiler]) # Only perform the check for file, if the check method requires it test -z "$MAGIC_CMD" && MAGIC_CMD=file case $deplibs_check_method in file_magic*) if test "$file_magic_cmd" = '$MAGIC_CMD'; then _LT_PATH_MAGIC fi ;; esac # Use C for the default configuration in the libtool script LT_SUPPORTED_TAG([CC]) _LT_LANG_C_CONFIG _LT_LANG_DEFAULT_CONFIG _LT_CONFIG_COMMANDS ])# _LT_SETUP # _LT_PREPARE_SED_QUOTE_VARS # -------------------------- # Define a few sed substitution that help us do robust quoting. m4_defun([_LT_PREPARE_SED_QUOTE_VARS], [# Backslashify metacharacters that are still active within # double-quoted strings. sed_quote_subst='s/\([["`$\\]]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\([["`\\]]\)/\\\1/g' # Sed substitution to delay expansion of an escaped shell variable in a # double_quote_subst'ed string. delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' # Sed substitution to delay expansion of an escaped single quote. delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' # Sed substitution to avoid accidental globbing in evaled expressions no_glob_subst='s/\*/\\\*/g' ]) # _LT_PROG_LTMAIN # --------------- # Note that this code is called both from `configure', and `config.status' # now that we use AC_CONFIG_COMMANDS to generate libtool. Notably, # `config.status' has no value for ac_aux_dir unless we are using Automake, # so we pass a copy along to make sure it has a sensible value anyway. m4_defun([_LT_PROG_LTMAIN], [m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl _LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir']) ltmain="$ac_aux_dir/ltmain.sh" ])# _LT_PROG_LTMAIN ## ------------------------------------- ## ## Accumulate code for creating libtool. ## ## ------------------------------------- ## # So that we can recreate a full libtool script including additional # tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS # in macros and then make a single call at the end using the `libtool' # label. # _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS]) # ---------------------------------------- # Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later. m4_define([_LT_CONFIG_LIBTOOL_INIT], [m4_ifval([$1], [m4_append([_LT_OUTPUT_LIBTOOL_INIT], [$1 ])])]) # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_INIT]) # _LT_CONFIG_LIBTOOL([COMMANDS]) # ------------------------------ # Register COMMANDS to be passed to AC_CONFIG_COMMANDS later. m4_define([_LT_CONFIG_LIBTOOL], [m4_ifval([$1], [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS], [$1 ])])]) # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS]) # _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS]) # ----------------------------------------------------- m4_defun([_LT_CONFIG_SAVE_COMMANDS], [_LT_CONFIG_LIBTOOL([$1]) _LT_CONFIG_LIBTOOL_INIT([$2]) ]) # _LT_FORMAT_COMMENT([COMMENT]) # ----------------------------- # Add leading comment marks to the start of each line, and a trailing # full-stop to the whole comment if one is not present already. m4_define([_LT_FORMAT_COMMENT], [m4_ifval([$1], [ m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])], [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.]) )]) ## ------------------------ ## ## FIXME: Eliminate VARNAME ## ## ------------------------ ## # _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?]) # ------------------------------------------------------------------- # CONFIGNAME is the name given to the value in the libtool script. # VARNAME is the (base) name used in the configure script. # VALUE may be 0, 1 or 2 for a computed quote escaped value based on # VARNAME. Any other value will be used directly. m4_define([_LT_DECL], [lt_if_append_uniq([lt_decl_varnames], [$2], [, ], [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name], [m4_ifval([$1], [$1], [$2])]) lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3]) m4_ifval([$4], [lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])]) lt_dict_add_subkey([lt_decl_dict], [$2], [tagged?], [m4_ifval([$5], [yes], [no])])]) ]) # _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION]) # -------------------------------------------------------- m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])]) # lt_decl_tag_varnames([SEPARATOR], [VARNAME1...]) # ------------------------------------------------ m4_define([lt_decl_tag_varnames], [_lt_decl_filter([tagged?], [yes], $@)]) # _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..]) # --------------------------------------------------------- m4_define([_lt_decl_filter], [m4_case([$#], [0], [m4_fatal([$0: too few arguments: $#])], [1], [m4_fatal([$0: too few arguments: $#: $1])], [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)], [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)], [lt_dict_filter([lt_decl_dict], $@)])[]dnl ]) # lt_decl_quote_varnames([SEPARATOR], [VARNAME1...]) # -------------------------------------------------- m4_define([lt_decl_quote_varnames], [_lt_decl_filter([value], [1], $@)]) # lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...]) # --------------------------------------------------- m4_define([lt_decl_dquote_varnames], [_lt_decl_filter([value], [2], $@)]) # lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...]) # --------------------------------------------------- m4_define([lt_decl_varnames_tagged], [m4_assert([$# <= 2])dnl _$0(m4_quote(m4_default([$1], [[, ]])), m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]), m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))]) m4_define([_lt_decl_varnames_tagged], [m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])]) # lt_decl_all_varnames([SEPARATOR], [VARNAME1...]) # ------------------------------------------------ m4_define([lt_decl_all_varnames], [_$0(m4_quote(m4_default([$1], [[, ]])), m4_if([$2], [], m4_quote(lt_decl_varnames), m4_quote(m4_shift($@))))[]dnl ]) m4_define([_lt_decl_all_varnames], [lt_join($@, lt_decl_varnames_tagged([$1], lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl ]) # _LT_CONFIG_STATUS_DECLARE([VARNAME]) # ------------------------------------ # Quote a variable value, and forward it to `config.status' so that its # declaration there will have the same value as in `configure'. VARNAME # must have a single quote delimited value for this to work. m4_define([_LT_CONFIG_STATUS_DECLARE], [$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`']) # _LT_CONFIG_STATUS_DECLARATIONS # ------------------------------ # We delimit libtool config variables with single quotes, so when # we write them to config.status, we have to be sure to quote all # embedded single quotes properly. In configure, this macro expands # each variable declared with _LT_DECL (and _LT_TAGDECL) into: # # ='`$ECHO "$" | $SED "$delay_single_quote_subst"`' m4_defun([_LT_CONFIG_STATUS_DECLARATIONS], [m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames), [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])]) # _LT_LIBTOOL_TAGS # ---------------- # Output comment and list of tags supported by the script m4_defun([_LT_LIBTOOL_TAGS], [_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl available_tags="_LT_TAGS"dnl ]) # _LT_LIBTOOL_DECLARE(VARNAME, [TAG]) # ----------------------------------- # Extract the dictionary values for VARNAME (optionally with TAG) and # expand to a commented shell variable setting: # # # Some comment about what VAR is for. # visible_name=$lt_internal_name m4_define([_LT_LIBTOOL_DECLARE], [_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [description])))[]dnl m4_pushdef([_libtool_name], m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])), [0], [_libtool_name=[$]$1], [1], [_libtool_name=$lt_[]$1], [2], [_libtool_name=$lt_[]$1], [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl ]) # _LT_LIBTOOL_CONFIG_VARS # ----------------------- # Produce commented declarations of non-tagged libtool config variables # suitable for insertion in the LIBTOOL CONFIG section of the `libtool' # script. Tagged libtool config variables (even for the LIBTOOL CONFIG # section) are produced by _LT_LIBTOOL_TAG_VARS. m4_defun([_LT_LIBTOOL_CONFIG_VARS], [m4_foreach([_lt_var], m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)), [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])]) # _LT_LIBTOOL_TAG_VARS(TAG) # ------------------------- m4_define([_LT_LIBTOOL_TAG_VARS], [m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames), [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])]) # _LT_TAGVAR(VARNAME, [TAGNAME]) # ------------------------------ m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])]) # _LT_CONFIG_COMMANDS # ------------------- # Send accumulated output to $CONFIG_STATUS. Thanks to the lists of # variables for single and double quote escaping we saved from calls # to _LT_DECL, we can put quote escaped variables declarations # into `config.status', and then the shell code to quote escape them in # for loops in `config.status'. Finally, any additional code accumulated # from calls to _LT_CONFIG_LIBTOOL_INIT is expanded. m4_defun([_LT_CONFIG_COMMANDS], [AC_PROVIDE_IFELSE([LT_OUTPUT], dnl If the libtool generation code has been placed in $CONFIG_LT, dnl instead of duplicating it all over again into config.status, dnl then we will have config.status run $CONFIG_LT later, so it dnl needs to know what name is stored there: [AC_CONFIG_COMMANDS([libtool], [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])], dnl If the libtool generation code is destined for config.status, dnl expand the accumulated commands and init code now: [AC_CONFIG_COMMANDS([libtool], [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])]) ])#_LT_CONFIG_COMMANDS # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT], [ # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH sed_quote_subst='$sed_quote_subst' double_quote_subst='$double_quote_subst' delay_variable_subst='$delay_variable_subst' _LT_CONFIG_STATUS_DECLARATIONS LTCC='$LTCC' LTCFLAGS='$LTCFLAGS' compiler='$compiler_DEFAULT' # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$[]1 _LTECHO_EOF' } # Quote evaled strings. for var in lt_decl_all_varnames([[ \ ]], lt_decl_quote_varnames); do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[[\\\\\\\`\\"\\\$]]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done # Double-quote double-evaled strings. for var in lt_decl_all_varnames([[ \ ]], lt_decl_dquote_varnames); do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[[\\\\\\\`\\"\\\$]]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done _LT_OUTPUT_LIBTOOL_INIT ]) # _LT_GENERATED_FILE_INIT(FILE, [COMMENT]) # ------------------------------------ # Generate a child script FILE with all initialization necessary to # reuse the environment learned by the parent script, and make the # file executable. If COMMENT is supplied, it is inserted after the # `#!' sequence but before initialization text begins. After this # macro, additional text can be appended to FILE to form the body of # the child script. The macro ends with non-zero status if the # file could not be fully written (such as if the disk is full). m4_ifdef([AS_INIT_GENERATED], [m4_defun([_LT_GENERATED_FILE_INIT],[AS_INIT_GENERATED($@)])], [m4_defun([_LT_GENERATED_FILE_INIT], [m4_require([AS_PREPARE])]dnl [m4_pushdef([AS_MESSAGE_LOG_FD])]dnl [lt_write_fail=0 cat >$1 <<_ASEOF || lt_write_fail=1 #! $SHELL # Generated by $as_me. $2 SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$1 <<\_ASEOF || lt_write_fail=1 AS_SHELL_SANITIZE _AS_PREPARE exec AS_MESSAGE_FD>&1 _ASEOF test $lt_write_fail = 0 && chmod +x $1[]dnl m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT # LT_OUTPUT # --------- # This macro allows early generation of the libtool script (before # AC_OUTPUT is called), incase it is used in configure for compilation # tests. AC_DEFUN([LT_OUTPUT], [: ${CONFIG_LT=./config.lt} AC_MSG_NOTICE([creating $CONFIG_LT]) _LT_GENERATED_FILE_INIT(["$CONFIG_LT"], [# Run this file to recreate a libtool stub with the current configuration.]) cat >>"$CONFIG_LT" <<\_LTEOF lt_cl_silent=false exec AS_MESSAGE_LOG_FD>>config.log { echo AS_BOX([Running $as_me.]) } >&AS_MESSAGE_LOG_FD lt_cl_help="\ \`$as_me' creates a local libtool stub from the current configuration, for use in further configure time tests before the real libtool is generated. Usage: $[0] [[OPTIONS]] -h, --help print this help, then exit -V, --version print version number, then exit -q, --quiet do not print progress messages -d, --debug don't remove temporary files Report bugs to ." lt_cl_version="\ m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION]) configured by $[0], generated by m4_PACKAGE_STRING. Copyright (C) 2011 Free Software Foundation, Inc. This config.lt script is free software; the Free Software Foundation gives unlimited permision to copy, distribute and modify it." while test $[#] != 0 do case $[1] in --version | --v* | -V ) echo "$lt_cl_version"; exit 0 ;; --help | --h* | -h ) echo "$lt_cl_help"; exit 0 ;; --debug | --d* | -d ) debug=: ;; --quiet | --q* | --silent | --s* | -q ) lt_cl_silent=: ;; -*) AC_MSG_ERROR([unrecognized option: $[1] Try \`$[0] --help' for more information.]) ;; *) AC_MSG_ERROR([unrecognized argument: $[1] Try \`$[0] --help' for more information.]) ;; esac shift done if $lt_cl_silent; then exec AS_MESSAGE_FD>/dev/null fi _LTEOF cat >>"$CONFIG_LT" <<_LTEOF _LT_OUTPUT_LIBTOOL_COMMANDS_INIT _LTEOF cat >>"$CONFIG_LT" <<\_LTEOF AC_MSG_NOTICE([creating $ofile]) _LT_OUTPUT_LIBTOOL_COMMANDS AS_EXIT(0) _LTEOF chmod +x "$CONFIG_LT" # configure is writing to config.log, but config.lt does its own redirection, # appending to config.log, which fails on DOS, as config.log is still kept # open by configure. Here we exec the FD to /dev/null, effectively closing # config.log, so it can be properly (re)opened and appended to by config.lt. lt_cl_success=: test "$silent" = yes && lt_config_lt_args="$lt_config_lt_args --quiet" exec AS_MESSAGE_LOG_FD>/dev/null $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false exec AS_MESSAGE_LOG_FD>>config.log $lt_cl_success || AS_EXIT(1) ])# LT_OUTPUT # _LT_CONFIG(TAG) # --------------- # If TAG is the built-in tag, create an initial libtool script with a # default configuration from the untagged config vars. Otherwise add code # to config.status for appending the configuration named by TAG from the # matching tagged config vars. m4_defun([_LT_CONFIG], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl _LT_CONFIG_SAVE_COMMANDS([ m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl m4_if(_LT_TAG, [C], [ # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi cfgfile="${ofile}T" trap "$RM \"$cfgfile\"; exit 1" 1 2 15 $RM "$cfgfile" cat <<_LT_EOF >> "$cfgfile" #! $SHELL # `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. # Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION # Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # _LT_COPYING _LT_LIBTOOL_TAGS # ### BEGIN LIBTOOL CONFIG _LT_LIBTOOL_CONFIG_VARS _LT_LIBTOOL_TAG_VARS # ### END LIBTOOL CONFIG _LT_EOF case $host_os in aix3*) cat <<\_LT_EOF >> "$cfgfile" # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi _LT_EOF ;; esac _LT_PROG_LTMAIN # We use sed instead of cat because bash on DJGPP gets confused if # if finds mixed CR/LF and LF-only lines. Since sed operates in # text mode, it properly converts lines to CR/LF. This bash problem # is reportedly fixed, but why not run on old versions too? sed '$q' "$ltmain" >> "$cfgfile" \ || (rm -f "$cfgfile"; exit 1) _LT_PROG_REPLACE_SHELLFNS mv -f "$cfgfile" "$ofile" || (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") chmod +x "$ofile" ], [cat <<_LT_EOF >> "$ofile" dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded dnl in a comment (ie after a #). # ### BEGIN LIBTOOL TAG CONFIG: $1 _LT_LIBTOOL_TAG_VARS(_LT_TAG) # ### END LIBTOOL TAG CONFIG: $1 _LT_EOF ])dnl /m4_if ], [m4_if([$1], [], [ PACKAGE='$PACKAGE' VERSION='$VERSION' TIMESTAMP='$TIMESTAMP' RM='$RM' ofile='$ofile'], []) ])dnl /_LT_CONFIG_SAVE_COMMANDS ])# _LT_CONFIG # LT_SUPPORTED_TAG(TAG) # --------------------- # Trace this macro to discover what tags are supported by the libtool # --tag option, using: # autoconf --trace 'LT_SUPPORTED_TAG:$1' AC_DEFUN([LT_SUPPORTED_TAG], []) # C support is built-in for now m4_define([_LT_LANG_C_enabled], []) m4_define([_LT_TAGS], []) # LT_LANG(LANG) # ------------- # Enable libtool support for the given language if not already enabled. AC_DEFUN([LT_LANG], [AC_BEFORE([$0], [LT_OUTPUT])dnl m4_case([$1], [C], [_LT_LANG(C)], [C++], [_LT_LANG(CXX)], [Go], [_LT_LANG(GO)], [Java], [_LT_LANG(GCJ)], [Fortran 77], [_LT_LANG(F77)], [Fortran], [_LT_LANG(FC)], [Windows Resource], [_LT_LANG(RC)], [m4_ifdef([_LT_LANG_]$1[_CONFIG], [_LT_LANG($1)], [m4_fatal([$0: unsupported language: "$1"])])])dnl ])# LT_LANG # _LT_LANG(LANGNAME) # ------------------ m4_defun([_LT_LANG], [m4_ifdef([_LT_LANG_]$1[_enabled], [], [LT_SUPPORTED_TAG([$1])dnl m4_append([_LT_TAGS], [$1 ])dnl m4_define([_LT_LANG_]$1[_enabled], [])dnl _LT_LANG_$1_CONFIG($1)])dnl ])# _LT_LANG m4_ifndef([AC_PROG_GO], [ ############################################################ # NOTE: This macro has been submitted for inclusion into # # GNU Autoconf as AC_PROG_GO. When it is available in # # a released version of Autoconf we should remove this # # macro and use it instead. # ############################################################ m4_defun([AC_PROG_GO], [AC_LANG_PUSH(Go)dnl AC_ARG_VAR([GOC], [Go compiler command])dnl AC_ARG_VAR([GOFLAGS], [Go compiler flags])dnl _AC_ARG_VAR_LDFLAGS()dnl AC_CHECK_TOOL(GOC, gccgo) if test -z "$GOC"; then if test -n "$ac_tool_prefix"; then AC_CHECK_PROG(GOC, [${ac_tool_prefix}gccgo], [${ac_tool_prefix}gccgo]) fi fi if test -z "$GOC"; then AC_CHECK_PROG(GOC, gccgo, gccgo, false) fi ])#m4_defun ])#m4_ifndef # _LT_LANG_DEFAULT_CONFIG # ----------------------- m4_defun([_LT_LANG_DEFAULT_CONFIG], [AC_PROVIDE_IFELSE([AC_PROG_CXX], [LT_LANG(CXX)], [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])]) AC_PROVIDE_IFELSE([AC_PROG_F77], [LT_LANG(F77)], [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])]) AC_PROVIDE_IFELSE([AC_PROG_FC], [LT_LANG(FC)], [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])]) dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal dnl pulling things in needlessly. AC_PROVIDE_IFELSE([AC_PROG_GCJ], [LT_LANG(GCJ)], [AC_PROVIDE_IFELSE([A][M_PROG_GCJ], [LT_LANG(GCJ)], [AC_PROVIDE_IFELSE([LT_PROG_GCJ], [LT_LANG(GCJ)], [m4_ifdef([AC_PROG_GCJ], [m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])]) m4_ifdef([A][M_PROG_GCJ], [m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])]) m4_ifdef([LT_PROG_GCJ], [m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])]) AC_PROVIDE_IFELSE([AC_PROG_GO], [LT_LANG(GO)], [m4_define([AC_PROG_GO], defn([AC_PROG_GO])[LT_LANG(GO)])]) AC_PROVIDE_IFELSE([LT_PROG_RC], [LT_LANG(RC)], [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])]) ])# _LT_LANG_DEFAULT_CONFIG # Obsolete macros: AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)]) AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)]) AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)]) AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)]) AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_CXX], []) dnl AC_DEFUN([AC_LIBTOOL_F77], []) dnl AC_DEFUN([AC_LIBTOOL_FC], []) dnl AC_DEFUN([AC_LIBTOOL_GCJ], []) dnl AC_DEFUN([AC_LIBTOOL_RC], []) # _LT_TAG_COMPILER # ---------------- m4_defun([_LT_TAG_COMPILER], [AC_REQUIRE([AC_PROG_CC])dnl _LT_DECL([LTCC], [CC], [1], [A C compiler])dnl _LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl _LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl _LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC ])# _LT_TAG_COMPILER # _LT_COMPILER_BOILERPLATE # ------------------------ # Check for compiler boilerplate output or warnings with # the simple compiler test code. m4_defun([_LT_COMPILER_BOILERPLATE], [m4_require([_LT_DECL_SED])dnl ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ])# _LT_COMPILER_BOILERPLATE # _LT_LINKER_BOILERPLATE # ---------------------- # Check for linker boilerplate output or warnings with # the simple link test code. m4_defun([_LT_LINKER_BOILERPLATE], [m4_require([_LT_DECL_SED])dnl ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* ])# _LT_LINKER_BOILERPLATE # _LT_REQUIRED_DARWIN_CHECKS # ------------------------- m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[ case $host_os in rhapsody* | darwin*) AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:]) AC_CHECK_TOOL([NMEDIT], [nmedit], [:]) AC_CHECK_TOOL([LIPO], [lipo], [:]) AC_CHECK_TOOL([OTOOL], [otool], [:]) AC_CHECK_TOOL([OTOOL64], [otool64], [:]) _LT_DECL([], [DSYMUTIL], [1], [Tool to manipulate archived DWARF debug symbol files on Mac OS X]) _LT_DECL([], [NMEDIT], [1], [Tool to change global to local symbols on Mac OS X]) _LT_DECL([], [LIPO], [1], [Tool to manipulate fat objects and archives on Mac OS X]) _LT_DECL([], [OTOOL], [1], [ldd/readelf like tool for Mach-O binaries on Mac OS X]) _LT_DECL([], [OTOOL64], [1], [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4]) AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod], [lt_cv_apple_cc_single_mod=no if test -z "${LT_MULTI_MODULE}"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE # non-empty at configure time, or by adding -multi_module to the # link flags. rm -rf libconftest.dylib* echo "int foo(void){return 1;}" > conftest.c echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c 2>conftest.err _lt_result=$? # If there is a non-empty error log, and "single_module" # appears in it, assume the flag caused a linker warning if test -s conftest.err && $GREP single_module conftest.err; then cat conftest.err >&AS_MESSAGE_LOG_FD # Otherwise, if the output was created with a 0 exit code from # the compiler, it worked. elif test -f libconftest.dylib && test $_lt_result -eq 0; then lt_cv_apple_cc_single_mod=yes else cat conftest.err >&AS_MESSAGE_LOG_FD fi rm -rf libconftest.dylib* rm -f conftest.* fi]) AC_CACHE_CHECK([for -exported_symbols_list linker flag], [lt_cv_ld_exported_symbols_list], [lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [lt_cv_ld_exported_symbols_list=yes], [lt_cv_ld_exported_symbols_list=no]) LDFLAGS="$save_LDFLAGS" ]) AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load], [lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&AS_MESSAGE_LOG_FD echo "$AR cru libconftest.a conftest.o" >&AS_MESSAGE_LOG_FD $AR cru libconftest.a conftest.o 2>&AS_MESSAGE_LOG_FD echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD cat > conftest.c << _LT_EOF int main() { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err _lt_result=$? if test -s conftest.err && $GREP force_load conftest.err; then cat conftest.err >&AS_MESSAGE_LOG_FD elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then lt_cv_ld_force_load=yes else cat conftest.err >&AS_MESSAGE_LOG_FD fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM ]) case $host_os in rhapsody* | darwin1.[[012]]) _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; darwin1.*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; darwin*) # darwin 5.x on # if running on 10.5 or later, the deployment target defaults # to the OS version, if on x86, and 10.4, the deployment # target defaults to 10.4. Don't you love it? case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in 10.0,*86*-darwin8*|10.0,*-darwin[[91]]*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; 10.[[012]]*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; 10.*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; esac ;; esac if test "$lt_cv_apple_cc_single_mod" = "yes"; then _lt_dar_single_mod='$single_module' fi if test "$lt_cv_ld_exported_symbols_list" = "yes"; then _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' else _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' fi if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then _lt_dsymutil='~$DSYMUTIL $lib || :' else _lt_dsymutil= fi ;; esac ]) # _LT_DARWIN_LINKER_FEATURES([TAG]) # --------------------------------- # Checks for linker and compiler features on darwin m4_defun([_LT_DARWIN_LINKER_FEATURES], [ m4_require([_LT_REQUIRED_DARWIN_CHECKS]) _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported if test "$lt_cv_ld_force_load" = "yes"; then _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes], [FC], [_LT_TAGVAR(compiler_needs_object, $1)=yes]) else _LT_TAGVAR(whole_archive_flag_spec, $1)='' fi _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined" case $cc_basename in ifort*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test "$_lt_dar_can_shared" = "yes"; then output_verbose_link_cmd=func_echo_all _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" m4_if([$1], [CXX], [ if test "$lt_cv_apple_cc_single_mod" != "yes"; then _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}" _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}" fi ],[]) else _LT_TAGVAR(ld_shlibs, $1)=no fi ]) # _LT_SYS_MODULE_PATH_AIX([TAGNAME]) # ---------------------------------- # Links a minimal program and checks the executable # for the system default hardcoded library path. In most cases, # this is /usr/lib:/lib, but when the MPI compilers are used # the location of the communication and MPI libs are included too. # If we don't find anything, use the default library path according # to the aix ld manual. # Store the results from the different compilers for each TAGNAME. # Allow to override them for all tags through lt_cv_aix_libpath. m4_defun([_LT_SYS_MODULE_PATH_AIX], [m4_require([_LT_DECL_SED])dnl if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])], [AC_LINK_IFELSE([AC_LANG_PROGRAM],[ lt_aix_libpath_sed='[ /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }]' _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi],[]) if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then _LT_TAGVAR([lt_cv_aix_libpath_], [$1])="/usr/lib:/lib" fi ]) aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1]) fi ])# _LT_SYS_MODULE_PATH_AIX # _LT_SHELL_INIT(ARG) # ------------------- m4_define([_LT_SHELL_INIT], [m4_divert_text([M4SH-INIT], [$1 ])])# _LT_SHELL_INIT # _LT_PROG_ECHO_BACKSLASH # ----------------------- # Find how we can fake an echo command that does not interpret backslash. # In particular, with Autoconf 2.60 or later we add some code to the start # of the generated configure script which will find a shell with a builtin # printf (which we can use as an echo command). m4_defun([_LT_PROG_ECHO_BACKSLASH], [ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO AC_MSG_CHECKING([how to print strings]) # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $[]1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } case "$ECHO" in printf*) AC_MSG_RESULT([printf]) ;; print*) AC_MSG_RESULT([print -r]) ;; *) AC_MSG_RESULT([cat]) ;; esac m4_ifdef([_AS_DETECT_SUGGESTED], [_AS_DETECT_SUGGESTED([ test -n "${ZSH_VERSION+set}${BASH_VERSION+set}" || ( ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO PATH=/empty FPATH=/empty; export PATH FPATH test "X`printf %s $ECHO`" = "X$ECHO" \ || test "X`print -r -- $ECHO`" = "X$ECHO" )])]) _LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts]) _LT_DECL([], [ECHO], [1], [An echo program that protects backslashes]) ])# _LT_PROG_ECHO_BACKSLASH # _LT_WITH_SYSROOT # ---------------- AC_DEFUN([_LT_WITH_SYSROOT], [AC_MSG_CHECKING([for sysroot]) AC_ARG_WITH([sysroot], [ --with-sysroot[=DIR] Search for dependent libraries within DIR (or the compiler's sysroot if not specified).], [], [with_sysroot=no]) dnl lt_sysroot will always be passed unquoted. We quote it here dnl in case the user passed a directory name. lt_sysroot= case ${with_sysroot} in #( yes) if test "$GCC" = yes; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) AC_MSG_RESULT([${with_sysroot}]) AC_MSG_ERROR([The sysroot must be an absolute path.]) ;; esac AC_MSG_RESULT([${lt_sysroot:-no}]) _LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl [dependent libraries, and in which our libraries should be installed.])]) # _LT_ENABLE_LOCK # --------------- m4_defun([_LT_ENABLE_LOCK], [AC_ARG_ENABLE([libtool-lock], [AS_HELP_STRING([--disable-libtool-lock], [avoid locking (might break parallel builds)])]) test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes # Some flags need to be propagated to the compiler or linker for good # libtool support. case $host in ia64-*-hpux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.$ac_objext` in *ELF-32*) HPUX_IA64_MODE="32" ;; *ELF-64*) HPUX_IA64_MODE="64" ;; esac fi rm -rf conftest* ;; *-*-irix6*) # Find out which ABI we are using. echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then if test "$lt_cv_prog_gnu_ld" = yes; then case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -melf32bsmip" ;; *N32*) LD="${LD-ld} -melf32bmipn32" ;; *64-bit*) LD="${LD-ld} -melf64bmip" ;; esac else case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -32" ;; *N32*) LD="${LD-ld} -n32" ;; *64-bit*) LD="${LD-ld} -64" ;; esac fi fi rm -rf conftest* ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.o` in *32-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_i386" ;; ppc64-*linux*|powerpc64-*linux*) LD="${LD-ld} -m elf32ppclinux" ;; s390x-*linux*) LD="${LD-ld} -m elf_s390" ;; sparc64-*linux*) LD="${LD-ld} -m elf32_sparc" ;; esac ;; *64-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_x86_64" ;; ppc*-*linux*|powerpc*-*linux*) LD="${LD-ld} -m elf64ppc" ;; s390*-*linux*|s390*-*tpf*) LD="${LD-ld} -m elf64_s390" ;; sparc*-*linux*) LD="${LD-ld} -m elf64_sparc" ;; esac ;; esac fi rm -rf conftest* ;; *-*-sco3.2v5*) # On SCO OpenServer 5, we need -belf to get full-featured binaries. SAVE_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS -belf" AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf, [AC_LANG_PUSH(C) AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no]) AC_LANG_POP]) if test x"$lt_cv_cc_needs_belf" != x"yes"; then # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf CFLAGS="$SAVE_CFLAGS" fi ;; *-*solaris*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.o` in *64-bit*) case $lt_cv_prog_gnu_ld in yes*) case $host in i?86-*-solaris*) LD="${LD-ld} -m elf_x86_64" ;; sparc*-*-solaris*) LD="${LD-ld} -m elf64_sparc" ;; esac # GNU ld 2.21 introduced _sol2 emulations. Use them if available. if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then LD="${LD-ld}_sol2" fi ;; *) if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then LD="${LD-ld} -64" fi ;; esac ;; esac fi rm -rf conftest* ;; esac need_locks="$enable_libtool_lock" ])# _LT_ENABLE_LOCK # _LT_PROG_AR # ----------- m4_defun([_LT_PROG_AR], [AC_CHECK_TOOLS(AR, [ar], false) : ${AR=ar} : ${AR_FLAGS=cru} _LT_DECL([], [AR], [1], [The archiver]) _LT_DECL([], [AR_FLAGS], [1], [Flags to create an archive]) AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file], [lt_cv_ar_at_file=no AC_COMPILE_IFELSE([AC_LANG_PROGRAM], [echo conftest.$ac_objext > conftest.lst lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD' AC_TRY_EVAL([lt_ar_try]) if test "$ac_status" -eq 0; then # Ensure the archiver fails upon bogus file names. rm -f conftest.$ac_objext libconftest.a AC_TRY_EVAL([lt_ar_try]) if test "$ac_status" -ne 0; then lt_cv_ar_at_file=@ fi fi rm -f conftest.* libconftest.a ]) ]) if test "x$lt_cv_ar_at_file" = xno; then archiver_list_spec= else archiver_list_spec=$lt_cv_ar_at_file fi _LT_DECL([], [archiver_list_spec], [1], [How to feed a file listing to the archiver]) ])# _LT_PROG_AR # _LT_CMD_OLD_ARCHIVE # ------------------- m4_defun([_LT_CMD_OLD_ARCHIVE], [_LT_PROG_AR AC_CHECK_TOOL(STRIP, strip, :) test -z "$STRIP" && STRIP=: _LT_DECL([], [STRIP], [1], [A symbol stripping program]) AC_CHECK_TOOL(RANLIB, ranlib, :) test -z "$RANLIB" && RANLIB=: _LT_DECL([], [RANLIB], [1], [Commands used to install an old-style archive]) # Determine commands to create old-style static archives. old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then case $host_os in openbsd*) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" ;; *) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" ;; esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in darwin*) lock_old_archive_extraction=yes ;; *) lock_old_archive_extraction=no ;; esac _LT_DECL([], [old_postinstall_cmds], [2]) _LT_DECL([], [old_postuninstall_cmds], [2]) _LT_TAGDECL([], [old_archive_cmds], [2], [Commands used to build an old-style archive]) _LT_DECL([], [lock_old_archive_extraction], [0], [Whether to use a lock for old archive extraction]) ])# _LT_CMD_OLD_ARCHIVE # _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, # [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE]) # ---------------------------------------------------------------- # Check whether the given compiler option works AC_DEFUN([_LT_COMPILER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4]) echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$3" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&AS_MESSAGE_LOG_FD echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi fi $RM conftest* ]) if test x"[$]$2" = xyes; then m4_if([$5], , :, [$5]) else m4_if([$6], , :, [$6]) fi ])# _LT_COMPILER_OPTION # Old name: AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], []) # _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, # [ACTION-SUCCESS], [ACTION-FAILURE]) # ---------------------------------------------------- # Check whether the given linker option works AC_DEFUN([_LT_LINKER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS $3" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&AS_MESSAGE_LOG_FD $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi else $2=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" ]) if test x"[$]$2" = xyes; then m4_if([$4], , :, [$4]) else m4_if([$5], , :, [$5]) fi ])# _LT_LINKER_OPTION # Old name: AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], []) # LT_CMD_MAX_LEN #--------------- AC_DEFUN([LT_CMD_MAX_LEN], [AC_REQUIRE([AC_CANONICAL_HOST])dnl # find the maximum length of command line arguments AC_MSG_CHECKING([the maximum length of command line arguments]) AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl i=0 teststring="ABCD" case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[ ]]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8 ; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test $i != 17 # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac ]) if test -n $lt_cv_sys_max_cmd_len ; then AC_MSG_RESULT($lt_cv_sys_max_cmd_len) else AC_MSG_RESULT(none) fi max_cmd_len=$lt_cv_sys_max_cmd_len _LT_DECL([], [max_cmd_len], [0], [What is the maximum length of a command?]) ])# LT_CMD_MAX_LEN # Old name: AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], []) # _LT_HEADER_DLFCN # ---------------- m4_defun([_LT_HEADER_DLFCN], [AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl ])# _LT_HEADER_DLFCN # _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE, # ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING) # ---------------------------------------------------------------- m4_defun([_LT_TRY_DLOPEN_SELF], [m4_require([_LT_HEADER_DLFCN])dnl if test "$cross_compiling" = yes; then : [$4] else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF [#line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; }] _LT_EOF if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) $1 ;; x$lt_dlneed_uscore) $2 ;; x$lt_dlunknown|x*) $3 ;; esac else : # compilation failed $3 fi fi rm -fr conftest* ])# _LT_TRY_DLOPEN_SELF # LT_SYS_DLOPEN_SELF # ------------------ AC_DEFUN([LT_SYS_DLOPEN_SELF], [m4_require([_LT_HEADER_DLFCN])dnl if test "x$enable_dlopen" != xyes; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen="load_add_on" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen="LoadLibrary" lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen="dlopen" lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[ lt_cv_dlopen="dyld" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ]) ;; *) AC_CHECK_FUNC([shl_load], [lt_cv_dlopen="shl_load"], [AC_CHECK_LIB([dld], [shl_load], [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"], [AC_CHECK_FUNC([dlopen], [lt_cv_dlopen="dlopen"], [AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"], [AC_CHECK_LIB([svld], [dlopen], [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"], [AC_CHECK_LIB([dld], [dld_link], [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"]) ]) ]) ]) ]) ]) ;; esac if test "x$lt_cv_dlopen" != xno; then enable_dlopen=yes else enable_dlopen=no fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS="$CPPFLAGS" test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS="$LDFLAGS" wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS="$LIBS" LIBS="$lt_cv_dlopen_libs $LIBS" AC_CACHE_CHECK([whether a program can dlopen itself], lt_cv_dlopen_self, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes, lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross) ]) if test "x$lt_cv_dlopen_self" = xyes; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" AC_CACHE_CHECK([whether a statically linked program can dlopen itself], lt_cv_dlopen_self_static, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross) ]) fi CPPFLAGS="$save_CPPFLAGS" LDFLAGS="$save_LDFLAGS" LIBS="$save_LIBS" ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi _LT_DECL([dlopen_support], [enable_dlopen], [0], [Whether dlopen is supported]) _LT_DECL([dlopen_self], [enable_dlopen_self], [0], [Whether dlopen of programs is supported]) _LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0], [Whether dlopen of statically linked programs is supported]) ])# LT_SYS_DLOPEN_SELF # Old name: AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], []) # _LT_COMPILER_C_O([TAGNAME]) # --------------------------- # Check to see if options -c and -o are simultaneously supported by compiler. # This macro does not hard code the compiler like AC_PROG_CC_C_O. m4_defun([_LT_COMPILER_C_O], [m4_require([_LT_DECL_SED])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_TAG_COMPILER])dnl AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext], [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)], [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&AS_MESSAGE_LOG_FD echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes fi fi chmod u+w . 2>&AS_MESSAGE_LOG_FD $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* ]) _LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1], [Does compiler simultaneously support -c and -o options?]) ])# _LT_COMPILER_C_O # _LT_COMPILER_FILE_LOCKS([TAGNAME]) # ---------------------------------- # Check to see if we can do hard links to lock some files if needed m4_defun([_LT_COMPILER_FILE_LOCKS], [m4_require([_LT_ENABLE_LOCK])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl _LT_COMPILER_C_O([$1]) hard_links="nottested" if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then # do not overwrite the value of need_locks provided by the user AC_MSG_CHECKING([if we can lock with hard links]) hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no AC_MSG_RESULT([$hard_links]) if test "$hard_links" = no; then AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe]) need_locks=warn fi else need_locks=no fi _LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?]) ])# _LT_COMPILER_FILE_LOCKS # _LT_CHECK_OBJDIR # ---------------- m4_defun([_LT_CHECK_OBJDIR], [AC_CACHE_CHECK([for objdir], [lt_cv_objdir], [rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi rmdir .libs 2>/dev/null]) objdir=$lt_cv_objdir _LT_DECL([], [objdir], [0], [The name of the directory that contains temporary libtool files])dnl m4_pattern_allow([LT_OBJDIR])dnl AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/", [Define to the sub-directory in which libtool stores uninstalled libraries.]) ])# _LT_CHECK_OBJDIR # _LT_LINKER_HARDCODE_LIBPATH([TAGNAME]) # -------------------------------------- # Check hardcoding attributes. m4_defun([_LT_LINKER_HARDCODE_LIBPATH], [AC_MSG_CHECKING([how to hardcode library paths into programs]) _LT_TAGVAR(hardcode_action, $1)= if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" || test -n "$_LT_TAGVAR(runpath_var, $1)" || test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then # We can hardcode non-existent directories. if test "$_LT_TAGVAR(hardcode_direct, $1)" != no && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no && test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then # Linking always hardcodes the temporary library directory. _LT_TAGVAR(hardcode_action, $1)=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. _LT_TAGVAR(hardcode_action, $1)=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. _LT_TAGVAR(hardcode_action, $1)=unsupported fi AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)]) if test "$_LT_TAGVAR(hardcode_action, $1)" = relink || test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then # Fast installation is not supported enable_fast_install=no elif test "$shlibpath_overrides_runpath" = yes || test "$enable_shared" = no; then # Fast installation is not necessary enable_fast_install=needless fi _LT_TAGDECL([], [hardcode_action], [0], [How to hardcode a shared library path into an executable]) ])# _LT_LINKER_HARDCODE_LIBPATH # _LT_CMD_STRIPLIB # ---------------- m4_defun([_LT_CMD_STRIPLIB], [m4_require([_LT_DECL_EGREP]) striplib= old_striplib= AC_MSG_CHECKING([whether stripping libraries is possible]) if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" test -z "$striplib" && striplib="$STRIP --strip-unneeded" AC_MSG_RESULT([yes]) else # FIXME - insert some real tests, host_os isn't really good enough case $host_os in darwin*) if test -n "$STRIP" ; then striplib="$STRIP -x" old_striplib="$STRIP -S" AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) fi ;; *) AC_MSG_RESULT([no]) ;; esac fi _LT_DECL([], [old_striplib], [1], [Commands to strip libraries]) _LT_DECL([], [striplib], [1]) ])# _LT_CMD_STRIPLIB # _LT_SYS_DYNAMIC_LINKER([TAG]) # ----------------------------- # PORTME Fill in your ld.so characteristics m4_defun([_LT_SYS_DYNAMIC_LINKER], [AC_REQUIRE([AC_CANONICAL_HOST])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_OBJDUMP])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_CHECK_SHELL_FEATURES])dnl AC_MSG_CHECKING([dynamic linker characteristics]) m4_if([$1], [], [ if test "$GCC" = yes; then case $host_os in darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; *) lt_awk_arg="/^libraries:/" ;; esac case $host_os in mingw* | cegcc*) lt_sed_strip_eq="s,=\([[A-Za-z]]:\),\1,g" ;; *) lt_sed_strip_eq="s,=/,/,g" ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` case $lt_search_path_spec in *\;*) # if the path contains ";" then we assume it to be the separator # otherwise default to the standard path separator (i.e. ":") - it is # assumed that no part of a normal pathname contains ";" but that should # okay in the real world where ";" in dirpaths is itself problematic. lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` ;; *) lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` ;; esac # Ok, now we have the path, separated by spaces, we can step through it # and add multilib dir if necessary. lt_tmp_lt_search_path_spec= lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` for lt_sys_path in $lt_search_path_spec; do if test -d "$lt_sys_path/$lt_multi_os_dir"; then lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" else test -d "$lt_sys_path" && \ lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" fi done lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' BEGIN {RS=" "; FS="/|\n";} { lt_foo=""; lt_count=0; for (lt_i = NF; lt_i > 0; lt_i--) { if ($lt_i != "" && $lt_i != ".") { if ($lt_i == "..") { lt_count++; } else { if (lt_count == 0) { lt_foo="/" $lt_i lt_foo; } else { lt_count--; } } } } if (lt_foo != "") { lt_freq[[lt_foo]]++; } if (lt_freq[[lt_foo]] == 1) { print lt_foo; } }'` # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's,/\([[A-Za-z]]:\),\1,g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` else sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" fi]) library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=".so" postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='${libname}${release}${shared_ext}$major' ;; aix[[4-9]]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test "$host_cpu" = ia64; then # AIX 5 supports IA64 library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line `#! .'. This would cause the generated library to # depend on `.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[[01]] | aix4.[[01]].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # AIX (on Power*) has no versioning support, so currently we can not hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. if test "$aix_use_runtimelinking" = yes; then # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' else # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='${libname}${release}.a $libname.a' soname_spec='${libname}${release}${shared_ext}$major' fi shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='${libname}${shared_ext}' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[[45]]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=".dll" need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' m4_if([$1], [],[ sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"]) ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' library_names_spec='${libname}.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec="$LIB" if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' soname_spec='${libname}${release}${major}$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' m4_if([$1], [],[ sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"]) sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[[23]].*) objformat=aout ;; *) objformat=elf ;; esac fi version_type=freebsd-$objformat case $version_type in freebsd-elf*) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' need_version=yes ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[[01]]* | freebsdelf3.[[01]]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \ freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=yes sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' if test "X$HPUX_IA64_MODE" = X32; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" fi sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[[3-9]]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test "$lt_cv_prog_gnu_ld" = yes; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH AC_CACHE_VAL([lt_cv_shlibpath_overrides_runpath], [lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \ LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\"" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null], [lt_cv_shlibpath_overrides_runpath=yes])]) LDFLAGS=$save_LDFLAGS libdir=$save_libdir ]) shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsdelf*-gnu) version_type=linux need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='NetBSD ld.elf_so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd*) version_type=sunos sys_lib_dlsearch_path_spec="/usr/lib" need_lib_prefix=no # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. case $host_os in openbsd3.3 | openbsd3.3.*) need_version=yes ;; *) need_version=no ;; esac library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then case $host_os in openbsd2.[[89]] | openbsd2.[[89]].*) shlibpath_overrides_runpath=no ;; *) shlibpath_overrides_runpath=yes ;; esac else shlibpath_overrides_runpath=yes fi ;; os2*) libname_spec='$name' shrext_cmds=".dll" need_lib_prefix=no library_names_spec='$libname${shared_ext} $libname.a' dynamic_linker='OS/2 ld.exe' shlibpath_var=LIBPATH ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test "$with_gnu_ld" = yes; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec ;then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' soname_spec='$libname${shared_ext}.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=freebsd-elf need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test "$with_gnu_ld" = yes; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac AC_MSG_RESULT([$dynamic_linker]) test "$dynamic_linker" = no && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test "$GCC" = yes; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" fi if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" fi _LT_DECL([], [variables_saved_for_relink], [1], [Variables whose values should be saved in libtool wrapper scripts and restored at link time]) _LT_DECL([], [need_lib_prefix], [0], [Do we need the "lib" prefix for modules?]) _LT_DECL([], [need_version], [0], [Do we need a version for libraries?]) _LT_DECL([], [version_type], [0], [Library versioning type]) _LT_DECL([], [runpath_var], [0], [Shared library runtime path variable]) _LT_DECL([], [shlibpath_var], [0],[Shared library path variable]) _LT_DECL([], [shlibpath_overrides_runpath], [0], [Is shlibpath searched before the hard-coded library search path?]) _LT_DECL([], [libname_spec], [1], [Format of library name prefix]) _LT_DECL([], [library_names_spec], [1], [[List of archive names. First name is the real one, the rest are links. The last name is the one that the linker finds with -lNAME]]) _LT_DECL([], [soname_spec], [1], [[The coded name of the library, if different from the real name]]) _LT_DECL([], [install_override_mode], [1], [Permission mode override for installation of shared libraries]) _LT_DECL([], [postinstall_cmds], [2], [Command to use after installation of a shared archive]) _LT_DECL([], [postuninstall_cmds], [2], [Command to use after uninstallation of a shared archive]) _LT_DECL([], [finish_cmds], [2], [Commands used to finish a libtool library installation in a directory]) _LT_DECL([], [finish_eval], [1], [[As "finish_cmds", except a single script fragment to be evaled but not shown]]) _LT_DECL([], [hardcode_into_libs], [0], [Whether we should hardcode library paths into libraries]) _LT_DECL([], [sys_lib_search_path_spec], [2], [Compile-time system search path for libraries]) _LT_DECL([], [sys_lib_dlsearch_path_spec], [2], [Run-time system search path for libraries]) ])# _LT_SYS_DYNAMIC_LINKER # _LT_PATH_TOOL_PREFIX(TOOL) # -------------------------- # find a file program which can recognize shared library AC_DEFUN([_LT_PATH_TOOL_PREFIX], [m4_require([_LT_DECL_EGREP])dnl AC_MSG_CHECKING([for $1]) AC_CACHE_VAL(lt_cv_path_MAGIC_CMD, [case $MAGIC_CMD in [[\\/*] | ?:[\\/]*]) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR dnl $ac_dummy forces splitting on constant user-supplied paths. dnl POSIX.2 word splitting is done only on the output of word expansions, dnl not every word. This closes a longstanding sh security hole. ac_dummy="m4_if([$2], , $PATH, [$2])" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/$1; then lt_cv_path_MAGIC_CMD="$ac_dir/$1" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac]) MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then AC_MSG_RESULT($MAGIC_CMD) else AC_MSG_RESULT(no) fi _LT_DECL([], [MAGIC_CMD], [0], [Used to examine libraries when file_magic_cmd begins with "file"])dnl ])# _LT_PATH_TOOL_PREFIX # Old name: AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], []) # _LT_PATH_MAGIC # -------------- # find a file program which can recognize a shared library m4_defun([_LT_PATH_MAGIC], [_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH) if test -z "$lt_cv_path_MAGIC_CMD"; then if test -n "$ac_tool_prefix"; then _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH) else MAGIC_CMD=: fi fi ])# _LT_PATH_MAGIC # LT_PATH_LD # ---------- # find the pathname to the GNU or non-GNU linker AC_DEFUN([LT_PATH_LD], [AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_PROG_ECHO_BACKSLASH])dnl AC_ARG_WITH([gnu-ld], [AS_HELP_STRING([--with-gnu-ld], [assume the C compiler uses GNU ld @<:@default=no@:>@])], [test "$withval" = no || with_gnu_ld=yes], [with_gnu_ld=no])dnl ac_prog=ld if test "$GCC" = yes; then # Check if gcc -print-prog-name=ld gives a path. AC_MSG_CHECKING([for ld used by $CC]) case $host in *-*-mingw*) # gcc leaves a trailing carriage return which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [[\\/]]* | ?:[[\\/]]*) re_direlt='/[[^/]][[^/]]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD="$ac_prog" ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test "$with_gnu_ld" = yes; then AC_MSG_CHECKING([for GNU ld]) else AC_MSG_CHECKING([for non-GNU ld]) fi AC_CACHE_VAL(lt_cv_path_LD, [if test -z "$LD"; then lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD="$ac_dir/$ac_prog" # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &1 /dev/null 2>&1; then lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; cegcc*) # use the weaker test based on 'objdump'. See mingw*. lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' lt_cv_file_magic_cmd='$OBJDUMP -f' ;; darwin* | rhapsody*) lt_cv_deplibs_check_method=pass_all ;; freebsd* | dragonfly*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then case $host_cpu in i*86 ) # Not sure whether the presence of OpenBSD here was a mistake. # Let's accept both of them until this is cleared up. lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` ;; esac else lt_cv_deplibs_check_method=pass_all fi ;; haiku*) lt_cv_deplibs_check_method=pass_all ;; hpux10.20* | hpux11*) lt_cv_file_magic_cmd=/usr/bin/file case $host_cpu in ia64*) lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64' lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so ;; hppa*64*) [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]'] lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl ;; *) lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]]\.[[0-9]]) shared library' lt_cv_file_magic_test_file=/usr/lib/libc.sl ;; esac ;; interix[[3-9]]*) # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$' ;; irix5* | irix6* | nonstopux*) case $LD in *-32|*"-32 ") libmagic=32-bit;; *-n32|*"-n32 ") libmagic=N32;; *-64|*"-64 ") libmagic=64-bit;; *) libmagic=never-match;; esac lt_cv_deplibs_check_method=pass_all ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) lt_cv_deplibs_check_method=pass_all ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$' fi ;; newos6*) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=/usr/lib/libnls.so ;; *nto* | *qnx*) lt_cv_deplibs_check_method=pass_all ;; openbsd*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' fi ;; osf3* | osf4* | osf5*) lt_cv_deplibs_check_method=pass_all ;; rdos*) lt_cv_deplibs_check_method=pass_all ;; solaris*) lt_cv_deplibs_check_method=pass_all ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) lt_cv_deplibs_check_method=pass_all ;; sysv4 | sysv4.3*) case $host_vendor in motorola) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]' lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` ;; ncr) lt_cv_deplibs_check_method=pass_all ;; sequent) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )' ;; sni) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib" lt_cv_file_magic_test_file=/lib/libc.so ;; siemens) lt_cv_deplibs_check_method=pass_all ;; pc) lt_cv_deplibs_check_method=pass_all ;; esac ;; tpf*) lt_cv_deplibs_check_method=pass_all ;; esac ]) file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in mingw* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[[\1]]\/[[\1]]\/g;/g"` fi ;; esac fi file_magic_cmd=$lt_cv_file_magic_cmd deplibs_check_method=$lt_cv_deplibs_check_method test -z "$deplibs_check_method" && deplibs_check_method=unknown _LT_DECL([], [deplibs_check_method], [1], [Method to check whether dependent libraries are shared objects]) _LT_DECL([], [file_magic_cmd], [1], [Command to use when deplibs_check_method = "file_magic"]) _LT_DECL([], [file_magic_glob], [1], [How to find potential files when deplibs_check_method = "file_magic"]) _LT_DECL([], [want_nocaseglob], [1], [Find potential files using nocaseglob when deplibs_check_method = "file_magic"]) ])# _LT_CHECK_MAGIC_METHOD # LT_PATH_NM # ---------- # find the pathname to a BSD- or MS-compatible name lister AC_DEFUN([LT_PATH_NM], [AC_REQUIRE([AC_PROG_CC])dnl AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM, [if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM="$NM" else lt_nm_to_check="${ac_tool_prefix}nm" if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. tmp_nm="$ac_dir/$lt_tmp_nm" if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then # Check to see if the nm accepts a BSD-compat flag. # Adding the `sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in */dev/null* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS="$lt_save_ifs" done : ${lt_cv_path_NM=no} fi]) if test "$lt_cv_path_NM" != "no"; then NM="$lt_cv_path_NM" else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :) case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols" ;; *) DUMPBIN=: ;; esac fi AC_SUBST([DUMPBIN]) if test "$DUMPBIN" != ":"; then NM="$DUMPBIN" fi fi test -z "$NM" && NM=nm AC_SUBST([NM]) _LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface], [lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD) cat conftest.out >&AS_MESSAGE_LOG_FD if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest*]) ])# LT_PATH_NM # Old names: AU_ALIAS([AM_PROG_NM], [LT_PATH_NM]) AU_ALIAS([AC_PROG_NM], [LT_PATH_NM]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_PROG_NM], []) dnl AC_DEFUN([AC_PROG_NM], []) # _LT_CHECK_SHAREDLIB_FROM_LINKLIB # -------------------------------- # how to determine the name of the shared library # associated with a specific link library. # -- PORTME fill in with the dynamic library characteristics m4_defun([_LT_CHECK_SHAREDLIB_FROM_LINKLIB], [m4_require([_LT_DECL_EGREP]) m4_require([_LT_DECL_OBJDUMP]) m4_require([_LT_DECL_DLLTOOL]) AC_CACHE_CHECK([how to associate runtime and link libraries], lt_cv_sharedlib_from_linklib_cmd, [lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in cygwin* | mingw* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh # decide which to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in *--identify-strict*) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib ;; *) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback ;; esac ;; *) # fallback: assume linklib IS sharedlib lt_cv_sharedlib_from_linklib_cmd="$ECHO" ;; esac ]) sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO _LT_DECL([], [sharedlib_from_linklib_cmd], [1], [Command to associate shared and link libraries]) ])# _LT_CHECK_SHAREDLIB_FROM_LINKLIB # _LT_PATH_MANIFEST_TOOL # ---------------------- # locate the manifest tool m4_defun([_LT_PATH_MANIFEST_TOOL], [AC_CHECK_TOOL(MANIFEST_TOOL, mt, :) test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool], [lt_cv_path_mainfest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&AS_MESSAGE_LOG_FD if $GREP 'Manifest Tool' conftest.out > /dev/null; then lt_cv_path_mainfest_tool=yes fi rm -f conftest*]) if test "x$lt_cv_path_mainfest_tool" != xyes; then MANIFEST_TOOL=: fi _LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl ])# _LT_PATH_MANIFEST_TOOL # LT_LIB_M # -------- # check for math library AC_DEFUN([LT_LIB_M], [AC_REQUIRE([AC_CANONICAL_HOST])dnl LIBM= case $host in *-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*) # These system don't have libm, or don't need it ;; *-ncr-sysv4.3*) AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw") AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm") ;; *) AC_CHECK_LIB(m, cos, LIBM="-lm") ;; esac AC_SUBST([LIBM]) ])# LT_LIB_M # Old name: AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_CHECK_LIBM], []) # _LT_COMPILER_NO_RTTI([TAGNAME]) # ------------------------------- m4_defun([_LT_COMPILER_NO_RTTI], [m4_require([_LT_TAG_COMPILER])dnl _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= if test "$GCC" = yes; then case $cc_basename in nvcc*) _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;; *) _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' ;; esac _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions], lt_cv_prog_compiler_rtti_exceptions, [-fno-rtti -fno-exceptions], [], [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"]) fi _LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1], [Compiler flag to turn off builtin functions]) ])# _LT_COMPILER_NO_RTTI # _LT_CMD_GLOBAL_SYMBOLS # ---------------------- m4_defun([_LT_CMD_GLOBAL_SYMBOLS], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([LT_PATH_NM])dnl AC_REQUIRE([LT_PATH_LD])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_TAG_COMPILER])dnl # Check for command to grab the raw symbol name followed by C symbol from nm. AC_MSG_CHECKING([command to parse $NM output from $compiler object]) AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe], [ # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] # Character class describing NM global symbol codes. symcode='[[BCDEGRST]]' # Regexp to match symbols that can be accessed directly from C. sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)' # Define system-specific variables. case $host_os in aix*) symcode='[[BCDT]]' ;; cygwin* | mingw* | pw32* | cegcc*) symcode='[[ABCDGISTW]]' ;; hpux*) if test "$host_cpu" = ia64; then symcode='[[ABCDEGRST]]' fi ;; irix* | nonstopux*) symcode='[[BCDEGRST]]' ;; osf*) symcode='[[BCDEGQRST]]' ;; solaris*) symcode='[[BDRT]]' ;; sco3.2v5*) symcode='[[DT]]' ;; sysv4.2uw2*) symcode='[[DT]]' ;; sysv5* | sco5v6* | unixware* | OpenUNIX*) symcode='[[ABDT]]' ;; sysv4) symcode='[[DFNSTU]]' ;; esac # If we're using GNU nm, then use its standard symbol codes. case `$NM -V 2>&1` in *GNU* | *'with BFD'*) symcode='[[ABCDGIRSTW]]' ;; esac # Transform an extracted symbol line into a proper C declaration. # Some systems (esp. on ia64) link data and code symbols differently, # so use this general approach. lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" # Transform an extracted symbol line into symbol name and symbol address lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (void *) \&\2},/p'" lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"lib\2\", (void *) \&\2},/p'" # Handle CRLF in mingw tool chain opt_cr= case $build_os in mingw*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac # Try without a prefix underscore, then with it. for ac_symprfx in "" "_"; do # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. symxfrm="\\1 $ac_symprfx\\2 \\2" # Write the raw and C identifiers. if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Fake it for dumpbin and say T for any non-static function # and D for any global variable. # Also find C++ and __fastcall symbols from MSVC++, # which start with @ or ?. lt_cv_sys_global_symbol_pipe="$AWK ['"\ " {last_section=section; section=\$ 3};"\ " /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ " /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ " \$ 0!~/External *\|/{next};"\ " / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ " {if(hide[section]) next};"\ " {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ " {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ " s[1]~/^[@?]/{print s[1], s[1]; next};"\ " s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ " ' prfx=^$ac_symprfx]" else lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[ ]]\($symcode$symcode*\)[[ ]][[ ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" fi lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'" # Check to see that the pipe works correctly. pipe_works=no rm -f conftest* cat > conftest.$ac_ext <<_LT_EOF #ifdef __cplusplus extern "C" { #endif char nm_test_var; void nm_test_func(void); void nm_test_func(void){} #ifdef __cplusplus } #endif int main(){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if AC_TRY_EVAL(ac_compile); then # Now try to grab the symbols. nlist=conftest.nm if AC_TRY_EVAL(NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) && test -s "$nlist"; then # Try sorting and uniquifying the output. if sort "$nlist" | uniq > "$nlist"T; then mv -f "$nlist"T "$nlist" else rm -f "$nlist"T fi # Make sure that we snagged all the symbols we need. if $GREP ' nm_test_var$' "$nlist" >/dev/null; then if $GREP ' nm_test_func$' "$nlist" >/dev/null; then cat <<_LT_EOF > conftest.$ac_ext /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT@&t@_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT@&t@_DLSYM_CONST #else # define LT@&t@_DLSYM_CONST const #endif #ifdef __cplusplus extern "C" { #endif _LT_EOF # Now generate the symbol file. eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' cat <<_LT_EOF >> conftest.$ac_ext /* The mapping between symbol names and symbols. */ LT@&t@_DLSYM_CONST struct { const char *name; void *address; } lt__PROGRAM__LTX_preloaded_symbols[[]] = { { "@PROGRAM@", (void *) 0 }, _LT_EOF $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext cat <<\_LT_EOF >> conftest.$ac_ext {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt__PROGRAM__LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif _LT_EOF # Now try linking the two files. mv conftest.$ac_objext conftstm.$ac_objext lt_globsym_save_LIBS=$LIBS lt_globsym_save_CFLAGS=$CFLAGS LIBS="conftstm.$ac_objext" CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)" if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then pipe_works=yes fi LIBS=$lt_globsym_save_LIBS CFLAGS=$lt_globsym_save_CFLAGS else echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD fi else echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD fi else echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD fi else echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD cat conftest.$ac_ext >&5 fi rm -rf conftest* conftst* # Do not use the global_symbol_pipe unless it works. if test "$pipe_works" = yes; then break else lt_cv_sys_global_symbol_pipe= fi done ]) if test -z "$lt_cv_sys_global_symbol_pipe"; then lt_cv_sys_global_symbol_to_cdecl= fi if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then AC_MSG_RESULT(failed) else AC_MSG_RESULT(ok) fi # Response file support. if test "$lt_cv_nm_interface" = "MS dumpbin"; then nm_file_list_spec='@' elif $NM --help 2>/dev/null | grep '[[@]]FILE' >/dev/null; then nm_file_list_spec='@' fi _LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1], [Take the output of nm and produce a listing of raw symbols and C names]) _LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1], [Transform the output of nm in a proper C declaration]) _LT_DECL([global_symbol_to_c_name_address], [lt_cv_sys_global_symbol_to_c_name_address], [1], [Transform the output of nm in a C name address pair]) _LT_DECL([global_symbol_to_c_name_address_lib_prefix], [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1], [Transform the output of nm in a C name address pair when lib prefix is needed]) _LT_DECL([], [nm_file_list_spec], [1], [Specify filename containing input files for $NM]) ]) # _LT_CMD_GLOBAL_SYMBOLS # _LT_COMPILER_PIC([TAGNAME]) # --------------------------- m4_defun([_LT_COMPILER_PIC], [m4_require([_LT_TAG_COMPILER])dnl _LT_TAGVAR(lt_prog_compiler_wl, $1)= _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)= m4_if([$1], [CXX], [ # C++ specific cases for pic, static, wl, etc. if test "$GXX" = yes; then _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' ;; *djgpp*) # DJGPP does not support shared libraries at all _LT_TAGVAR(lt_prog_compiler_pic, $1)= ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. _LT_TAGVAR(lt_prog_compiler_static, $1)= ;; interix[[3-9]]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic fi ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac else case $host_os in aix[[4-9]]*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' else _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' fi ;; chorus*) case $cc_basename in cxch68*) # Green Hills C++ Compiler # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" ;; esac ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; dgux*) case $cc_basename in ec++*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' ;; ghcx*) # Green Hills C++ Compiler _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; *) ;; esac ;; freebsd* | dragonfly*) # FreeBSD uses GNU C++ ;; hpux9* | hpux10* | hpux11*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' if test "$host_cpu" != ia64; then _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' fi ;; aCC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' ;; esac ;; *) ;; esac ;; interix*) # This is c89, which is MS Visual C++ (no shared libs) # Anyone wants to do a port? ;; irix5* | irix6* | nonstopux*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' # CC pic flag -KPIC is the default. ;; *) ;; esac ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # KAI C++ Compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; ecpc* ) # old Intel C++ for x86_64 which still supported -KPIC. _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; icpc* ) # Intel C++, used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; pgCC* | pgcpp*) # Portland Group C++ compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; cxx*) # Compaq C++ # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; xlc* | xlC* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL 8.0, 9.0 on PPC and BlueGene _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; esac ;; esac ;; lynxos*) ;; m88k*) ;; mvs*) case $cc_basename in cxx*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall' ;; *) ;; esac ;; netbsd* | netbsdelf*-gnu) ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' ;; RCC*) # Rational C++ 2.4.1 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; cxx*) # Digital/Compaq C++ _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; *) ;; esac ;; psos*) ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; gcx*) # Green Hills C++ Compiler _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' ;; *) ;; esac ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; lcc*) # Lucid _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; *) ;; esac ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' ;; *) ;; esac ;; vxworks*) ;; *) _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; esac fi ], [ if test "$GCC" = yes; then _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. _LT_TAGVAR(lt_prog_compiler_static, $1)= ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac ;; interix[[3-9]]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; msdosdjgpp*) # Just because we use GCC doesn't mean we suddenly get shared libraries # on systems that don't support them. _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no enable_shared=no ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic fi ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac case $cc_basename in nvcc*) # Cuda Compiler Driver 2.2 _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Xlinker ' if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then _LT_TAGVAR(lt_prog_compiler_pic, $1)="-Xcompiler $_LT_TAGVAR(lt_prog_compiler_pic, $1)" fi ;; esac else # PORTME Check for flag to pass linker flags through the system compiler. case $host_os in aix*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' else _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' fi ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; hpux9* | hpux10* | hpux11*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but # not for PA HP-UX. case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' ;; esac # Is there a better lt_prog_compiler_static that works with the bundled CC? _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' ;; irix5* | irix6* | nonstopux*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # PIC (with -KPIC) is the default. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in # old Intel for x86_64 which still supported -KPIC. ecc*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; # icc used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. icc* | ifort*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; # Lahey Fortran 8.1. lf95*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared' _LT_TAGVAR(lt_prog_compiler_static, $1)='--static' ;; nagfor*) # NAG Fortran compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group compilers (*not* the Pentium gcc compiler, # which looks to be a dead project) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; ccc*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # All Alpha code is PIC. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; xl* | bgxl* | bgf* | mpixl*) # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [[1-7]].* | *Sun*Fortran*\ 8.[[0-3]]*) # Sun Fortran 8.3 passes all unrecognized flags to the linker _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='' ;; *Sun\ F* | *Sun*Fortran*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; *Sun\ C*) # Sun C 5.9 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' ;; *Intel*\ [[CF]]*Compiler*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; *Portland\ Group*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; esac ;; newsos6) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; osf3* | osf4* | osf5*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # All OSF/1 code is PIC. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; rdos*) _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; solaris*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' case $cc_basename in f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';; *) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';; esac ;; sunos4*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; sysv4 | sysv4.2uw2* | sysv4.3*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; sysv4*MP*) if test -d /usr/nec ;then _LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; unicos*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; uts4*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; *) _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; esac fi ]) case $host_os in # For platforms which do not support PIC, -DPIC is meaningless: *djgpp*) _LT_TAGVAR(lt_prog_compiler_pic, $1)= ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])" ;; esac AC_CACHE_CHECK([for $compiler option to produce PIC], [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)], [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_prog_compiler_pic, $1)]) _LT_TAGVAR(lt_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_cv_prog_compiler_pic, $1) # # Check to make sure the PIC flag actually works. # if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works], [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)], [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [], [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in "" | " "*) ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;; esac], [_LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no]) fi _LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1], [Additional compiler flags for building library objects]) _LT_TAGDECL([wl], [lt_prog_compiler_wl], [1], [How to pass a linker flag through the compiler]) # # Check to make sure the static flag actually works. # wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\" _LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works], _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1), $lt_tmp_static_flag, [], [_LT_TAGVAR(lt_prog_compiler_static, $1)=]) _LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1], [Compiler flag to prevent dynamic linking]) ])# _LT_COMPILER_PIC # _LT_LINKER_SHLIBS([TAGNAME]) # ---------------------------- # See if the linker supports building shared libraries. m4_defun([_LT_LINKER_SHLIBS], [AC_REQUIRE([LT_PATH_LD])dnl AC_REQUIRE([LT_PATH_NM])dnl m4_require([_LT_PATH_MANIFEST_TOOL])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl m4_require([_LT_TAG_COMPILER])dnl AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) m4_if([$1], [CXX], [ _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] case $host_os in aix[[4-9]]*) # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global defined # symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi ;; pw32*) _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds" ;; cygwin* | mingw* | cegcc*) case $cc_basename in cl*) _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' ;; *) _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] ;; esac ;; linux* | k*bsd*-gnu | gnu*) _LT_TAGVAR(link_all_deplibs, $1)=no ;; *) _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' ;; esac ], [ runpath_var= _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_cmds, $1)= _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(compiler_needs_object, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(old_archive_from_new_cmds, $1)= _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)= _LT_TAGVAR(thread_safe_flag_spec, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= # include_expsyms should be a list of space-separated symbols to be *always* # included in the symbol list _LT_TAGVAR(include_expsyms, $1)= # exclude_expsyms can be an extended regexp of symbols to exclude # it will be wrapped by ` (' and `)$', so one must not match beginning or # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', # as well as any symbol that contains `d'. _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out # platforms (ab)use it in PIC code, but their linkers get confused if # the symbol is explicitly referenced. Since portable code cannot # rely on this symbol name, it's probably fine to never include it in # preloaded symbol tables. # Exclude shared library initialization/finalization symbols. dnl Note also adjust exclude_expsyms for C++ above. extract_expsyms_cmds= case $host_os in cygwin* | mingw* | pw32* | cegcc*) # FIXME: the MSVC++ port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++. if test "$GCC" != yes; then with_gnu_ld=no fi ;; interix*) # we just hope/assume this is gcc and not c89 (= MSVC++) with_gnu_ld=yes ;; openbsd*) with_gnu_ld=no ;; linux* | k*bsd*-gnu | gnu*) _LT_TAGVAR(link_all_deplibs, $1)=no ;; esac _LT_TAGVAR(ld_shlibs, $1)=yes # On some targets, GNU ld is compatible enough with the native linker # that we're better off using the native interface for both. lt_use_gnu_ld_interface=no if test "$with_gnu_ld" = yes; then case $host_os in aix*) # The AIX port of GNU ld has always aspired to compatibility # with the native linker. However, as the warning in the GNU ld # block says, versions before 2.19.5* couldn't really create working # shared libraries, regardless of the interface used. case `$LD -v 2>&1` in *\ \(GNU\ Binutils\)\ 2.19.5*) ;; *\ \(GNU\ Binutils\)\ 2.[[2-9]]*) ;; *\ \(GNU\ Binutils\)\ [[3-9]]*) ;; *) lt_use_gnu_ld_interface=yes ;; esac ;; *) lt_use_gnu_ld_interface=yes ;; esac fi if test "$lt_use_gnu_ld_interface" = yes; then # If archive_cmds runs LD, not CC, wlarc should be empty wlarc='${wl}' # Set some defaults for GNU ld with shared library support. These # are reset later if shared libraries are not supported. Putting them # here allows them to be overridden if necessary. runpath_var=LD_RUN_PATH _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' # ancient GNU ld didn't support --whole-archive et. al. if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else _LT_TAGVAR(whole_archive_flag_spec, $1)= fi supports_anon_versioning=no case `$LD -v 2>&1` in *GNU\ gold*) supports_anon_versioning=yes ;; *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11 *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... *\ 2.11.*) ;; # other 2.11 versions *) supports_anon_versioning=yes ;; esac # See if GNU ld supports shared libraries. case $host_os in aix[[3-9]]*) # On AIX/PPC, the GNU linker is very broken if test "$host_cpu" != ia64; then _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: the GNU linker, at least up to release 2.19, is reported *** to be unable to reliably create shared libraries on AIX. *** Therefore, libtool is disabling shared libraries support. If you *** really care for shared libraries, you may want to install binutils *** 2.20 or above, or modify your PATH so that a non-GNU linker is found. *** You will then need to restart the configuration process. _LT_EOF fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='' ;; m68k) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; cygwin* | mingw* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, # as there is no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(link_all_deplibs, $1)=yes ;; interix[[3-9]]*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) tmp_diet=no if test "$host_os" = linux-dietlibc; then case $cc_basename in diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) esac fi if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ && test "$tmp_diet" = no then tmp_addflag=' $pic_flag' tmp_sharedflag='-shared' case $cc_basename,$host_cpu in pgcc*) # Portland Group C compiler _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag' ;; pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group f77 and f90 compilers _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag -Mnomain' ;; ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 tmp_addflag=' -i_dynamic' ;; efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 tmp_addflag=' -i_dynamic -nofor_main' ;; ifc* | ifort*) # Intel Fortran compiler tmp_addflag=' -nofor_main' ;; lf95*) # Lahey Fortran 8.1 _LT_TAGVAR(whole_archive_flag_spec, $1)= tmp_sharedflag='--shared' ;; xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below) tmp_sharedflag='-qmkshrobj' tmp_addflag= ;; nvcc*) # Cuda Compiler Driver 2.2 _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes ;; esac case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C 5.9 _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes tmp_sharedflag='-G' ;; *Sun\ F*) # Sun Fortran 8.3 tmp_sharedflag='-G' ;; esac _LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi case $cc_basename in xlf* | bgf* | bgxlf* | mpixlf*) # IBM XL Fortran 10.1 on PPC cannot create shared libs itself _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' if test "x$supports_anon_versioning" = xyes; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' fi ;; esac else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' wlarc= else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' fi ;; solaris*) if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: The releases 2.8.* of the GNU linker cannot reliably *** create shared libraries on Solaris systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.9.1 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) case `$LD -v 2>&1` in *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*) _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not *** reliably create shared libraries on SCO systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.16.91.0.3 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF ;; *) # For security reasons, it is highly recommended that you always # use absolute paths for naming shared libraries, and exclude the # DT_RUNPATH tag from executables and libraries. But doing so # requires that you compile everything twice, which is a pain. if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; sunos4*) _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' wlarc= _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then runpath_var= _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= fi else # PORTME fill in a description of your system's linker (not GNU ld) case $host_os in aix3*) _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' # Note: this linker hardcodes the directories in LIBPATH if there # are no directories specified by -L. _LT_TAGVAR(hardcode_minus_L, $1)=yes if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then # Neither direct hardcoding nor static linking is supported with a # broken collect2. _LT_TAGVAR(hardcode_direct, $1)=unsupported fi ;; aix[[4-9]]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global # defined symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) for ld_flag in $LDFLAGS; do if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then aix_use_runtimelinking=yes break fi done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. _LT_TAGVAR(archive_cmds, $1)='' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(file_list_spec, $1)='${wl}-f,' if test "$GCC" = yes; then case $host_os in aix4.[[012]]|aix4.[[012]].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 _LT_TAGVAR(hardcode_direct, $1)=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)= fi ;; esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi _LT_TAGVAR(link_all_deplibs, $1)=no else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to export. _LT_TAGVAR(always_export_symbols, $1)=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. _LT_TAGVAR(allow_undefined_flag, $1)='-berok' # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' fi _LT_TAGVAR(archive_cmds_need_lc, $1)=yes # This is similar to how AIX traditionally builds its shared libraries. _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='' ;; m68k) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac ;; bsdi[[45]]*) _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic ;; cygwin* | mingw* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++. # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. case $cc_basename in cl*) # Native MSVC _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1,DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols' # Don't use ranlib _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # Assume MSVC wrapper _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' # The linker will automatically build a .lib file if we build a DLL. _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' # FIXME: Should let the user specify the lib program. _LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes ;; esac ;; darwin* | rhapsody*) _LT_DARWIN_LINKER_FEATURES($1) ;; dgux*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor # support. Future versions do this automatically, but an explicit c++rt0.o # does not break anything, and helps significantly (at the cost of a little # extra space). freebsd2.2*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # Unfortunately, older versions of FreeBSD 2 do not have this feature. freebsd2.*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. freebsd* | dragonfly*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; hpux9*) if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_direct, $1)=yes # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' ;; hpux10*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi if test "$with_gnu_ld" = no; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes fi ;; hpux11*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' ;; esac else case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) m4_if($1, [], [ # Older versions of the 11.00 compiler do not understand -b yet # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) _LT_LINKER_OPTION([if $CC understands -b], _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b], [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'], [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])], [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags']) ;; esac fi if test "$with_gnu_ld" = no; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: case $host_cpu in hppa*64*|ia64*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac fi ;; irix5* | irix6* | nonstopux*) if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' # Try to use the -exported_symbol ld option, if it does not # work, assume that -exports_file does not work either and # implicitly export all symbols. # This should be the same for all languages, so no per-tag cache variable. AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol], [lt_cv_irix_exported_symbol], [save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" AC_LINK_IFELSE( [AC_LANG_SOURCE( [AC_LANG_CASE([C], [[int foo (void) { return 0; }]], [C++], [[int foo (void) { return 0; }]], [Fortran 77], [[ subroutine foo end]], [Fortran], [[ subroutine foo end]])])], [lt_cv_irix_exported_symbol=yes], [lt_cv_irix_exported_symbol=no]) LDFLAGS="$save_LDFLAGS"]) if test "$lt_cv_irix_exported_symbol" = yes; then _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' fi else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(inherit_rpath, $1)=yes _LT_TAGVAR(link_all_deplibs, $1)=yes ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out else _LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; newsos6) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *nto* | *qnx*) ;; openbsd*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=yes if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' else case $host_os in openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' ;; esac fi else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; os2*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' ;; osf3*) if test "$GCC" = yes; then _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: ;; osf4* | osf5*) # as osf3* with the addition of -msym flag if test "$GCC" = yes; then _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' else _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' # Both c and cxx compiler support -rpath directly _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_separator, $1)=: ;; solaris*) _LT_TAGVAR(no_undefined_flag, $1)=' -z defs' if test "$GCC" = yes; then wlarc='${wl}' _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' else case `$CC -V 2>&1` in *"Compilers 5.0"*) wlarc='' _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' ;; *) wlarc='${wl}' _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' ;; esac fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. GCC discards it without `$wl', # but is careful enough not to reorder. # Supported since Solaris 2.6 (maybe 2.5.1?) if test "$GCC" = yes; then _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' else _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' fi ;; esac _LT_TAGVAR(link_all_deplibs, $1)=yes ;; sunos4*) if test "x$host_vendor" = xsequent; then # Use $CC to link under sequent, because it throws in some extra .o # files that make .init and .fini sections work. _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; sysv4) case $host_vendor in sni) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true??? ;; siemens) ## LD is ld it makes a PLAMLIB ## CC just makes a GrossModule. _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs' _LT_TAGVAR(hardcode_direct, $1)=no ;; motorola) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie ;; esac runpath_var='LD_RUN_PATH' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; sysv4.3*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var=LD_RUN_PATH hardcode_runpath_var=yes _LT_TAGVAR(ld_shlibs, $1)=yes fi ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; uts4*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(ld_shlibs, $1)=no ;; esac if test x$host_vendor = xsni; then case $host in sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym' ;; esac fi fi ]) AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no _LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld _LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl _LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl _LT_DECL([], [extract_expsyms_cmds], [2], [The commands to extract the exported symbol list from a shared archive]) # # Do we need to explicitly link libc? # case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in x|xyes) # Assume -lc should be added _LT_TAGVAR(archive_cmds_need_lc, $1)=yes if test "$enable_shared" = yes && test "$GCC" = yes; then case $_LT_TAGVAR(archive_cmds, $1) in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. AC_CACHE_CHECK([whether -lc should be explicitly linked in], [lt_cv_]_LT_TAGVAR(archive_cmds_need_lc, $1), [$RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if AC_TRY_EVAL(ac_compile) 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1) compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1) _LT_TAGVAR(allow_undefined_flag, $1)= if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) then lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=no else lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=yes fi _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* ]) _LT_TAGVAR(archive_cmds_need_lc, $1)=$lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1) ;; esac fi ;; esac _LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0], [Whether or not to add -lc for building shared libraries]) _LT_TAGDECL([allow_libtool_libs_with_static_runtimes], [enable_shared_with_static_runtimes], [0], [Whether or not to disallow shared libs when runtime libs are static]) _LT_TAGDECL([], [export_dynamic_flag_spec], [1], [Compiler flag to allow reflexive dlopens]) _LT_TAGDECL([], [whole_archive_flag_spec], [1], [Compiler flag to generate shared objects directly from archives]) _LT_TAGDECL([], [compiler_needs_object], [1], [Whether the compiler copes with passing no objects directly]) _LT_TAGDECL([], [old_archive_from_new_cmds], [2], [Create an old-style archive from a shared archive]) _LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2], [Create a temporary old-style archive to link instead of a shared archive]) _LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive]) _LT_TAGDECL([], [archive_expsym_cmds], [2]) _LT_TAGDECL([], [module_cmds], [2], [Commands used to build a loadable module if different from building a shared archive.]) _LT_TAGDECL([], [module_expsym_cmds], [2]) _LT_TAGDECL([], [with_gnu_ld], [1], [Whether we are building with GNU ld or not]) _LT_TAGDECL([], [allow_undefined_flag], [1], [Flag that allows shared libraries with undefined symbols to be built]) _LT_TAGDECL([], [no_undefined_flag], [1], [Flag that enforces no undefined symbols]) _LT_TAGDECL([], [hardcode_libdir_flag_spec], [1], [Flag to hardcode $libdir into a binary during linking. This must work even if $libdir does not exist]) _LT_TAGDECL([], [hardcode_libdir_separator], [1], [Whether we need a single "-rpath" flag with a separated argument]) _LT_TAGDECL([], [hardcode_direct], [0], [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_direct_absolute], [0], [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the resulting binary and the resulting library dependency is "absolute", i.e impossible to change by setting ${shlibpath_var} if the library is relocated]) _LT_TAGDECL([], [hardcode_minus_L], [0], [Set to "yes" if using the -LDIR flag during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_shlibpath_var], [0], [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_automatic], [0], [Set to "yes" if building a shared library automatically hardcodes DIR into the library and all subsequent libraries and executables linked against it]) _LT_TAGDECL([], [inherit_rpath], [0], [Set to yes if linker adds runtime paths of dependent libraries to runtime path list]) _LT_TAGDECL([], [link_all_deplibs], [0], [Whether libtool must link a program against all its dependency libraries]) _LT_TAGDECL([], [always_export_symbols], [0], [Set to "yes" if exported symbols are required]) _LT_TAGDECL([], [export_symbols_cmds], [2], [The commands to list exported symbols]) _LT_TAGDECL([], [exclude_expsyms], [1], [Symbols that should not be listed in the preloaded symbols]) _LT_TAGDECL([], [include_expsyms], [1], [Symbols that must always be exported]) _LT_TAGDECL([], [prelink_cmds], [2], [Commands necessary for linking programs (against libraries) with templates]) _LT_TAGDECL([], [postlink_cmds], [2], [Commands necessary for finishing linking programs]) _LT_TAGDECL([], [file_list_spec], [1], [Specify filename containing input files]) dnl FIXME: Not yet implemented dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1], dnl [Compiler flag to generate thread safe objects]) ])# _LT_LINKER_SHLIBS # _LT_LANG_C_CONFIG([TAG]) # ------------------------ # Ensure that the configuration variables for a C compiler are suitably # defined. These variables are subsequently used by _LT_CONFIG to write # the compiler configuration to `libtool'. m4_defun([_LT_LANG_C_CONFIG], [m4_require([_LT_DECL_EGREP])dnl lt_save_CC="$CC" AC_LANG_PUSH(C) # Source file extension for C test sources. ac_ext=c # Object file extension for compiled C test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(){return(0);}' _LT_TAG_COMPILER # Save the default compiler, since it gets overwritten when the other # tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. compiler_DEFAULT=$CC # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) LT_SYS_DLOPEN_SELF _LT_CMD_STRIPLIB # Report which library types will actually be built AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_CONFIG($1) fi AC_LANG_POP CC="$lt_save_CC" ])# _LT_LANG_C_CONFIG # _LT_LANG_CXX_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for a C++ compiler are suitably # defined. These variables are subsequently used by _LT_CONFIG to write # the compiler configuration to `libtool'. m4_defun([_LT_LANG_CXX_CONFIG], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_PATH_MANIFEST_TOOL])dnl if test -n "$CXX" && ( test "X$CXX" != "Xno" && ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || (test "X$CXX" != "Xg++"))) ; then AC_PROG_CXXCPP else _lt_caught_CXX_error=yes fi AC_LANG_PUSH(C++) _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(compiler_needs_object, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for C++ test sources. ac_ext=cpp # Object file extension for compiled C++ test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the CXX compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_caught_CXX_error" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_LD=$LD lt_save_GCC=$GCC GCC=$GXX lt_save_with_gnu_ld=$with_gnu_ld lt_save_path_LD=$lt_cv_path_LD if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx else $as_unset lt_cv_prog_gnu_ld fi if test -n "${lt_cv_path_LDCXX+set}"; then lt_cv_path_LD=$lt_cv_path_LDCXX else $as_unset lt_cv_path_LD fi test -z "${LDCXX+set}" || LD=$LDCXX CC=${CXX-"c++"} CFLAGS=$CXXFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) if test -n "$compiler"; then # We don't want -fno-exception when compiling C++ code, so set the # no_builtin_flag separately if test "$GXX" = yes; then _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' else _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= fi if test "$GXX" = yes; then # Set up default GNU C++ configuration LT_PATH_LD # Check if GNU C++ uses GNU ld as the underlying linker, since the # archiving commands below assume that GNU ld is being used. if test "$with_gnu_ld" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' # If archive_cmds runs LD, not CC, wlarc should be empty # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to # investigate it a little bit more. (MM) wlarc='${wl}' # ancient GNU ld didn't support --whole-archive et. al. if eval "`$CC -print-prog-name=ld` --help 2>&1" | $GREP 'no-whole-archive' > /dev/null; then _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else _LT_TAGVAR(whole_archive_flag_spec, $1)= fi else with_gnu_ld=no wlarc= # A generic and very simple default shared library creation # command for GNU C++ for the case where it uses the native # linker, instead of GNU ld. If possible, this setting should # overridden to take advantage of the native linker features on # the platform it is being used on. _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' fi # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else GXX=no with_gnu_ld=no wlarc= fi # PORTME: fill in a description of your system's C++ link characteristics AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) _LT_TAGVAR(ld_shlibs, $1)=yes case $host_os in aix3*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aix[[4-9]]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) for ld_flag in $LDFLAGS; do case $ld_flag in *-brtl*) aix_use_runtimelinking=yes break ;; esac done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. _LT_TAGVAR(archive_cmds, $1)='' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(file_list_spec, $1)='${wl}-f,' if test "$GXX" = yes; then case $host_os in aix4.[[012]]|aix4.[[012]].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 _LT_TAGVAR(hardcode_direct, $1)=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)= fi esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to # export. _LT_TAGVAR(always_export_symbols, $1)=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. _LT_TAGVAR(allow_undefined_flag, $1)='-berok' # Determine the default libpath from the value encoded in an empty # executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' fi _LT_TAGVAR(archive_cmds_need_lc, $1)=yes # This is similar to how AIX traditionally builds its shared # libraries. _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; chorus*) case $cc_basename in *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; cygwin* | mingw* | pw32* | cegcc*) case $GXX,$cc_basename in ,cl* | no,cl*) # Native MSVC # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes # Don't use ranlib _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ func_to_tool_file "$lt_outputfile"~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # g++ # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, # as there is no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; darwin* | rhapsody*) _LT_DARWIN_LINKER_FEATURES($1) ;; dgux*) case $cc_basename in ec++*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; ghcx*) # Green Hills C++ Compiler # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; freebsd2.*) # C++ shared libraries reported to be fairly broken before # switch to ELF _LT_TAGVAR(ld_shlibs, $1)=no ;; freebsd-elf*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; freebsd* | dragonfly*) # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF # conventions _LT_TAGVAR(ld_shlibs, $1)=yes ;; haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(link_all_deplibs, $1)=yes ;; hpux9*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, # but as the default # location of the library. case $cc_basename in CC*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aCC*) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; hpux10*|hpux11*) if test $with_gnu_ld = no; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: case $host_cpu in hppa*64*|ia64*) ;; *) _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' ;; esac fi case $host_cpu in hppa*64*|ia64*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, # but as the default # location of the library. ;; esac case $cc_basename in CC*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aCC*) case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then if test $with_gnu_ld = no; then case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac fi else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; interix[[3-9]]*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; irix5* | irix6*) case $cc_basename in CC*) # SGI C++ _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' # Archives containing C++ object files must be created using # "CC -ar", where "CC" is the IRIX C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs' ;; *) if test "$GXX" = yes; then if test "$with_gnu_ld" = no; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib' fi fi _LT_TAGVAR(link_all_deplibs, $1)=yes ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(inherit_rpath, $1)=yes ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' # Archives containing C++ object files must be created using # "CC -Bstatic", where "CC" is the KAI C++ compiler. _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; icpc* | ecpc* ) # Intel C++ with_gnu_ld=yes # version 8.0 and above of icpc choke on multiply defined symbols # if we add $predep_objects and $postdep_objects, however 7.1 and # earlier do not add the objects themselves. case `$CC -V 2>&1` in *"Version 7."*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; *) # Version 8.0 or newer tmp_idyn= case $host_cpu in ia64*) tmp_idyn=' -i_dynamic';; esac _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; esac _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' ;; pgCC* | pgcpp*) # Portland Group C++ compiler case `$CC -V` in *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*) _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~ compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"' _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~ $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~ $RANLIB $oldlib' _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; *) # Version 6 and above use weak symbols _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' ;; cxx*) # Compaq C++ _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' runpath_var=LD_RUN_PATH _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed' ;; xl* | mpixl* | bgxl*) # IBM XL 8.0 on PPC, with GNU ld _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes # Not sure whether something based on # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 # would be better. output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' ;; esac ;; esac ;; lynxos*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; m88k*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; mvs*) case $cc_basename in cxx*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' wlarc= _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no fi # Workaround some broken pre-1.5 toolchains output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' ;; *nto* | *qnx*) _LT_TAGVAR(ld_shlibs, $1)=yes ;; openbsd2*) # C++ shared libraries are fairly broken _LT_TAGVAR(ld_shlibs, $1)=no ;; openbsd*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' fi output_verbose_link_cmd=func_echo_all else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Archives containing C++ object files must be created using # the KAI C++ compiler. case $host in osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;; esac ;; RCC*) # Rational C++ 2.4.1 # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; cxx*) case $host in osf3*) _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' ;; *) _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ echo "-hidden">> $lib.exp~ $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~ $RM $lib.exp' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' ;; esac _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes && test "$with_gnu_ld" = no; then _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' case $host in osf3*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; psos*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; lcc*) # Lucid # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ _LT_TAGVAR(archive_cmds_need_lc,$1)=yes _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. # Supported since Solaris 2.6 (maybe 2.5.1?) _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' ;; esac _LT_TAGVAR(link_all_deplibs, $1)=yes output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' ;; gcx*) # Green Hills C++ Compiler _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' # The C++ compiler must be used to create the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs' ;; *) # GNU C++ compiler with Solaris linker if test "$GXX" = yes && test "$with_gnu_ld" = no; then _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs' if $CC --version | $GREP -v '^2\.7' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # g++ 2.7 appears to require `-G' NOT `-shared' on this # platform. _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir' case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' ;; esac fi ;; esac ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var='LD_RUN_PATH' case $cc_basename in CC*) _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' runpath_var='LD_RUN_PATH' case $cc_basename in CC*) _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~ '"$_LT_TAGVAR(old_archive_cmds, $1)" _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~ '"$_LT_TAGVAR(reload_cmds, $1)" ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; vxworks*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no _LT_TAGVAR(GCC, $1)="$GXX" _LT_TAGVAR(LD, $1)="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_SYS_HIDDEN_LIBDEPS($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS LDCXX=$LD LD=$lt_save_LD GCC=$lt_save_GCC with_gnu_ld=$lt_save_with_gnu_ld lt_cv_path_LDCXX=$lt_cv_path_LD lt_cv_path_LD=$lt_save_path_LD lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld fi # test "$_lt_caught_CXX_error" != yes AC_LANG_POP ])# _LT_LANG_CXX_CONFIG # _LT_FUNC_STRIPNAME_CNF # ---------------------- # func_stripname_cnf prefix suffix name # strip PREFIX and SUFFIX off of NAME. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). # # This function is identical to the (non-XSI) version of func_stripname, # except this one can be used by m4 code that may be executed by configure, # rather than the libtool script. m4_defun([_LT_FUNC_STRIPNAME_CNF],[dnl AC_REQUIRE([_LT_DECL_SED]) AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH]) func_stripname_cnf () { case ${2} in .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; esac } # func_stripname_cnf ])# _LT_FUNC_STRIPNAME_CNF # _LT_SYS_HIDDEN_LIBDEPS([TAGNAME]) # --------------------------------- # Figure out "hidden" library dependencies from verbose # compiler output when linking a shared library. # Parse the compiler output and extract the necessary # objects, libraries and library flags. m4_defun([_LT_SYS_HIDDEN_LIBDEPS], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl AC_REQUIRE([_LT_FUNC_STRIPNAME_CNF])dnl # Dependencies to place before and after the object being linked: _LT_TAGVAR(predep_objects, $1)= _LT_TAGVAR(postdep_objects, $1)= _LT_TAGVAR(predeps, $1)= _LT_TAGVAR(postdeps, $1)= _LT_TAGVAR(compiler_lib_search_path, $1)= dnl we can't use the lt_simple_compile_test_code here, dnl because it contains code intended for an executable, dnl not a library. It's possible we should let each dnl tag define a new lt_????_link_test_code variable, dnl but it's only used here... m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF int a; void foo (void) { a = 0; } _LT_EOF ], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF class Foo { public: Foo (void) { a = 0; } private: int a; }; _LT_EOF ], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF subroutine foo implicit none integer*4 a a=0 return end _LT_EOF ], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF subroutine foo implicit none integer a a=0 return end _LT_EOF ], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF public class foo { private int a; public void bar (void) { a = 0; } }; _LT_EOF ], [$1], [GO], [cat > conftest.$ac_ext <<_LT_EOF package foo func foo() { } _LT_EOF ]) _lt_libdeps_save_CFLAGS=$CFLAGS case "$CC $CFLAGS " in #( *\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;; *\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;; *\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;; esac dnl Parse the compiler output and extract the necessary dnl objects, libraries and library flags. if AC_TRY_EVAL(ac_compile); then # Parse the compiler output and extract the necessary # objects, libraries and library flags. # Sentinel used to keep track of whether or not we are before # the conftest object file. pre_test_object_deps_done=no for p in `eval "$output_verbose_link_cmd"`; do case ${prev}${p} in -L* | -R* | -l*) # Some compilers place space between "-{L,R}" and the path. # Remove the space. if test $p = "-L" || test $p = "-R"; then prev=$p continue fi # Expand the sysroot to ease extracting the directories later. if test -z "$prev"; then case $p in -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;; -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;; -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;; esac fi case $p in =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;; esac if test "$pre_test_object_deps_done" = no; then case ${prev} in -L | -R) # Internal compiler library paths should come after those # provided the user. The postdeps already come after the # user supplied libs so there is no need to process them. if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}" else _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}" fi ;; # The "-l" case would never come before the object being # linked, so don't bother handling this case. esac else if test -z "$_LT_TAGVAR(postdeps, $1)"; then _LT_TAGVAR(postdeps, $1)="${prev}${p}" else _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}" fi fi prev= ;; *.lto.$objext) ;; # Ignore GCC LTO objects *.$objext) # This assumes that the test object file only shows up # once in the compiler output. if test "$p" = "conftest.$objext"; then pre_test_object_deps_done=yes continue fi if test "$pre_test_object_deps_done" = no; then if test -z "$_LT_TAGVAR(predep_objects, $1)"; then _LT_TAGVAR(predep_objects, $1)="$p" else _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p" fi else if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then _LT_TAGVAR(postdep_objects, $1)="$p" else _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p" fi fi ;; *) ;; # Ignore the rest. esac done # Clean up. rm -f a.out a.exe else echo "libtool.m4: error: problem compiling $1 test program" fi $RM -f confest.$objext CFLAGS=$_lt_libdeps_save_CFLAGS # PORTME: override above test on systems where it is broken m4_if([$1], [CXX], [case $host_os in interix[[3-9]]*) # Interix 3.5 installs completely hosed .la files for C++, so rather than # hack all around it, let's just trust "g++" to DTRT. _LT_TAGVAR(predep_objects,$1)= _LT_TAGVAR(postdep_objects,$1)= _LT_TAGVAR(postdeps,$1)= ;; linux*) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac if test "$solaris_use_stlport4" != yes; then _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' fi ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac # Adding this requires a known-good setup of shared libraries for # Sun compiler versions before 5.6, else PIC objects from an old # archive will be linked into the output, leading to subtle bugs. if test "$solaris_use_stlport4" != yes; then _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' fi ;; esac ;; esac ]) case " $_LT_TAGVAR(postdeps, $1) " in *" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; esac _LT_TAGVAR(compiler_lib_search_dirs, $1)= if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'` fi _LT_TAGDECL([], [compiler_lib_search_dirs], [1], [The directories searched by this compiler when creating a shared library]) _LT_TAGDECL([], [predep_objects], [1], [Dependencies to place before and after the objects being linked to create a shared library]) _LT_TAGDECL([], [postdep_objects], [1]) _LT_TAGDECL([], [predeps], [1]) _LT_TAGDECL([], [postdeps], [1]) _LT_TAGDECL([], [compiler_lib_search_path], [1], [The library search path used internally by the compiler when linking a shared library]) ])# _LT_SYS_HIDDEN_LIBDEPS # _LT_LANG_F77_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for a Fortran 77 compiler are # suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_F77_CONFIG], [AC_LANG_PUSH(Fortran 77) if test -z "$F77" || test "X$F77" = "Xno"; then _lt_disable_F77=yes fi _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for f77 test sources. ac_ext=f # Object file extension for compiled f77 test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the F77 compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_disable_F77" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="\ subroutine t return end " # Code to be used in simple link tests lt_simple_link_test_code="\ program t end " # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC="$CC" lt_save_GCC=$GCC lt_save_CFLAGS=$CFLAGS CC=${F77-"f77"} CFLAGS=$FFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) GCC=$G77 if test -n "$compiler"; then AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_TAGVAR(GCC, $1)="$G77" _LT_TAGVAR(LD, $1)="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" GCC=$lt_save_GCC CC="$lt_save_CC" CFLAGS="$lt_save_CFLAGS" fi # test "$_lt_disable_F77" != yes AC_LANG_POP ])# _LT_LANG_F77_CONFIG # _LT_LANG_FC_CONFIG([TAG]) # ------------------------- # Ensure that the configuration variables for a Fortran compiler are # suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_FC_CONFIG], [AC_LANG_PUSH(Fortran) if test -z "$FC" || test "X$FC" = "Xno"; then _lt_disable_FC=yes fi _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for fc test sources. ac_ext=${ac_fc_srcext-f} # Object file extension for compiled fc test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the FC compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_disable_FC" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="\ subroutine t return end " # Code to be used in simple link tests lt_simple_link_test_code="\ program t end " # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC="$CC" lt_save_GCC=$GCC lt_save_CFLAGS=$CFLAGS CC=${FC-"f95"} CFLAGS=$FCFLAGS compiler=$CC GCC=$ac_cv_fc_compiler_gnu _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) if test -n "$compiler"; then AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu" _LT_TAGVAR(LD, $1)="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_SYS_HIDDEN_LIBDEPS($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS fi # test "$_lt_disable_FC" != yes AC_LANG_POP ])# _LT_LANG_FC_CONFIG # _LT_LANG_GCJ_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for the GNU Java Compiler compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_GCJ_CONFIG], [AC_REQUIRE([LT_PROG_GCJ])dnl AC_LANG_SAVE # Source file extension for Java test sources. ac_ext=java # Object file extension for compiled Java test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="class foo {}" # Code to be used in simple link tests lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC=yes CC=${GCJ-"gcj"} CFLAGS=$GCJFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_TAGVAR(LD, $1)="$LD" _LT_CC_BASENAME([$compiler]) # GCJ did not exist at the time GCC didn't implicitly link libc in. _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi AC_LANG_RESTORE GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_GCJ_CONFIG # _LT_LANG_GO_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for the GNU Go compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_GO_CONFIG], [AC_REQUIRE([LT_PROG_GO])dnl AC_LANG_SAVE # Source file extension for Go test sources. ac_ext=go # Object file extension for compiled Go test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="package main; func main() { }" # Code to be used in simple link tests lt_simple_link_test_code='package main; func main() { }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC=yes CC=${GOC-"gccgo"} CFLAGS=$GOFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_TAGVAR(LD, $1)="$LD" _LT_CC_BASENAME([$compiler]) # Go did not exist at the time GCC didn't implicitly link libc in. _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi AC_LANG_RESTORE GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_GO_CONFIG # _LT_LANG_RC_CONFIG([TAG]) # ------------------------- # Ensure that the configuration variables for the Windows resource compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_RC_CONFIG], [AC_REQUIRE([LT_PROG_RC])dnl AC_LANG_SAVE # Source file extension for RC test sources. ac_ext=rc # Object file extension for compiled RC test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }' # Code to be used in simple link tests lt_simple_link_test_code="$lt_simple_compile_test_code" # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC="$CC" lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC= CC=${RC-"windres"} CFLAGS= compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes if test -n "$compiler"; then : _LT_CONFIG($1) fi GCC=$lt_save_GCC AC_LANG_RESTORE CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_RC_CONFIG # LT_PROG_GCJ # ----------- AC_DEFUN([LT_PROG_GCJ], [m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ], [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ], [AC_CHECK_TOOL(GCJ, gcj,) test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2" AC_SUBST(GCJFLAGS)])])[]dnl ]) # Old name: AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_GCJ], []) # LT_PROG_GO # ---------- AC_DEFUN([LT_PROG_GO], [AC_CHECK_TOOL(GOC, gccgo,) ]) # LT_PROG_RC # ---------- AC_DEFUN([LT_PROG_RC], [AC_CHECK_TOOL(RC, windres,) ]) # Old name: AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_RC], []) # _LT_DECL_EGREP # -------------- # If we don't have a new enough Autoconf to choose the best grep # available, choose the one first in the user's PATH. m4_defun([_LT_DECL_EGREP], [AC_REQUIRE([AC_PROG_EGREP])dnl AC_REQUIRE([AC_PROG_FGREP])dnl test -z "$GREP" && GREP=grep _LT_DECL([], [GREP], [1], [A grep program that handles long lines]) _LT_DECL([], [EGREP], [1], [An ERE matcher]) _LT_DECL([], [FGREP], [1], [A literal string matcher]) dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too AC_SUBST([GREP]) ]) # _LT_DECL_OBJDUMP # -------------- # If we don't have a new enough Autoconf to choose the best objdump # available, choose the one first in the user's PATH. m4_defun([_LT_DECL_OBJDUMP], [AC_CHECK_TOOL(OBJDUMP, objdump, false) test -z "$OBJDUMP" && OBJDUMP=objdump _LT_DECL([], [OBJDUMP], [1], [An object symbol dumper]) AC_SUBST([OBJDUMP]) ]) # _LT_DECL_DLLTOOL # ---------------- # Ensure DLLTOOL variable is set. m4_defun([_LT_DECL_DLLTOOL], [AC_CHECK_TOOL(DLLTOOL, dlltool, false) test -z "$DLLTOOL" && DLLTOOL=dlltool _LT_DECL([], [DLLTOOL], [1], [DLL creation program]) AC_SUBST([DLLTOOL]) ]) # _LT_DECL_SED # ------------ # Check for a fully-functional sed program, that truncates # as few characters as possible. Prefer GNU sed if found. m4_defun([_LT_DECL_SED], [AC_PROG_SED test -z "$SED" && SED=sed Xsed="$SED -e 1s/^X//" _LT_DECL([], [SED], [1], [A sed program that does not truncate output]) _LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"], [Sed that helps us avoid accidentally triggering echo(1) options like -n]) ])# _LT_DECL_SED m4_ifndef([AC_PROG_SED], [ ############################################################ # NOTE: This macro has been submitted for inclusion into # # GNU Autoconf as AC_PROG_SED. When it is available in # # a released version of Autoconf we should remove this # # macro and use it instead. # ############################################################ m4_defun([AC_PROG_SED], [AC_MSG_CHECKING([for a sed that does not truncate output]) AC_CACHE_VAL(lt_cv_path_SED, [# Loop through the user's path and test for sed and gsed. # Then use that list of sed's as ones to test for truncation. as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for lt_ac_prog in sed gsed; do for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" fi done done done IFS=$as_save_IFS lt_ac_max=0 lt_ac_count=0 # Add /usr/xpg4/bin/sed as it is typically found on Solaris # along with /bin/sed that truncates output. for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do test ! -f $lt_ac_sed && continue cat /dev/null > conftest.in lt_ac_count=0 echo $ECHO_N "0123456789$ECHO_C" >conftest.in # Check for GNU sed and select it if it is found. if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then lt_cv_path_SED=$lt_ac_sed break fi while true; do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo >>conftest.nl $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break cmp -s conftest.out conftest.nl || break # 10000 chars as input seems more than enough test $lt_ac_count -gt 10 && break lt_ac_count=`expr $lt_ac_count + 1` if test $lt_ac_count -gt $lt_ac_max; then lt_ac_max=$lt_ac_count lt_cv_path_SED=$lt_ac_sed fi done done ]) SED=$lt_cv_path_SED AC_SUBST([SED]) AC_MSG_RESULT([$SED]) ])#AC_PROG_SED ])#m4_ifndef # Old name: AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_SED], []) # _LT_CHECK_SHELL_FEATURES # ------------------------ # Find out whether the shell is Bourne or XSI compatible, # or has some other useful features. m4_defun([_LT_CHECK_SHELL_FEATURES], [AC_MSG_CHECKING([whether the shell understands some XSI constructs]) # Try some XSI features xsi_shell=no ( _lt_dummy="a/b/c" test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \ = c,a/b,b/c, \ && eval 'test $(( 1 + 1 )) -eq 2 \ && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ && xsi_shell=yes AC_MSG_RESULT([$xsi_shell]) _LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell']) AC_MSG_CHECKING([whether the shell understands "+="]) lt_shell_append=no ( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \ >/dev/null 2>&1 \ && lt_shell_append=yes AC_MSG_RESULT([$lt_shell_append]) _LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append']) if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then lt_unset=unset else lt_unset=false fi _LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl # test EBCDIC or ASCII case `echo X|tr X '\101'` in A) # ASCII based system # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr lt_SP2NL='tr \040 \012' lt_NL2SP='tr \015\012 \040\040' ;; *) # EBCDIC based system lt_SP2NL='tr \100 \n' lt_NL2SP='tr \r\n \100\100' ;; esac _LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl _LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl ])# _LT_CHECK_SHELL_FEATURES # _LT_PROG_FUNCTION_REPLACE (FUNCNAME, REPLACEMENT-BODY) # ------------------------------------------------------ # In `$cfgfile', look for function FUNCNAME delimited by `^FUNCNAME ()$' and # '^} FUNCNAME ', and replace its body with REPLACEMENT-BODY. m4_defun([_LT_PROG_FUNCTION_REPLACE], [dnl { sed -e '/^$1 ()$/,/^} # $1 /c\ $1 ()\ {\ m4_bpatsubsts([$2], [$], [\\], [^\([ ]\)], [\\\1]) } # Extended-shell $1 implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: ]) # _LT_PROG_REPLACE_SHELLFNS # ------------------------- # Replace existing portable implementations of several shell functions with # equivalent extended shell implementations where those features are available.. m4_defun([_LT_PROG_REPLACE_SHELLFNS], [if test x"$xsi_shell" = xyes; then _LT_PROG_FUNCTION_REPLACE([func_dirname], [dnl case ${1} in */*) func_dirname_result="${1%/*}${2}" ;; * ) func_dirname_result="${3}" ;; esac]) _LT_PROG_FUNCTION_REPLACE([func_basename], [dnl func_basename_result="${1##*/}"]) _LT_PROG_FUNCTION_REPLACE([func_dirname_and_basename], [dnl case ${1} in */*) func_dirname_result="${1%/*}${2}" ;; * ) func_dirname_result="${3}" ;; esac func_basename_result="${1##*/}"]) _LT_PROG_FUNCTION_REPLACE([func_stripname], [dnl # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are # positional parameters, so assign one to ordinary parameter first. func_stripname_result=${3} func_stripname_result=${func_stripname_result#"${1}"} func_stripname_result=${func_stripname_result%"${2}"}]) _LT_PROG_FUNCTION_REPLACE([func_split_long_opt], [dnl func_split_long_opt_name=${1%%=*} func_split_long_opt_arg=${1#*=}]) _LT_PROG_FUNCTION_REPLACE([func_split_short_opt], [dnl func_split_short_opt_arg=${1#??} func_split_short_opt_name=${1%"$func_split_short_opt_arg"}]) _LT_PROG_FUNCTION_REPLACE([func_lo2o], [dnl case ${1} in *.lo) func_lo2o_result=${1%.lo}.${objext} ;; *) func_lo2o_result=${1} ;; esac]) _LT_PROG_FUNCTION_REPLACE([func_xform], [ func_xform_result=${1%.*}.lo]) _LT_PROG_FUNCTION_REPLACE([func_arith], [ func_arith_result=$(( $[*] ))]) _LT_PROG_FUNCTION_REPLACE([func_len], [ func_len_result=${#1}]) fi if test x"$lt_shell_append" = xyes; then _LT_PROG_FUNCTION_REPLACE([func_append], [ eval "${1}+=\\${2}"]) _LT_PROG_FUNCTION_REPLACE([func_append_quoted], [dnl func_quote_for_eval "${2}" dnl m4 expansion turns \\\\ into \\, and then the shell eval turns that into \ eval "${1}+=\\\\ \\$func_quote_for_eval_result"]) # Save a `func_append' function call where possible by direct use of '+=' sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: else # Save a `func_append' function call even when '+=' is not available sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$_lt_function_replace_fail" = x":"; then AC_MSG_WARN([Unable to substitute extended shell functions in $ofile]) fi ]) # _LT_PATH_CONVERSION_FUNCTIONS # ----------------------------- # Determine which file name conversion functions should be used by # func_to_host_file (and, implicitly, by func_to_host_path). These are needed # for certain cross-compile configurations and native mingw. m4_defun([_LT_PATH_CONVERSION_FUNCTIONS], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl AC_MSG_CHECKING([how to convert $build file names to $host format]) AC_CACHE_VAL(lt_cv_to_host_file_cmd, [case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 ;; esac ;; *-*-cygwin* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_noop ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin ;; esac ;; * ) # unhandled hosts (and "normal" native builds) lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac ]) to_host_file_cmd=$lt_cv_to_host_file_cmd AC_MSG_RESULT([$lt_cv_to_host_file_cmd]) _LT_DECL([to_host_file_cmd], [lt_cv_to_host_file_cmd], [0], [convert $build file names to $host format])dnl AC_MSG_CHECKING([how to convert $build file names to toolchain format]) AC_CACHE_VAL(lt_cv_to_tool_file_cmd, [#assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac ]) to_tool_file_cmd=$lt_cv_to_tool_file_cmd AC_MSG_RESULT([$lt_cv_to_tool_file_cmd]) _LT_DECL([to_tool_file_cmd], [lt_cv_to_tool_file_cmd], [0], [convert $build files to toolchain format])dnl ])# _LT_PATH_CONVERSION_FUNCTIONS sauerbraten-0.0.20130203.dfsg/enet/enet_dll.cbp0000644000175000017500000000440011377327351020613 0ustar vincentvincent sauerbraten-0.0.20130203.dfsg/enet/libenet.pc.in0000644000175000017500000000040411373036002020674 0ustar vincentvincentprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: @PACKAGE_NAME@ Description: Low-latency UDP networking library supporting optional reliability Version: @PACKAGE_VERSION@ Cflags: -I${includedir} Libs: -L${libdir} -lenet sauerbraten-0.0.20130203.dfsg/enet/ChangeLog0000644000175000017500000001261512061673417020116 0ustar vincentvincentENet 1.3.6 (December 11, 2012): * added support for intercept callback in ENetHost that can be used to process raw packets before ENet * added enet_socket_shutdown() for issuing shutdown on a socket * fixed enet_socket_connect() to not error on non-blocking connects * fixed bug in MTU negotiation during connections ENet 1.3.5 (July 31, 2012): * fixed bug in unreliable packet fragment queuing ENet 1.3.4 (May 29, 2012): * added enet_peer_ping_interval() for configuring per-peer ping intervals * added enet_peer_timeout() for configuring per-peer timeouts * added protocol packet size limits ENet 1.3.3 (June 28, 2011): * fixed bug with simultaneous disconnects not dispatching events ENet 1.3.2 (May 31, 2011): * added support for unreliable packet fragmenting via the packet flag ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT * fixed regression in unreliable packet queuing * added check against received port to limit some forms of IP-spoofing ENet 1.3.1 (February 10, 2011): * fixed bug in tracking of reliable data in transit * reliable data window size now scales with the throttle * fixed bug in fragment length calculation when checksums are used ENet 1.3.0 (June 5, 2010): * enet_host_create() now requires the channel limit to be specified as a parameter * enet_host_connect() now accepts a data parameter which is supplied to the receiving receiving host in the event data field for a connect event * added an adaptive order-2 PPM range coder as a built-in compressor option which can be set with enet_host_compress_with_range_coder() * added support for packet compression configurable with a callback * improved session number handling to not rely on the packet checksum field, saving 4 bytes per packet unless the checksum option is used * removed the dependence on the rand callback for session number handling Caveats: This version is not protocol compatible with the 1.2 series or earlier. The enet_host_connect and enet_host_create API functions require supplying additional parameters. ENet 1.2.5 (June 28, 2011): * fixed bug with simultaneous disconnects not dispatching events ENet 1.2.4 (May 31, 2011): * fixed regression in unreliable packet queuing * added check against received port to limit some forms of IP-spoofing ENet 1.2.3 (February 10, 2011): * fixed bug in tracking reliable data in transit ENet 1.2.2 (June 5, 2010): * checksum functionality is now enabled by setting a checksum callback inside ENetHost instead of being a configure script option * added totalSentData, totalSentPackets, totalReceivedData, and totalReceivedPackets counters inside ENetHost for getting usage statistics * added enet_host_channel_limit() for limiting the maximum number of channels allowed by connected peers * now uses dispatch queues for event dispatch rather than potentially unscalable array walking * added no_memory callback that is called when a malloc attempt fails, such that if no_memory returns rather than aborts (the default behavior), then the error is propagated to the return value of the API calls * now uses packed attribute for protocol structures on platforms with strange alignment rules * improved autoconf build system contributed by Nathan Brink allowing for easier building as a shared library Caveats: If you were using the compile-time option that enabled checksums, make sure to set the checksum callback inside ENetHost to enet_crc32 to regain the old behavior. The ENetCallbacks structure has added new fields, so make sure to clear the structure to zero before use if using enet_initialize_with_callbacks(). ENet 1.2.1 (November 12, 2009): * fixed bug that could cause disconnect events to be dropped * added thin wrapper around select() for portable usage * added ENET_SOCKOPT_REUSEADDR socket option * factored enet_socket_bind()/enet_socket_listen() out of enet_socket_create() * added contributed Code::Blocks build file ENet 1.2 (February 12, 2008): * fixed bug in VERIFY_CONNECT acknowledgement that could cause connect attempts to occasionally timeout * fixed acknowledgements to check both the outgoing and sent queues when removing acknowledged packets * fixed accidental bit rot in the MSVC project file * revised sequence number overflow handling to address some possible disconnect bugs * added enet_host_check_events() for getting only local queued events * factored out socket option setting into enet_socket_set_option() so that socket options are now set separately from enet_socket_create() Caveats: While this release is superficially protocol compatible with 1.1, differences in the sequence number overflow handling can potentially cause random disconnects. ENet 1.1 (June 6, 2007): * optional CRC32 just in case someone needs a stronger checksum than UDP provides (--enable-crc32 configure option) * the size of packet headers are half the size they used to be (so less overhead when sending small packets) * enet_peer_disconnect_later() that waits till all queued outgoing packets get sent before issuing an actual disconnect * freeCallback field in individual packets for notification of when a packet is about to be freed * ENET_PACKET_FLAG_NO_ALLOCATE for supplying pre-allocated data to a packet (can be used in concert with freeCallback to support some custom allocation schemes that the normal memory allocation callbacks would normally not allow) * enet_address_get_host_ip() for printing address numbers * promoted the enet_socket_*() functions to be part of the API now * a few stability/crash fixes sauerbraten-0.0.20130203.dfsg/enet/win32.c0000644000175000017500000002107412061673417017451 0ustar vincentvincent/** @file win32.c @brief ENet Win32 system specific functions */ #ifdef WIN32 #include #define ENET_BUILDING_LIB 1 #include "enet/enet.h" static enet_uint32 timeBase = 0; int enet_initialize (void) { WORD versionRequested = MAKEWORD (1, 1); WSADATA wsaData; if (WSAStartup (versionRequested, & wsaData)) return -1; if (LOBYTE (wsaData.wVersion) != 1|| HIBYTE (wsaData.wVersion) != 1) { WSACleanup (); return -1; } timeBeginPeriod (1); return 0; } void enet_deinitialize (void) { timeEndPeriod (1); WSACleanup (); } enet_uint32 enet_time_get (void) { return (enet_uint32) timeGetTime () - timeBase; } void enet_time_set (enet_uint32 newTimeBase) { timeBase = (enet_uint32) timeGetTime () - newTimeBase; } int enet_address_set_host (ENetAddress * address, const char * name) { struct hostent * hostEntry; hostEntry = gethostbyname (name); if (hostEntry == NULL || hostEntry -> h_addrtype != AF_INET) { unsigned long host = inet_addr (name); if (host == INADDR_NONE) return -1; address -> host = host; return 0; } address -> host = * (enet_uint32 *) hostEntry -> h_addr_list [0]; return 0; } int enet_address_get_host_ip (const ENetAddress * address, char * name, size_t nameLength) { char * addr = inet_ntoa (* (struct in_addr *) & address -> host); if (addr == NULL) return -1; strncpy (name, addr, nameLength); return 0; } int enet_address_get_host (const ENetAddress * address, char * name, size_t nameLength) { struct in_addr in; struct hostent * hostEntry; in.s_addr = address -> host; hostEntry = gethostbyaddr ((char *) & in, sizeof (struct in_addr), AF_INET); if (hostEntry == NULL) return enet_address_get_host_ip (address, name, nameLength); strncpy (name, hostEntry -> h_name, nameLength); return 0; } int enet_socket_bind (ENetSocket socket, const ENetAddress * address) { struct sockaddr_in sin; memset (& sin, 0, sizeof (struct sockaddr_in)); sin.sin_family = AF_INET; if (address != NULL) { sin.sin_port = ENET_HOST_TO_NET_16 (address -> port); sin.sin_addr.s_addr = address -> host; } else { sin.sin_port = 0; sin.sin_addr.s_addr = INADDR_ANY; } return bind (socket, (struct sockaddr *) & sin, sizeof (struct sockaddr_in)) == SOCKET_ERROR ? -1 : 0; } int enet_socket_listen (ENetSocket socket, int backlog) { return listen (socket, backlog < 0 ? SOMAXCONN : backlog) == SOCKET_ERROR ? -1 : 0; } ENetSocket enet_socket_create (ENetSocketType type) { return socket (PF_INET, type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0); } int enet_socket_set_option (ENetSocket socket, ENetSocketOption option, int value) { int result = SOCKET_ERROR; switch (option) { case ENET_SOCKOPT_NONBLOCK: { u_long nonBlocking = (u_long) value; result = ioctlsocket (socket, FIONBIO, & nonBlocking); break; } case ENET_SOCKOPT_BROADCAST: result = setsockopt (socket, SOL_SOCKET, SO_BROADCAST, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_REUSEADDR: result = setsockopt (socket, SOL_SOCKET, SO_REUSEADDR, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_RCVBUF: result = setsockopt (socket, SOL_SOCKET, SO_RCVBUF, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_SNDBUF: result = setsockopt (socket, SOL_SOCKET, SO_SNDBUF, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_RCVTIMEO: result = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_SNDTIMEO: result = setsockopt (socket, SOL_SOCKET, SO_SNDTIMEO, (char *) & value, sizeof (int)); break; default: break; } return result == SOCKET_ERROR ? -1 : 0; } int enet_socket_connect (ENetSocket socket, const ENetAddress * address) { struct sockaddr_in sin; int result; memset (& sin, 0, sizeof (struct sockaddr_in)); sin.sin_family = AF_INET; sin.sin_port = ENET_HOST_TO_NET_16 (address -> port); sin.sin_addr.s_addr = address -> host; result = connect (socket, (struct sockaddr *) & sin, sizeof (struct sockaddr_in)); if (result == SOCKET_ERROR && WSAGetLastError () != WSAEWOULDBLOCK) return -1; return 0; } ENetSocket enet_socket_accept (ENetSocket socket, ENetAddress * address) { SOCKET result; struct sockaddr_in sin; int sinLength = sizeof (struct sockaddr_in); result = accept (socket, address != NULL ? (struct sockaddr *) & sin : NULL, address != NULL ? & sinLength : NULL); if (result == INVALID_SOCKET) return ENET_SOCKET_NULL; if (address != NULL) { address -> host = (enet_uint32) sin.sin_addr.s_addr; address -> port = ENET_NET_TO_HOST_16 (sin.sin_port); } return result; } int enet_socket_shutdown (ENetSocket socket, ENetSocketShutdown how) { return shutdown (socket, (int) how) == SOCKET_ERROR ? -1 : 0; } void enet_socket_destroy (ENetSocket socket) { if (socket != INVALID_SOCKET) closesocket (socket); } int enet_socket_send (ENetSocket socket, const ENetAddress * address, const ENetBuffer * buffers, size_t bufferCount) { struct sockaddr_in sin; DWORD sentLength; if (address != NULL) { memset (& sin, 0, sizeof (struct sockaddr_in)); sin.sin_family = AF_INET; sin.sin_port = ENET_HOST_TO_NET_16 (address -> port); sin.sin_addr.s_addr = address -> host; } if (WSASendTo (socket, (LPWSABUF) buffers, (DWORD) bufferCount, & sentLength, 0, address != NULL ? (struct sockaddr *) & sin : NULL, address != NULL ? sizeof (struct sockaddr_in) : 0, NULL, NULL) == SOCKET_ERROR) { if (WSAGetLastError () == WSAEWOULDBLOCK) return 0; return -1; } return (int) sentLength; } int enet_socket_receive (ENetSocket socket, ENetAddress * address, ENetBuffer * buffers, size_t bufferCount) { INT sinLength = sizeof (struct sockaddr_in); DWORD flags = 0, recvLength; struct sockaddr_in sin; if (WSARecvFrom (socket, (LPWSABUF) buffers, (DWORD) bufferCount, & recvLength, & flags, address != NULL ? (struct sockaddr *) & sin : NULL, address != NULL ? & sinLength : NULL, NULL, NULL) == SOCKET_ERROR) { switch (WSAGetLastError ()) { case WSAEWOULDBLOCK: case WSAECONNRESET: return 0; } return -1; } if (flags & MSG_PARTIAL) return -1; if (address != NULL) { address -> host = (enet_uint32) sin.sin_addr.s_addr; address -> port = ENET_NET_TO_HOST_16 (sin.sin_port); } return (int) recvLength; } int enet_socketset_select (ENetSocket maxSocket, ENetSocketSet * readSet, ENetSocketSet * writeSet, enet_uint32 timeout) { struct timeval timeVal; timeVal.tv_sec = timeout / 1000; timeVal.tv_usec = (timeout % 1000) * 1000; return select (maxSocket + 1, readSet, writeSet, NULL, & timeVal); } int enet_socket_wait (ENetSocket socket, enet_uint32 * condition, enet_uint32 timeout) { fd_set readSet, writeSet; struct timeval timeVal; int selectCount; timeVal.tv_sec = timeout / 1000; timeVal.tv_usec = (timeout % 1000) * 1000; FD_ZERO (& readSet); FD_ZERO (& writeSet); if (* condition & ENET_SOCKET_WAIT_SEND) FD_SET (socket, & writeSet); if (* condition & ENET_SOCKET_WAIT_RECEIVE) FD_SET (socket, & readSet); selectCount = select (socket + 1, & readSet, & writeSet, NULL, & timeVal); if (selectCount < 0) return -1; * condition = ENET_SOCKET_WAIT_NONE; if (selectCount == 0) return 0; if (FD_ISSET (socket, & writeSet)) * condition |= ENET_SOCKET_WAIT_SEND; if (FD_ISSET (socket, & readSet)) * condition |= ENET_SOCKET_WAIT_RECEIVE; return 0; } #endif sauerbraten-0.0.20130203.dfsg/enet/Makefile.in0000644000175000017500000006436012061673417020415 0ustar vincentvincent# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = . DIST_COMMON = README $(am__configure_deps) $(enetinclude_HEADERS) \ $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(srcdir)/libenet.pc.in $(top_srcdir)/configure ChangeLog \ config.guess config.sub depcomp install-sh ltmain.sh missing ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ configure.lineno config.status.lineno mkinstalldirs = $(install_sh) -d CONFIG_CLEAN_FILES = libenet.pc CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(pkgconfigdir)" \ "$(DESTDIR)$(enetincludedir)" LTLIBRARIES = $(lib_LTLIBRARIES) libenet_la_LIBADD = am_libenet_la_OBJECTS = callbacks.lo compress.lo host.lo list.lo \ packet.lo peer.lo protocol.lo unix.lo win32.lo libenet_la_OBJECTS = $(am_libenet_la_OBJECTS) libenet_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(libenet_la_LDFLAGS) $(LDFLAGS) -o $@ DEFAULT_INCLUDES = -I.@am__isrc@ depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) CCLD = $(CC) LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ SOURCES = $(libenet_la_SOURCES) DIST_SOURCES = $(libenet_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DATA = $(nodist_pkgconfig_DATA) HEADERS = $(enetinclude_HEADERS) ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) distdir = $(PACKAGE)-$(VERSION) top_distdir = $(distdir) am__remove_distdir = \ if test -d "$(distdir)"; then \ find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ && rm -rf "$(distdir)" \ || { sleep 5 && rm -rf "$(distdir)"; }; \ else :; fi DIST_ARCHIVES = $(distdir).tar.gz GZIP_ENV = --best distuninstallcheck_listfiles = find . -type f -print am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' distcleancheck_listfiles = find . -type f -print ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ pkgconfigdir = $(libdir)/pkgconfig nodist_pkgconfig_DATA = libenet.pc enetincludedir = $(includedir)/enet enetinclude_HEADERS = \ include/enet/callbacks.h \ include/enet/enet.h \ include/enet/list.h \ include/enet/protocol.h \ include/enet/time.h \ include/enet/types.h \ include/enet/unix.h \ include/enet/utility.h \ include/enet/win32.h lib_LTLIBRARIES = libenet.la libenet_la_SOURCES = callbacks.c compress.c host.c list.c packet.c peer.c protocol.c unix.c win32.c # see info '(libtool) Updating version info' before making a release libenet_la_LDFLAGS = $(AM_LDFLAGS) -version-info 3:0:1 INCLUDES = -I$(top_srcdir)/include ACLOCAL_AMFLAGS = -Im4 all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj am--refresh: Makefile @: $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \ $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \ && exit 0; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ echo ' $(SHELL) ./config.status'; \ $(SHELL) ./config.status;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) $(SHELL) ./config.status --recheck $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) $(am__cd) $(srcdir) && $(AUTOCONF) $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) $(am__aclocal_m4_deps): libenet.pc: $(top_builddir)/config.status $(srcdir)/libenet.pc.in cd $(top_builddir) && $(SHELL) ./config.status $@ install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ test "$$dir" != "$$p" || dir=.; \ echo "rm -f \"$${dir}/so_locations\""; \ rm -f "$${dir}/so_locations"; \ done libenet.la: $(libenet_la_OBJECTS) $(libenet_la_DEPENDENCIES) $(EXTRA_libenet_la_DEPENDENCIES) $(libenet_la_LINK) -rpath $(libdir) $(libenet_la_OBJECTS) $(libenet_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/callbacks.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/compress.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/host.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/list.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/packet.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/peer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/protocol.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/unix.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/win32.Plo@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c $< .c.obj: @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs distclean-libtool: -rm -f libtool config.lt install-nodist_pkgconfigDATA: $(nodist_pkgconfig_DATA) @$(NORMAL_INSTALL) @list='$(nodist_pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(pkgconfigdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(pkgconfigdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(pkgconfigdir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(pkgconfigdir)" || exit $$?; \ done uninstall-nodist_pkgconfigDATA: @$(NORMAL_UNINSTALL) @list='$(nodist_pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(pkgconfigdir)'; $(am__uninstall_files_from_dir) install-enetincludeHEADERS: $(enetinclude_HEADERS) @$(NORMAL_INSTALL) @list='$(enetinclude_HEADERS)'; test -n "$(enetincludedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(enetincludedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(enetincludedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(enetincludedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(enetincludedir)" || exit $$?; \ done uninstall-enetincludeHEADERS: @$(NORMAL_UNINSTALL) @list='$(enetinclude_HEADERS)'; test -n "$(enetincludedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(enetincludedir)'; $(am__uninstall_files_from_dir) ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) $(am__remove_distdir) test -d "$(distdir)" || mkdir "$(distdir)" @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done -test -n "$(am__skip_mode_fix)" \ || find "$(distdir)" -type d ! -perm -755 \ -exec chmod u+rwx,go+rx {} \; -o \ ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ || chmod -R a+r "$(distdir)" dist-gzip: distdir tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz $(am__remove_distdir) dist-bzip2: distdir tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 $(am__remove_distdir) dist-lzip: distdir tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz $(am__remove_distdir) dist-lzma: distdir tardir=$(distdir) && $(am__tar) | lzma -9 -c >$(distdir).tar.lzma $(am__remove_distdir) dist-xz: distdir tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz $(am__remove_distdir) dist-tarZ: distdir tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z $(am__remove_distdir) dist-shar: distdir shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz $(am__remove_distdir) dist-zip: distdir -rm -f $(distdir).zip zip -rq $(distdir).zip $(distdir) $(am__remove_distdir) dist dist-all: distdir tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz $(am__remove_distdir) # This target untars the dist file and tries a VPATH configuration. Then # it guarantees that the distribution is self-contained by making another # tarfile. distcheck: dist case '$(DIST_ARCHIVES)' in \ *.tar.gz*) \ GZIP=$(GZIP_ENV) gzip -dc $(distdir).tar.gz | $(am__untar) ;;\ *.tar.bz2*) \ bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ *.tar.lzma*) \ lzma -dc $(distdir).tar.lzma | $(am__untar) ;;\ *.tar.lz*) \ lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ *.tar.xz*) \ xz -dc $(distdir).tar.xz | $(am__untar) ;;\ *.tar.Z*) \ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ *.shar.gz*) \ GZIP=$(GZIP_ENV) gzip -dc $(distdir).shar.gz | unshar ;;\ *.zip*) \ unzip $(distdir).zip ;;\ esac chmod -R a-w $(distdir); chmod u+w $(distdir) mkdir $(distdir)/_build mkdir $(distdir)/_inst chmod a-w $(distdir) test -d $(distdir)/_build || exit 0; \ dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ && am__cwd=`pwd` \ && $(am__cd) $(distdir)/_build \ && ../configure --srcdir=.. --prefix="$$dc_install_base" \ $(AM_DISTCHECK_CONFIGURE_FLAGS) \ $(DISTCHECK_CONFIGURE_FLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) dvi \ && $(MAKE) $(AM_MAKEFLAGS) check \ && $(MAKE) $(AM_MAKEFLAGS) install \ && $(MAKE) $(AM_MAKEFLAGS) installcheck \ && $(MAKE) $(AM_MAKEFLAGS) uninstall \ && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ distuninstallcheck \ && chmod -R a-w "$$dc_install_base" \ && ({ \ (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ } || { rm -rf "$$dc_destdir"; exit 1; }) \ && rm -rf "$$dc_destdir" \ && $(MAKE) $(AM_MAKEFLAGS) dist \ && rm -rf $(DIST_ARCHIVES) \ && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \ && cd "$$am__cwd" \ || exit 1 $(am__remove_distdir) @(echo "$(distdir) archives ready for distribution: "; \ list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' distuninstallcheck: @test -n '$(distuninstallcheck_dir)' || { \ echo 'ERROR: trying to run $@ with an empty' \ '$$(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ $(am__cd) '$(distuninstallcheck_dir)' || { \ echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left after uninstall:" ; \ if test -n "$(DESTDIR)"; then \ echo " (check DESTDIR support)"; \ fi ; \ $(distuninstallcheck_listfiles) ; \ exit 1; } >&2 distcleancheck: distclean @if test '$(srcdir)' = . ; then \ echo "ERROR: distcleancheck can only run from a VPATH build" ; \ exit 1 ; \ fi @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left in build directory after distclean:" ; \ $(distcleancheck_listfiles) ; \ exit 1; } >&2 check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) $(DATA) $(HEADERS) installdirs: for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(pkgconfigdir)" "$(DESTDIR)$(enetincludedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ mostlyclean-am distclean: distclean-am -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-libtool distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-enetincludeHEADERS \ install-nodist_pkgconfigDATA install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf $(top_srcdir)/autom4te.cache -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-enetincludeHEADERS uninstall-libLTLIBRARIES \ uninstall-nodist_pkgconfigDATA .MAKE: install-am install-strip .PHONY: CTAGS GTAGS all all-am am--refresh check check-am clean \ clean-generic clean-libLTLIBRARIES clean-libtool ctags dist \ dist-all dist-bzip2 dist-gzip dist-lzip dist-lzma dist-shar \ dist-tarZ dist-xz dist-zip distcheck distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distcleancheck distdir distuninstallcheck dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-enetincludeHEADERS install-exec install-exec-am \ install-html install-html-am install-info install-info-am \ install-libLTLIBRARIES install-man \ install-nodist_pkgconfigDATA install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags uninstall uninstall-am uninstall-enetincludeHEADERS \ uninstall-libLTLIBRARIES uninstall-nodist_pkgconfigDATA # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sauerbraten-0.0.20130203.dfsg/enet/design.txt0000644000175000017500000001327511164631435020356 0ustar vincentvincent* Why ENet? ENet evolved specifically as a UDP networking layer for the multiplayer first person shooter Cube. Cube necessitated low latency communcation with data sent out very frequently, so TCP was an unsuitable choice due to its high latency and stream orientation. UDP, however, lacks many sometimes necessary features from TCP such as reliability, sequencing, unrestricted packet sizes, and connection management. So UDP by itself was not suitable as a network protocol either. No suitable freely available networking libraries existed at the time of ENet's creation to fill this niche. UDP and TCP could have been used together in Cube to benefit somewhat from both of their features, however, the resulting combinations of protocols still leaves much to be desired. TCP lacks multiple streams of communication without resorting to opening many sockets and complicates delineation of packets due to its buffering behavior. UDP lacks sequencing, connection management, management of bandwidth resources, and imposes limitations on the size of packets. A significant investment is required to integrate these two protocols, and the end result is worse off in features and performance than the uniform protocol presented by ENet. ENet thus attempts to address these issues and provide a single, uniform protocol layered over UDP to the developer with the best features of UDP and TCP as well as some useful features neither provide, with a much cleaner integration than any resulting from a mixture of UDP and TCP. * Connection management ENet provides a simple connection interface over which to communicate with a foreign host. The liveness of the connection is actively monitored by pinging the foreign host at frequent intervals, and also monitors the network conditions from the local host to the foreign host such as the mean round trip time and packet loss in this fashion. * Sequencing Rather than a single byte stream that complicates the delineation of packets, ENet presents connections as multiple, properly sequenced packet streams that simplify the transfer of various types of data. ENet provides sequencing for all packets by assigning to each sent packet a sequence number that is incremented as packets are sent. ENet guarentees that no packet with a higher sequence number will be delivered before a packet with a lower sequence number, thus ensuring packets are delivered exactly in the order they are sent. For unreliable packets, ENet will simply discard the lower sequence number packet if a packet with a higher sequence number has already been delivered. This allows the packets to be dispatched immediately as they arrive, and reduce latency of unreliable packets to an absolute minimum. For reliable packets, if a higher sequence number packet arrives, but the preceding packets in the sequence have not yet arrived, ENet will stall delivery of the higher sequence number packets until its predecessors have arrived. * Channels Since ENet will stall delivery of reliable packets to ensure proper sequencing, and consequently any packets of higher sequence number whether reliable or unreliable, in the event the reliable packet's predecessors have not yet arrived, this can introduce latency into the delivery of other packets which may not need to be as strictly ordered with respect to the packet that stalled their delivery. To combat this latency and reduce the ordering restrictions on packets, ENet provides multiple channels of communication over a given connection. Each channel is independently sequenced, and so the delivery status of a packet in one channel will not stall the delivery of other packets in another channel. * Reliability ENet provides optional reliability of packet delivery by ensuring the foreign host acknowledges receipt of all reliable packets. ENet will attempt to resend the packet up to a reasonable amount of times, if no acknowledgement of the packet's receipt happens within a specified timeout. Retry timeouts are progressive and become more lenient with every failed attempt to allow for temporary turbulence in network conditions. * Fragmentation and reassembly ENet will send and deliver packets regardless of size. Large packets are fragmented into many smaller packets of suitable size, and reassembled on the foreign host to recover the original packet for delivery. The process is entirely transparent to the developer. * Aggregation ENet aggregates all protocol commands, including acknowledgements and packet transfer, into larger protocol packets to ensure the proper utilization of the connection and to limit the opportunities for packet loss that might otherwise result in further delivery latency. * Adaptability ENet provides an in-flight data window for reliable packets to ensure connections are not overwhelmed by volumes of packets. It also provides a static bandwidth allocation mechanism to ensure the total volume of packets sent and received to a host don't exceed the host's capabilities. Further, ENet also provides a dynamic throttle that responds to deviations from normal network connections to rectify various types of network congestion by further limiting the volume of packets sent. * Portability ENet works on Windows and any other Unix or Unix-like platform providing a BSD sockets interface. The library has a small and stable code base that can easily be extended to support other platforms and integrates easily. * Freedom ENet demands no royalties and doesn't carry a viral license that would restrict you in how you might use it in your programs. ENet is licensed under a short-and-sweet MIT-style license, which gives you the freedom to do anything you want with it (well, almost anything). sauerbraten-0.0.20130203.dfsg/enet/include/0000755000175000017500000000000012100771037017751 5ustar vincentvincentsauerbraten-0.0.20130203.dfsg/enet/include/enet/0000755000175000017500000000000012100771037020704 5ustar vincentvincentsauerbraten-0.0.20130203.dfsg/enet/include/enet/types.h0000644000175000017500000000053311164573771022240 0ustar vincentvincent/** @file types.h @brief type definitions for ENet */ #ifndef __ENET_TYPES_H__ #define __ENET_TYPES_H__ typedef unsigned char enet_uint8; /**< unsigned 8-bit type */ typedef unsigned short enet_uint16; /**< unsigned 16-bit type */ typedef unsigned int enet_uint32; /**< unsigned 32-bit type */ #endif /* __ENET_TYPES_H__ */ sauerbraten-0.0.20130203.dfsg/enet/include/enet/time.h0000644000175000017500000000102211164573771022024 0ustar vincentvincent/** @file time.h @brief ENet time constants and macros */ #ifndef __ENET_TIME_H__ #define __ENET_TIME_H__ #define ENET_TIME_OVERFLOW 86400000 #define ENET_TIME_LESS(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW) #define ENET_TIME_GREATER(a, b) ((b) - (a) >= ENET_TIME_OVERFLOW) #define ENET_TIME_LESS_EQUAL(a, b) (! ENET_TIME_GREATER (a, b)) #define ENET_TIME_GREATER_EQUAL(a, b) (! ENET_TIME_LESS (a, b)) #define ENET_TIME_DIFFERENCE(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW ? (b) - (a) : (a) - (b)) #endif /* __ENET_TIME_H__ */ sauerbraten-0.0.20130203.dfsg/enet/include/enet/callbacks.h0000644000175000017500000000101211375320316022771 0ustar vincentvincent/** @file callbacks.h @brief ENet callbacks */ #ifndef __ENET_CALLBACKS_H__ #define __ENET_CALLBACKS_H__ #include typedef struct _ENetCallbacks { void * (ENET_CALLBACK * malloc) (size_t size); void (ENET_CALLBACK * free) (void * memory); void (ENET_CALLBACK * no_memory) (void); } ENetCallbacks; /** @defgroup callbacks ENet internal callbacks @{ @ingroup private */ extern void * enet_malloc (size_t); extern void enet_free (void *); /** @} */ #endif /* __ENET_CALLBACKS_H__ */ sauerbraten-0.0.20130203.dfsg/enet/include/enet/win32.h0000644000175000017500000000260211164573771022035 0ustar vincentvincent/** @file win32.h @brief ENet Win32 header */ #ifndef __ENET_WIN32_H__ #define __ENET_WIN32_H__ #ifdef ENET_BUILDING_LIB #pragma warning (disable: 4996) // 'strncpy' was declared deprecated #pragma warning (disable: 4267) // size_t to int conversion #pragma warning (disable: 4244) // 64bit to 32bit int #pragma warning (disable: 4018) // signed/unsigned mismatch #endif #include #include typedef SOCKET ENetSocket; enum { ENET_SOCKET_NULL = INVALID_SOCKET }; #define ENET_HOST_TO_NET_16(value) (htons (value)) #define ENET_HOST_TO_NET_32(value) (htonl (value)) #define ENET_NET_TO_HOST_16(value) (ntohs (value)) #define ENET_NET_TO_HOST_32(value) (ntohl (value)) typedef struct { size_t dataLength; void * data; } ENetBuffer; #define ENET_CALLBACK __cdecl #if defined ENET_DLL #if defined ENET_BUILDING_LIB #define ENET_API __declspec( dllexport ) #else #define ENET_API __declspec( dllimport ) #endif /* ENET_BUILDING_LIB */ #else /* !ENET_DLL */ #define ENET_API extern #endif /* ENET_DLL */ typedef fd_set ENetSocketSet; #define ENET_SOCKETSET_EMPTY(sockset) FD_ZERO (& (sockset)) #define ENET_SOCKETSET_ADD(sockset, socket) FD_SET (socket, & (sockset)) #define ENET_SOCKETSET_REMOVE(sockset, socket) FD_CLEAR (socket, & (sockset)) #define ENET_SOCKETSET_CHECK(sockset, socket) FD_ISSET (socket, & (sockset)) #endif /* __ENET_WIN32_H__ */ sauerbraten-0.0.20130203.dfsg/enet/include/enet/utility.h0000644000175000017500000000035511164573771022601 0ustar vincentvincent/** @file utility.h @brief ENet utility header */ #ifndef __ENET_UTILITY_H__ #define __ENET_UTILITY_H__ #define ENET_MAX(x, y) ((x) > (y) ? (x) : (y)) #define ENET_MIN(x, y) ((x) < (y) ? (x) : (y)) #endif /* __ENET_UTILITY_H__ */ sauerbraten-0.0.20130203.dfsg/enet/include/enet/protocol.h0000644000175000017500000001323711701613700022722 0ustar vincentvincent/** @file protocol.h @brief ENet protocol */ #ifndef __ENET_PROTOCOL_H__ #define __ENET_PROTOCOL_H__ #include "enet/types.h" enum { ENET_PROTOCOL_MINIMUM_MTU = 576, ENET_PROTOCOL_MAXIMUM_MTU = 4096, ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS = 32, ENET_PROTOCOL_MINIMUM_WINDOW_SIZE = 4096, ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE = 32768, ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT = 1, ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT = 255, ENET_PROTOCOL_MAXIMUM_PEER_ID = 0xFFF, ENET_PROTOCOL_MAXIMUM_PACKET_SIZE = 1024 * 1024 * 1024, ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT = 1024 * 1024 }; typedef enum _ENetProtocolCommand { ENET_PROTOCOL_COMMAND_NONE = 0, ENET_PROTOCOL_COMMAND_ACKNOWLEDGE = 1, ENET_PROTOCOL_COMMAND_CONNECT = 2, ENET_PROTOCOL_COMMAND_VERIFY_CONNECT = 3, ENET_PROTOCOL_COMMAND_DISCONNECT = 4, ENET_PROTOCOL_COMMAND_PING = 5, ENET_PROTOCOL_COMMAND_SEND_RELIABLE = 6, ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE = 7, ENET_PROTOCOL_COMMAND_SEND_FRAGMENT = 8, ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED = 9, ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT = 10, ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE = 11, ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT = 12, ENET_PROTOCOL_COMMAND_COUNT = 13, ENET_PROTOCOL_COMMAND_MASK = 0x0F } ENetProtocolCommand; typedef enum _ENetProtocolFlag { ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE = (1 << 7), ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED = (1 << 6), ENET_PROTOCOL_HEADER_FLAG_COMPRESSED = (1 << 14), ENET_PROTOCOL_HEADER_FLAG_SENT_TIME = (1 << 15), ENET_PROTOCOL_HEADER_FLAG_MASK = ENET_PROTOCOL_HEADER_FLAG_COMPRESSED | ENET_PROTOCOL_HEADER_FLAG_SENT_TIME, ENET_PROTOCOL_HEADER_SESSION_MASK = (3 << 12), ENET_PROTOCOL_HEADER_SESSION_SHIFT = 12 } ENetProtocolFlag; #ifdef _MSC_VER_ #pragma pack(push, 1) #define ENET_PACKED #elif defined(__GNUC__) #define ENET_PACKED __attribute__ ((packed)) #else #define ENET_PACKED #endif typedef struct _ENetProtocolHeader { enet_uint16 peerID; enet_uint16 sentTime; } ENET_PACKED ENetProtocolHeader; typedef struct _ENetProtocolCommandHeader { enet_uint8 command; enet_uint8 channelID; enet_uint16 reliableSequenceNumber; } ENET_PACKED ENetProtocolCommandHeader; typedef struct _ENetProtocolAcknowledge { ENetProtocolCommandHeader header; enet_uint16 receivedReliableSequenceNumber; enet_uint16 receivedSentTime; } ENET_PACKED ENetProtocolAcknowledge; typedef struct _ENetProtocolConnect { ENetProtocolCommandHeader header; enet_uint16 outgoingPeerID; enet_uint8 incomingSessionID; enet_uint8 outgoingSessionID; enet_uint32 mtu; enet_uint32 windowSize; enet_uint32 channelCount; enet_uint32 incomingBandwidth; enet_uint32 outgoingBandwidth; enet_uint32 packetThrottleInterval; enet_uint32 packetThrottleAcceleration; enet_uint32 packetThrottleDeceleration; enet_uint32 connectID; enet_uint32 data; } ENET_PACKED ENetProtocolConnect; typedef struct _ENetProtocolVerifyConnect { ENetProtocolCommandHeader header; enet_uint16 outgoingPeerID; enet_uint8 incomingSessionID; enet_uint8 outgoingSessionID; enet_uint32 mtu; enet_uint32 windowSize; enet_uint32 channelCount; enet_uint32 incomingBandwidth; enet_uint32 outgoingBandwidth; enet_uint32 packetThrottleInterval; enet_uint32 packetThrottleAcceleration; enet_uint32 packetThrottleDeceleration; enet_uint32 connectID; } ENET_PACKED ENetProtocolVerifyConnect; typedef struct _ENetProtocolBandwidthLimit { ENetProtocolCommandHeader header; enet_uint32 incomingBandwidth; enet_uint32 outgoingBandwidth; } ENET_PACKED ENetProtocolBandwidthLimit; typedef struct _ENetProtocolThrottleConfigure { ENetProtocolCommandHeader header; enet_uint32 packetThrottleInterval; enet_uint32 packetThrottleAcceleration; enet_uint32 packetThrottleDeceleration; } ENET_PACKED ENetProtocolThrottleConfigure; typedef struct _ENetProtocolDisconnect { ENetProtocolCommandHeader header; enet_uint32 data; } ENET_PACKED ENetProtocolDisconnect; typedef struct _ENetProtocolPing { ENetProtocolCommandHeader header; } ENET_PACKED ENetProtocolPing; typedef struct _ENetProtocolSendReliable { ENetProtocolCommandHeader header; enet_uint16 dataLength; } ENET_PACKED ENetProtocolSendReliable; typedef struct _ENetProtocolSendUnreliable { ENetProtocolCommandHeader header; enet_uint16 unreliableSequenceNumber; enet_uint16 dataLength; } ENET_PACKED ENetProtocolSendUnreliable; typedef struct _ENetProtocolSendUnsequenced { ENetProtocolCommandHeader header; enet_uint16 unsequencedGroup; enet_uint16 dataLength; } ENET_PACKED ENetProtocolSendUnsequenced; typedef struct _ENetProtocolSendFragment { ENetProtocolCommandHeader header; enet_uint16 startSequenceNumber; enet_uint16 dataLength; enet_uint32 fragmentCount; enet_uint32 fragmentNumber; enet_uint32 totalLength; enet_uint32 fragmentOffset; } ENET_PACKED ENetProtocolSendFragment; typedef union _ENetProtocol { ENetProtocolCommandHeader header; ENetProtocolAcknowledge acknowledge; ENetProtocolConnect connect; ENetProtocolVerifyConnect verifyConnect; ENetProtocolDisconnect disconnect; ENetProtocolPing ping; ENetProtocolSendReliable sendReliable; ENetProtocolSendUnreliable sendUnreliable; ENetProtocolSendUnsequenced sendUnsequenced; ENetProtocolSendFragment sendFragment; ENetProtocolBandwidthLimit bandwidthLimit; ENetProtocolThrottleConfigure throttleConfigure; } ENET_PACKED ENetProtocol; #ifdef _MSC_VER_ #pragma pack(pop) #endif #endif /* __ENET_PROTOCOL_H__ */ sauerbraten-0.0.20130203.dfsg/enet/include/enet/enet.h0000644000175000017500000005624212062332501022015 0ustar vincentvincent/** @file enet.h @brief ENet public header file */ #ifndef __ENET_ENET_H__ #define __ENET_ENET_H__ #ifdef __cplusplus extern "C" { #endif #include #ifdef WIN32 #include "enet/win32.h" #else #include "enet/unix.h" #endif #include "enet/types.h" #include "enet/protocol.h" #include "enet/list.h" #include "enet/callbacks.h" #define ENET_VERSION_MAJOR 1 #define ENET_VERSION_MINOR 3 #define ENET_VERSION_PATCH 6 #define ENET_VERSION_CREATE(major, minor, patch) (((major)<<16) | ((minor)<<8) | (patch)) #define ENET_VERSION ENET_VERSION_CREATE(ENET_VERSION_MAJOR, ENET_VERSION_MINOR, ENET_VERSION_PATCH) typedef enet_uint32 ENetVersion; struct _ENetHost; struct _ENetEvent; struct _ENetPacket; typedef enum _ENetSocketType { ENET_SOCKET_TYPE_STREAM = 1, ENET_SOCKET_TYPE_DATAGRAM = 2 } ENetSocketType; typedef enum _ENetSocketWait { ENET_SOCKET_WAIT_NONE = 0, ENET_SOCKET_WAIT_SEND = (1 << 0), ENET_SOCKET_WAIT_RECEIVE = (1 << 1) } ENetSocketWait; typedef enum _ENetSocketOption { ENET_SOCKOPT_NONBLOCK = 1, ENET_SOCKOPT_BROADCAST = 2, ENET_SOCKOPT_RCVBUF = 3, ENET_SOCKOPT_SNDBUF = 4, ENET_SOCKOPT_REUSEADDR = 5, ENET_SOCKOPT_RCVTIMEO = 6, ENET_SOCKOPT_SNDTIMEO = 7 } ENetSocketOption; typedef enum _ENetSocketShutdown { ENET_SOCKET_SHUTDOWN_READ = 0, ENET_SOCKET_SHUTDOWN_WRITE = 1, ENET_SOCKET_SHUTDOWN_READ_WRITE = 2 } ENetSocketShutdown; enum { ENET_HOST_ANY = 0, /**< specifies the default server host */ ENET_HOST_BROADCAST = 0xFFFFFFFF, /**< specifies a subnet-wide broadcast */ ENET_PORT_ANY = 0 /**< specifies that a port should be automatically chosen */ }; /** * Portable internet address structure. * * The host must be specified in network byte-order, and the port must be in host * byte-order. The constant ENET_HOST_ANY may be used to specify the default * server host. The constant ENET_HOST_BROADCAST may be used to specify the * broadcast address (255.255.255.255). This makes sense for enet_host_connect, * but not for enet_host_create. Once a server responds to a broadcast, the * address is updated from ENET_HOST_BROADCAST to the server's actual IP address. */ typedef struct _ENetAddress { enet_uint32 host; enet_uint16 port; } ENetAddress; /** * Packet flag bit constants. * * The host must be specified in network byte-order, and the port must be in * host byte-order. The constant ENET_HOST_ANY may be used to specify the * default server host. @sa ENetPacket */ typedef enum _ENetPacketFlag { /** packet must be received by the target peer and resend attempts should be * made until the packet is delivered */ ENET_PACKET_FLAG_RELIABLE = (1 << 0), /** packet will not be sequenced with other packets * not supported for reliable packets */ ENET_PACKET_FLAG_UNSEQUENCED = (1 << 1), /** packet will not allocate data, and user must supply it instead */ ENET_PACKET_FLAG_NO_ALLOCATE = (1 << 2), /** packet will be fragmented using unreliable (instead of reliable) sends * if it exceeds the MTU */ ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT = (1 << 3) } ENetPacketFlag; typedef void (ENET_CALLBACK * ENetPacketFreeCallback) (struct _ENetPacket *); /** * ENet packet structure. * * An ENet data packet that may be sent to or received from a peer. The shown * fields should only be read and never modified. The data field contains the * allocated data for the packet. The dataLength fields specifies the length * of the allocated data. The flags field is either 0 (specifying no flags), * or a bitwise-or of any combination of the following flags: * * ENET_PACKET_FLAG_RELIABLE - packet must be received by the target peer * and resend attempts should be made until the packet is delivered * * ENET_PACKET_FLAG_UNSEQUENCED - packet will not be sequenced with other packets * (not supported for reliable packets) * * ENET_PACKET_FLAG_NO_ALLOCATE - packet will not allocate data, and user must supply it instead @sa ENetPacketFlag */ typedef struct _ENetPacket { size_t referenceCount; /**< internal use only */ enet_uint32 flags; /**< bitwise-or of ENetPacketFlag constants */ enet_uint8 * data; /**< allocated data for packet */ size_t dataLength; /**< length of data */ ENetPacketFreeCallback freeCallback; /**< function to be called when the packet is no longer in use */ } ENetPacket; typedef struct _ENetAcknowledgement { ENetListNode acknowledgementList; enet_uint32 sentTime; ENetProtocol command; } ENetAcknowledgement; typedef struct _ENetOutgoingCommand { ENetListNode outgoingCommandList; enet_uint16 reliableSequenceNumber; enet_uint16 unreliableSequenceNumber; enet_uint32 sentTime; enet_uint32 roundTripTimeout; enet_uint32 roundTripTimeoutLimit; enet_uint32 fragmentOffset; enet_uint16 fragmentLength; enet_uint16 sendAttempts; ENetProtocol command; ENetPacket * packet; } ENetOutgoingCommand; typedef struct _ENetIncomingCommand { ENetListNode incomingCommandList; enet_uint16 reliableSequenceNumber; enet_uint16 unreliableSequenceNumber; ENetProtocol command; enet_uint32 fragmentCount; enet_uint32 fragmentsRemaining; enet_uint32 * fragments; ENetPacket * packet; } ENetIncomingCommand; typedef enum _ENetPeerState { ENET_PEER_STATE_DISCONNECTED = 0, ENET_PEER_STATE_CONNECTING = 1, ENET_PEER_STATE_ACKNOWLEDGING_CONNECT = 2, ENET_PEER_STATE_CONNECTION_PENDING = 3, ENET_PEER_STATE_CONNECTION_SUCCEEDED = 4, ENET_PEER_STATE_CONNECTED = 5, ENET_PEER_STATE_DISCONNECT_LATER = 6, ENET_PEER_STATE_DISCONNECTING = 7, ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT = 8, ENET_PEER_STATE_ZOMBIE = 9 } ENetPeerState; #ifndef ENET_BUFFER_MAXIMUM #define ENET_BUFFER_MAXIMUM (1 + 2 * ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS) #endif enum { ENET_HOST_RECEIVE_BUFFER_SIZE = 256 * 1024, ENET_HOST_SEND_BUFFER_SIZE = 256 * 1024, ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL = 1000, ENET_HOST_DEFAULT_MTU = 1400, ENET_PEER_DEFAULT_ROUND_TRIP_TIME = 500, ENET_PEER_DEFAULT_PACKET_THROTTLE = 32, ENET_PEER_PACKET_THROTTLE_SCALE = 32, ENET_PEER_PACKET_THROTTLE_COUNTER = 7, ENET_PEER_PACKET_THROTTLE_ACCELERATION = 2, ENET_PEER_PACKET_THROTTLE_DECELERATION = 2, ENET_PEER_PACKET_THROTTLE_INTERVAL = 5000, ENET_PEER_PACKET_LOSS_SCALE = (1 << 16), ENET_PEER_PACKET_LOSS_INTERVAL = 10000, ENET_PEER_WINDOW_SIZE_SCALE = 64 * 1024, ENET_PEER_TIMEOUT_LIMIT = 32, ENET_PEER_TIMEOUT_MINIMUM = 5000, ENET_PEER_TIMEOUT_MAXIMUM = 30000, ENET_PEER_PING_INTERVAL = 500, ENET_PEER_UNSEQUENCED_WINDOWS = 64, ENET_PEER_UNSEQUENCED_WINDOW_SIZE = 1024, ENET_PEER_FREE_UNSEQUENCED_WINDOWS = 32, ENET_PEER_RELIABLE_WINDOWS = 16, ENET_PEER_RELIABLE_WINDOW_SIZE = 0x1000, ENET_PEER_FREE_RELIABLE_WINDOWS = 8 }; typedef struct _ENetChannel { enet_uint16 outgoingReliableSequenceNumber; enet_uint16 outgoingUnreliableSequenceNumber; enet_uint16 usedReliableWindows; enet_uint16 reliableWindows [ENET_PEER_RELIABLE_WINDOWS]; enet_uint16 incomingReliableSequenceNumber; enet_uint16 incomingUnreliableSequenceNumber; ENetList incomingReliableCommands; ENetList incomingUnreliableCommands; } ENetChannel; /** * An ENet peer which data packets may be sent or received from. * * No fields should be modified unless otherwise specified. */ typedef struct _ENetPeer { ENetListNode dispatchList; struct _ENetHost * host; enet_uint16 outgoingPeerID; enet_uint16 incomingPeerID; enet_uint32 connectID; enet_uint8 outgoingSessionID; enet_uint8 incomingSessionID; ENetAddress address; /**< Internet address of the peer */ void * data; /**< Application private data, may be freely modified */ ENetPeerState state; ENetChannel * channels; size_t channelCount; /**< Number of channels allocated for communication with peer */ enet_uint32 incomingBandwidth; /**< Downstream bandwidth of the client in bytes/second */ enet_uint32 outgoingBandwidth; /**< Upstream bandwidth of the client in bytes/second */ enet_uint32 incomingBandwidthThrottleEpoch; enet_uint32 outgoingBandwidthThrottleEpoch; enet_uint32 incomingDataTotal; enet_uint32 outgoingDataTotal; enet_uint32 lastSendTime; enet_uint32 lastReceiveTime; enet_uint32 nextTimeout; enet_uint32 earliestTimeout; enet_uint32 packetLossEpoch; enet_uint32 packetsSent; enet_uint32 packetsLost; enet_uint32 packetLoss; /**< mean packet loss of reliable packets as a ratio with respect to the constant ENET_PEER_PACKET_LOSS_SCALE */ enet_uint32 packetLossVariance; enet_uint32 packetThrottle; enet_uint32 packetThrottleLimit; enet_uint32 packetThrottleCounter; enet_uint32 packetThrottleEpoch; enet_uint32 packetThrottleAcceleration; enet_uint32 packetThrottleDeceleration; enet_uint32 packetThrottleInterval; enet_uint32 pingInterval; enet_uint32 timeoutLimit; enet_uint32 timeoutMinimum; enet_uint32 timeoutMaximum; enet_uint32 lastRoundTripTime; enet_uint32 lowestRoundTripTime; enet_uint32 lastRoundTripTimeVariance; enet_uint32 highestRoundTripTimeVariance; enet_uint32 roundTripTime; /**< mean round trip time (RTT), in milliseconds, between sending a reliable packet and receiving its acknowledgement */ enet_uint32 roundTripTimeVariance; enet_uint32 mtu; enet_uint32 windowSize; enet_uint32 reliableDataInTransit; enet_uint16 outgoingReliableSequenceNumber; ENetList acknowledgements; ENetList sentReliableCommands; ENetList sentUnreliableCommands; ENetList outgoingReliableCommands; ENetList outgoingUnreliableCommands; ENetList dispatchedCommands; int needsDispatch; enet_uint16 incomingUnsequencedGroup; enet_uint16 outgoingUnsequencedGroup; enet_uint32 unsequencedWindow [ENET_PEER_UNSEQUENCED_WINDOW_SIZE / 32]; enet_uint32 eventData; } ENetPeer; /** An ENet packet compressor for compressing UDP packets before socket sends or receives. */ typedef struct _ENetCompressor { /** Context data for the compressor. Must be non-NULL. */ void * context; /** Compresses from inBuffers[0:inBufferCount-1], containing inLimit bytes, to outData, outputting at most outLimit bytes. Should return 0 on failure. */ size_t (ENET_CALLBACK * compress) (void * context, const ENetBuffer * inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 * outData, size_t outLimit); /** Decompresses from inData, containing inLimit bytes, to outData, outputting at most outLimit bytes. Should return 0 on failure. */ size_t (ENET_CALLBACK * decompress) (void * context, const enet_uint8 * inData, size_t inLimit, enet_uint8 * outData, size_t outLimit); /** Destroys the context when compression is disabled or the host is destroyed. May be NULL. */ void (ENET_CALLBACK * destroy) (void * context); } ENetCompressor; /** Callback that computes the checksum of the data held in buffers[0:bufferCount-1] */ typedef enet_uint32 (ENET_CALLBACK * ENetChecksumCallback) (const ENetBuffer * buffers, size_t bufferCount); /** Callback for intercepting received raw UDP packets. Should return 1 to intercept, 0 to ignore, or -1 to propagate an error. */ typedef int (ENET_CALLBACK * ENetInterceptCallback) (struct _ENetHost * host, struct _ENetEvent * event); /** An ENet host for communicating with peers. * * No fields should be modified unless otherwise stated. @sa enet_host_create() @sa enet_host_destroy() @sa enet_host_connect() @sa enet_host_service() @sa enet_host_flush() @sa enet_host_broadcast() @sa enet_host_compress() @sa enet_host_compress_with_range_coder() @sa enet_host_channel_limit() @sa enet_host_bandwidth_limit() @sa enet_host_bandwidth_throttle() */ typedef struct _ENetHost { ENetSocket socket; ENetAddress address; /**< Internet address of the host */ enet_uint32 incomingBandwidth; /**< downstream bandwidth of the host */ enet_uint32 outgoingBandwidth; /**< upstream bandwidth of the host */ enet_uint32 bandwidthThrottleEpoch; enet_uint32 mtu; enet_uint32 randomSeed; int recalculateBandwidthLimits; ENetPeer * peers; /**< array of peers allocated for this host */ size_t peerCount; /**< number of peers allocated for this host */ size_t channelLimit; /**< maximum number of channels allowed for connected peers */ enet_uint32 serviceTime; ENetList dispatchQueue; int continueSending; size_t packetSize; enet_uint16 headerFlags; ENetProtocol commands [ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS]; size_t commandCount; ENetBuffer buffers [ENET_BUFFER_MAXIMUM]; size_t bufferCount; ENetChecksumCallback checksum; /**< callback the user can set to enable packet checksums for this host */ ENetCompressor compressor; enet_uint8 packetData [2][ENET_PROTOCOL_MAXIMUM_MTU]; ENetAddress receivedAddress; enet_uint8 * receivedData; size_t receivedDataLength; enet_uint32 totalSentData; /**< total data sent, user should reset to 0 as needed to prevent overflow */ enet_uint32 totalSentPackets; /**< total UDP packets sent, user should reset to 0 as needed to prevent overflow */ enet_uint32 totalReceivedData; /**< total data received, user should reset to 0 as needed to prevent overflow */ enet_uint32 totalReceivedPackets; /**< total UDP packets received, user should reset to 0 as needed to prevent overflow */ ENetInterceptCallback intercept; /**< callback the user can set to intercept received raw UDP packets */ } ENetHost; /** * An ENet event type, as specified in @ref ENetEvent. */ typedef enum _ENetEventType { /** no event occurred within the specified time limit */ ENET_EVENT_TYPE_NONE = 0, /** a connection request initiated by enet_host_connect has completed. * The peer field contains the peer which successfully connected. */ ENET_EVENT_TYPE_CONNECT = 1, /** a peer has disconnected. This event is generated on a successful * completion of a disconnect initiated by enet_pper_disconnect, if * a peer has timed out, or if a connection request intialized by * enet_host_connect has timed out. The peer field contains the peer * which disconnected. The data field contains user supplied data * describing the disconnection, or 0, if none is available. */ ENET_EVENT_TYPE_DISCONNECT = 2, /** a packet has been received from a peer. The peer field specifies the * peer which sent the packet. The channelID field specifies the channel * number upon which the packet was received. The packet field contains * the packet that was received; this packet must be destroyed with * enet_packet_destroy after use. */ ENET_EVENT_TYPE_RECEIVE = 3 } ENetEventType; /** * An ENet event as returned by enet_host_service(). @sa enet_host_service */ typedef struct _ENetEvent { ENetEventType type; /**< type of the event */ ENetPeer * peer; /**< peer that generated a connect, disconnect or receive event */ enet_uint8 channelID; /**< channel on the peer that generated the event, if appropriate */ enet_uint32 data; /**< data associated with the event, if appropriate */ ENetPacket * packet; /**< packet associated with the event, if appropriate */ } ENetEvent; /** @defgroup global ENet global functions @{ */ /** Initializes ENet globally. Must be called prior to using any functions in ENet. @returns 0 on success, < 0 on failure */ ENET_API int enet_initialize (void); /** Initializes ENet globally and supplies user-overridden callbacks. Must be called prior to using any functions in ENet. Do not use enet_initialize() if you use this variant. Make sure the ENetCallbacks structure is zeroed out so that any additional callbacks added in future versions will be properly ignored. @param version the constant ENET_VERSION should be supplied so ENet knows which version of ENetCallbacks struct to use @param inits user-overriden callbacks where any NULL callbacks will use ENet's defaults @returns 0 on success, < 0 on failure */ ENET_API int enet_initialize_with_callbacks (ENetVersion version, const ENetCallbacks * inits); /** Shuts down ENet globally. Should be called when a program that has initialized ENet exits. */ ENET_API void enet_deinitialize (void); /** @} */ /** @defgroup private ENet private implementation functions */ /** Returns the wall-time in milliseconds. Its initial value is unspecified unless otherwise set. */ ENET_API enet_uint32 enet_time_get (void); /** Sets the current wall-time in milliseconds. */ ENET_API void enet_time_set (enet_uint32); /** @defgroup socket ENet socket functions @{ */ ENET_API ENetSocket enet_socket_create (ENetSocketType); ENET_API int enet_socket_bind (ENetSocket, const ENetAddress *); ENET_API int enet_socket_listen (ENetSocket, int); ENET_API ENetSocket enet_socket_accept (ENetSocket, ENetAddress *); ENET_API int enet_socket_connect (ENetSocket, const ENetAddress *); ENET_API int enet_socket_send (ENetSocket, const ENetAddress *, const ENetBuffer *, size_t); ENET_API int enet_socket_receive (ENetSocket, ENetAddress *, ENetBuffer *, size_t); ENET_API int enet_socket_wait (ENetSocket, enet_uint32 *, enet_uint32); ENET_API int enet_socket_set_option (ENetSocket, ENetSocketOption, int); ENET_API int enet_socket_shutdown (ENetSocket, ENetSocketShutdown); ENET_API void enet_socket_destroy (ENetSocket); ENET_API int enet_socketset_select (ENetSocket, ENetSocketSet *, ENetSocketSet *, enet_uint32); /** @} */ /** @defgroup Address ENet address functions @{ */ /** Attempts to resolve the host named by the parameter hostName and sets the host field in the address parameter if successful. @param address destination to store resolved address @param hostName host name to lookup @retval 0 on success @retval < 0 on failure @returns the address of the given hostName in address on success */ ENET_API int enet_address_set_host (ENetAddress * address, const char * hostName); /** Gives the printable form of the ip address specified in the address parameter. @param address address printed @param hostName destination for name, must not be NULL @param nameLength maximum length of hostName. @returns the null-terminated name of the host in hostName on success @retval 0 on success @retval < 0 on failure */ ENET_API int enet_address_get_host_ip (const ENetAddress * address, char * hostName, size_t nameLength); /** Attempts to do a reverse lookup of the host field in the address parameter. @param address address used for reverse lookup @param hostName destination for name, must not be NULL @param nameLength maximum length of hostName. @returns the null-terminated name of the host in hostName on success @retval 0 on success @retval < 0 on failure */ ENET_API int enet_address_get_host (const ENetAddress * address, char * hostName, size_t nameLength); /** @} */ ENET_API ENetPacket * enet_packet_create (const void *, size_t, enet_uint32); ENET_API void enet_packet_destroy (ENetPacket *); ENET_API int enet_packet_resize (ENetPacket *, size_t); ENET_API enet_uint32 enet_crc32 (const ENetBuffer *, size_t); ENET_API ENetHost * enet_host_create (const ENetAddress *, size_t, size_t, enet_uint32, enet_uint32); ENET_API void enet_host_destroy (ENetHost *); ENET_API ENetPeer * enet_host_connect (ENetHost *, const ENetAddress *, size_t, enet_uint32); ENET_API int enet_host_check_events (ENetHost *, ENetEvent *); ENET_API int enet_host_service (ENetHost *, ENetEvent *, enet_uint32); ENET_API void enet_host_flush (ENetHost *); ENET_API void enet_host_broadcast (ENetHost *, enet_uint8, ENetPacket *); ENET_API void enet_host_compress (ENetHost *, const ENetCompressor *); ENET_API int enet_host_compress_with_range_coder (ENetHost * host); ENET_API void enet_host_channel_limit (ENetHost *, size_t); ENET_API void enet_host_bandwidth_limit (ENetHost *, enet_uint32, enet_uint32); extern void enet_host_bandwidth_throttle (ENetHost *); ENET_API int enet_peer_send (ENetPeer *, enet_uint8, ENetPacket *); ENET_API ENetPacket * enet_peer_receive (ENetPeer *, enet_uint8 * channelID); ENET_API void enet_peer_ping (ENetPeer *); ENET_API void enet_peer_ping_interval (ENetPeer *, enet_uint32); ENET_API void enet_peer_timeout (ENetPeer *, enet_uint32, enet_uint32, enet_uint32); ENET_API void enet_peer_reset (ENetPeer *); ENET_API void enet_peer_disconnect (ENetPeer *, enet_uint32); ENET_API void enet_peer_disconnect_now (ENetPeer *, enet_uint32); ENET_API void enet_peer_disconnect_later (ENetPeer *, enet_uint32); ENET_API void enet_peer_throttle_configure (ENetPeer *, enet_uint32, enet_uint32, enet_uint32); extern int enet_peer_throttle (ENetPeer *, enet_uint32); extern void enet_peer_reset_queues (ENetPeer *); extern void enet_peer_setup_outgoing_command (ENetPeer *, ENetOutgoingCommand *); extern ENetOutgoingCommand * enet_peer_queue_outgoing_command (ENetPeer *, const ENetProtocol *, ENetPacket *, enet_uint32, enet_uint16); extern ENetIncomingCommand * enet_peer_queue_incoming_command (ENetPeer *, const ENetProtocol *, ENetPacket *, enet_uint32); extern ENetAcknowledgement * enet_peer_queue_acknowledgement (ENetPeer *, const ENetProtocol *, enet_uint16); extern void enet_peer_dispatch_incoming_unreliable_commands (ENetPeer *, ENetChannel *); extern void enet_peer_dispatch_incoming_reliable_commands (ENetPeer *, ENetChannel *); ENET_API void * enet_range_coder_create (void); ENET_API void enet_range_coder_destroy (void *); ENET_API size_t enet_range_coder_compress (void *, const ENetBuffer *, size_t, size_t, enet_uint8 *, size_t); ENET_API size_t enet_range_coder_decompress (void *, const enet_uint8 *, size_t, enet_uint8 *, size_t); extern size_t enet_protocol_command_size (enet_uint8); #ifdef __cplusplus } #endif #endif /* __ENET_ENET_H__ */ sauerbraten-0.0.20130203.dfsg/enet/include/enet/list.h0000644000175000017500000000211311373036002022022 0ustar vincentvincent/** @file list.h @brief ENet list management */ #ifndef __ENET_LIST_H__ #define __ENET_LIST_H__ #include typedef struct _ENetListNode { struct _ENetListNode * next; struct _ENetListNode * previous; } ENetListNode; typedef ENetListNode * ENetListIterator; typedef struct _ENetList { ENetListNode sentinel; } ENetList; extern void enet_list_clear (ENetList *); extern ENetListIterator enet_list_insert (ENetListIterator, void *); extern void * enet_list_remove (ENetListIterator); extern ENetListIterator enet_list_move (ENetListIterator, void *, void *); extern size_t enet_list_size (ENetList *); #define enet_list_begin(list) ((list) -> sentinel.next) #define enet_list_end(list) (& (list) -> sentinel) #define enet_list_empty(list) (enet_list_begin (list) == enet_list_end (list)) #define enet_list_next(iterator) ((iterator) -> next) #define enet_list_previous(iterator) ((iterator) -> previous) #define enet_list_front(list) ((void *) (list) -> sentinel.next) #define enet_list_back(list) ((void *) (list) -> sentinel.previous) #endif /* __ENET_LIST_H__ */ sauerbraten-0.0.20130203.dfsg/enet/include/enet/unix.h0000644000175000017500000000232611164573771022061 0ustar vincentvincent/** @file unix.h @brief ENet Unix header */ #ifndef __ENET_UNIX_H__ #define __ENET_UNIX_H__ #include #include #include #include #include typedef int ENetSocket; enum { ENET_SOCKET_NULL = -1 }; #define ENET_HOST_TO_NET_16(value) (htons (value)) /**< macro that converts host to net byte-order of a 16-bit value */ #define ENET_HOST_TO_NET_32(value) (htonl (value)) /**< macro that converts host to net byte-order of a 32-bit value */ #define ENET_NET_TO_HOST_16(value) (ntohs (value)) /**< macro that converts net to host byte-order of a 16-bit value */ #define ENET_NET_TO_HOST_32(value) (ntohl (value)) /**< macro that converts net to host byte-order of a 32-bit value */ typedef struct { void * data; size_t dataLength; } ENetBuffer; #define ENET_CALLBACK #define ENET_API extern typedef fd_set ENetSocketSet; #define ENET_SOCKETSET_EMPTY(sockset) FD_ZERO (& (sockset)) #define ENET_SOCKETSET_ADD(sockset, socket) FD_SET (socket, & (sockset)) #define ENET_SOCKETSET_REMOVE(sockset, socket) FD_CLEAR (socket, & (sockset)) #define ENET_SOCKETSET_CHECK(sockset, socket) FD_ISSET (socket, & (sockset)) #endif /* __ENET_UNIX_H__ */ sauerbraten-0.0.20130203.dfsg/enet/config.sub0000755000175000017500000010532712006035707020323 0ustar vincentvincent#! /bin/sh # Configuration validation subroutine script. # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, # 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, # 2011, 2012 Free Software Foundation, Inc. timestamp='2012-04-18' # This file is (in principle) common to ALL GNU software. # The presence of a machine in this file suggests that SOME GNU software # can handle that machine. It does not imply ALL GNU software can. # # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Please send patches to . Submit a context # diff and a properly formatted GNU ChangeLog entry. # # Configuration subroutine to validate and canonicalize a configuration type. # Supply the specified configuration type as an argument. # If it is invalid, we print an error message on stderr and exit with code 1. # Otherwise, we print the canonical config type on stdout and succeed. # You can get the latest version of this script from: # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD # This file is supposed to be the same for all GNU packages # and recognize all the CPU types, system types and aliases # that are meaningful with *any* GNU software. # Each package is responsible for reporting which valid configurations # it does not support. The user should be able to distinguish # a failure to support a valid configuration from a meaningless # configuration. # The goal of this file is to map all the various variations of a given # machine specification into a single specification in the form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM # or in some cases, the newer four-part form: # CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM # It is wrong to echo any other type of specification. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] CPU-MFR-OPSYS $0 [OPTION] ALIAS Canonicalize a configuration name. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.sub ($timestamp) Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" exit 1 ;; *local*) # First pass through any local machine types. echo $1 exit ;; * ) break ;; esac done case $# in 0) echo "$me: missing argument$help" >&2 exit 1;; 1) ;; *) echo "$me: too many arguments$help" >&2 exit 1;; esac # Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). # Here we must recognize all the valid KERNEL-OS combinations. maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` case $maybe_os in nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \ linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \ knetbsd*-gnu* | netbsd*-gnu* | \ kopensolaris*-gnu* | \ storm-chaos* | os2-emx* | rtmk-nova*) os=-$maybe_os basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` ;; android-linux) os=-linux-android basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown ;; *) basic_machine=`echo $1 | sed 's/-[^-]*$//'` if [ $basic_machine != $1 ] then os=`echo $1 | sed 's/.*-/-/'` else os=; fi ;; esac ### Let's recognize common machines as not being operating systems so ### that things like config.sub decstation-3100 work. We also ### recognize some manufacturers as not being operating systems, so we ### can provide default operating systems below. case $os in -sun*os*) # Prevent following clause from handling this invalid input. ;; -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ -apple | -axis | -knuth | -cray | -microblaze) os= basic_machine=$1 ;; -bluegene*) os=-cnk ;; -sim | -cisco | -oki | -wec | -winbond) os= basic_machine=$1 ;; -scout) ;; -wrs) os=-vxworks basic_machine=$1 ;; -chorusos*) os=-chorusos basic_machine=$1 ;; -chorusrdb) os=-chorusrdb basic_machine=$1 ;; -hiux*) os=-hiuxwe2 ;; -sco6) os=-sco5v6 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco5) os=-sco3.2v5 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco4) os=-sco3.2v4 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2.[4-9]*) os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2v[4-9]*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco5v6*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco*) os=-sco3.2v2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -udk*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -isc) os=-isc2.2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -clix*) basic_machine=clipper-intergraph ;; -isc*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -lynx*178) os=-lynxos178 ;; -lynx*5) os=-lynxos5 ;; -lynx*) os=-lynxos ;; -ptx*) basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` ;; -windowsnt*) os=`echo $os | sed -e 's/windowsnt/winnt/'` ;; -psos*) os=-psos ;; -mint | -mint[0-9]*) basic_machine=m68k-atari os=-mint ;; esac # Decode aliases for certain CPU-COMPANY combinations. case $basic_machine in # Recognize the basic CPU types without company name. # Some are omitted here because they have special meanings below. 1750a | 580 \ | a29k \ | aarch64 | aarch64_be \ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ | am33_2.0 \ | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \ | be32 | be64 \ | bfin \ | c4x | clipper \ | d10v | d30v | dlx | dsp16xx \ | epiphany \ | fido | fr30 | frv \ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ | hexagon \ | i370 | i860 | i960 | ia64 \ | ip2k | iq2000 \ | le32 | le64 \ | lm32 \ | m32c | m32r | m32rle | m68000 | m68k | m88k \ | maxq | mb | microblaze | mcore | mep | metag \ | mips | mipsbe | mipseb | mipsel | mipsle \ | mips16 \ | mips64 | mips64el \ | mips64octeon | mips64octeonel \ | mips64orion | mips64orionel \ | mips64r5900 | mips64r5900el \ | mips64vr | mips64vrel \ | mips64vr4100 | mips64vr4100el \ | mips64vr4300 | mips64vr4300el \ | mips64vr5000 | mips64vr5000el \ | mips64vr5900 | mips64vr5900el \ | mipsisa32 | mipsisa32el \ | mipsisa32r2 | mipsisa32r2el \ | mipsisa64 | mipsisa64el \ | mipsisa64r2 | mipsisa64r2el \ | mipsisa64sb1 | mipsisa64sb1el \ | mipsisa64sr71k | mipsisa64sr71kel \ | mipstx39 | mipstx39el \ | mn10200 | mn10300 \ | moxie \ | mt \ | msp430 \ | nds32 | nds32le | nds32be \ | nios | nios2 \ | ns16k | ns32k \ | open8 \ | or32 \ | pdp10 | pdp11 | pj | pjl \ | powerpc | powerpc64 | powerpc64le | powerpcle \ | pyramid \ | rl78 | rx \ | score \ | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ | sh64 | sh64le \ | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ | spu \ | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \ | ubicom32 \ | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \ | we32k \ | x86 | xc16x | xstormy16 | xtensa \ | z8k | z80) basic_machine=$basic_machine-unknown ;; c54x) basic_machine=tic54x-unknown ;; c55x) basic_machine=tic55x-unknown ;; c6x) basic_machine=tic6x-unknown ;; m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip) basic_machine=$basic_machine-unknown os=-none ;; m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) ;; ms1) basic_machine=mt-unknown ;; strongarm | thumb | xscale) basic_machine=arm-unknown ;; xgate) basic_machine=$basic_machine-unknown os=-none ;; xscaleeb) basic_machine=armeb-unknown ;; xscaleel) basic_machine=armel-unknown ;; # We use `pc' rather than `unknown' # because (1) that's what they normally are, and # (2) the word "unknown" tends to confuse beginning users. i*86 | x86_64) basic_machine=$basic_machine-pc ;; # Object if more than one company name word. *-*-*) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; # Recognize the basic CPU types with company name. 580-* \ | a29k-* \ | aarch64-* | aarch64_be-* \ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ | avr-* | avr32-* \ | be32-* | be64-* \ | bfin-* | bs2000-* \ | c[123]* | c30-* | [cjt]90-* | c4x-* \ | clipper-* | craynv-* | cydra-* \ | d10v-* | d30v-* | dlx-* \ | elxsi-* \ | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ | h8300-* | h8500-* \ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ | hexagon-* \ | i*86-* | i860-* | i960-* | ia64-* \ | ip2k-* | iq2000-* \ | le32-* | le64-* \ | lm32-* \ | m32c-* | m32r-* | m32rle-* \ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ | m88110-* | m88k-* | maxq-* | mcore-* | metag-* | microblaze-* \ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ | mips16-* \ | mips64-* | mips64el-* \ | mips64octeon-* | mips64octeonel-* \ | mips64orion-* | mips64orionel-* \ | mips64r5900-* | mips64r5900el-* \ | mips64vr-* | mips64vrel-* \ | mips64vr4100-* | mips64vr4100el-* \ | mips64vr4300-* | mips64vr4300el-* \ | mips64vr5000-* | mips64vr5000el-* \ | mips64vr5900-* | mips64vr5900el-* \ | mipsisa32-* | mipsisa32el-* \ | mipsisa32r2-* | mipsisa32r2el-* \ | mipsisa64-* | mipsisa64el-* \ | mipsisa64r2-* | mipsisa64r2el-* \ | mipsisa64sb1-* | mipsisa64sb1el-* \ | mipsisa64sr71k-* | mipsisa64sr71kel-* \ | mipstx39-* | mipstx39el-* \ | mmix-* \ | mt-* \ | msp430-* \ | nds32-* | nds32le-* | nds32be-* \ | nios-* | nios2-* \ | none-* | np1-* | ns16k-* | ns32k-* \ | open8-* \ | orion-* \ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \ | pyramid-* \ | rl78-* | romp-* | rs6000-* | rx-* \ | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ | sparclite-* \ | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \ | tahoe-* \ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ | tile*-* \ | tron-* \ | ubicom32-* \ | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \ | vax-* \ | we32k-* \ | x86-* | x86_64-* | xc16x-* | xps100-* \ | xstormy16-* | xtensa*-* \ | ymp-* \ | z8k-* | z80-*) ;; # Recognize the basic CPU types without company name, with glob match. xtensa*) basic_machine=$basic_machine-unknown ;; # Recognize the various machine names and aliases which stand # for a CPU type and a company and sometimes even an OS. 386bsd) basic_machine=i386-unknown os=-bsd ;; 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) basic_machine=m68000-att ;; 3b*) basic_machine=we32k-att ;; a29khif) basic_machine=a29k-amd os=-udi ;; abacus) basic_machine=abacus-unknown ;; adobe68k) basic_machine=m68010-adobe os=-scout ;; alliant | fx80) basic_machine=fx80-alliant ;; altos | altos3068) basic_machine=m68k-altos ;; am29k) basic_machine=a29k-none os=-bsd ;; amd64) basic_machine=x86_64-pc ;; amd64-*) basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; amdahl) basic_machine=580-amdahl os=-sysv ;; amiga | amiga-*) basic_machine=m68k-unknown ;; amigaos | amigados) basic_machine=m68k-unknown os=-amigaos ;; amigaunix | amix) basic_machine=m68k-unknown os=-sysv4 ;; apollo68) basic_machine=m68k-apollo os=-sysv ;; apollo68bsd) basic_machine=m68k-apollo os=-bsd ;; aros) basic_machine=i386-pc os=-aros ;; aux) basic_machine=m68k-apple os=-aux ;; balance) basic_machine=ns32k-sequent os=-dynix ;; blackfin) basic_machine=bfin-unknown os=-linux ;; blackfin-*) basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; bluegene*) basic_machine=powerpc-ibm os=-cnk ;; c54x-*) basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c55x-*) basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c6x-*) basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c90) basic_machine=c90-cray os=-unicos ;; cegcc) basic_machine=arm-unknown os=-cegcc ;; convex-c1) basic_machine=c1-convex os=-bsd ;; convex-c2) basic_machine=c2-convex os=-bsd ;; convex-c32) basic_machine=c32-convex os=-bsd ;; convex-c34) basic_machine=c34-convex os=-bsd ;; convex-c38) basic_machine=c38-convex os=-bsd ;; cray | j90) basic_machine=j90-cray os=-unicos ;; craynv) basic_machine=craynv-cray os=-unicosmp ;; cr16 | cr16-*) basic_machine=cr16-unknown os=-elf ;; crds | unos) basic_machine=m68k-crds ;; crisv32 | crisv32-* | etraxfs*) basic_machine=crisv32-axis ;; cris | cris-* | etrax*) basic_machine=cris-axis ;; crx) basic_machine=crx-unknown os=-elf ;; da30 | da30-*) basic_machine=m68k-da30 ;; decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) basic_machine=mips-dec ;; decsystem10* | dec10*) basic_machine=pdp10-dec os=-tops10 ;; decsystem20* | dec20*) basic_machine=pdp10-dec os=-tops20 ;; delta | 3300 | motorola-3300 | motorola-delta \ | 3300-motorola | delta-motorola) basic_machine=m68k-motorola ;; delta88) basic_machine=m88k-motorola os=-sysv3 ;; dicos) basic_machine=i686-pc os=-dicos ;; djgpp) basic_machine=i586-pc os=-msdosdjgpp ;; dpx20 | dpx20-*) basic_machine=rs6000-bull os=-bosx ;; dpx2* | dpx2*-bull) basic_machine=m68k-bull os=-sysv3 ;; ebmon29k) basic_machine=a29k-amd os=-ebmon ;; elxsi) basic_machine=elxsi-elxsi os=-bsd ;; encore | umax | mmax) basic_machine=ns32k-encore ;; es1800 | OSE68k | ose68k | ose | OSE) basic_machine=m68k-ericsson os=-ose ;; fx2800) basic_machine=i860-alliant ;; genix) basic_machine=ns32k-ns ;; gmicro) basic_machine=tron-gmicro os=-sysv ;; go32) basic_machine=i386-pc os=-go32 ;; h3050r* | hiux*) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; h8300hms) basic_machine=h8300-hitachi os=-hms ;; h8300xray) basic_machine=h8300-hitachi os=-xray ;; h8500hms) basic_machine=h8500-hitachi os=-hms ;; harris) basic_machine=m88k-harris os=-sysv3 ;; hp300-*) basic_machine=m68k-hp ;; hp300bsd) basic_machine=m68k-hp os=-bsd ;; hp300hpux) basic_machine=m68k-hp os=-hpux ;; hp3k9[0-9][0-9] | hp9[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k2[0-9][0-9] | hp9k31[0-9]) basic_machine=m68000-hp ;; hp9k3[2-9][0-9]) basic_machine=m68k-hp ;; hp9k6[0-9][0-9] | hp6[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k7[0-79][0-9] | hp7[0-79][0-9]) basic_machine=hppa1.1-hp ;; hp9k78[0-9] | hp78[0-9]) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[0-9][13679] | hp8[0-9][13679]) basic_machine=hppa1.1-hp ;; hp9k8[0-9][0-9] | hp8[0-9][0-9]) basic_machine=hppa1.0-hp ;; hppa-next) os=-nextstep3 ;; hppaosf) basic_machine=hppa1.1-hp os=-osf ;; hppro) basic_machine=hppa1.1-hp os=-proelf ;; i370-ibm* | ibm*) basic_machine=i370-ibm ;; i*86v32) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv32 ;; i*86v4*) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv4 ;; i*86v) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv ;; i*86sol2) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-solaris2 ;; i386mach) basic_machine=i386-mach os=-mach ;; i386-vsta | vsta) basic_machine=i386-unknown os=-vsta ;; iris | iris4d) basic_machine=mips-sgi case $os in -irix*) ;; *) os=-irix4 ;; esac ;; isi68 | isi) basic_machine=m68k-isi os=-sysv ;; m68knommu) basic_machine=m68k-unknown os=-linux ;; m68knommu-*) basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; m88k-omron*) basic_machine=m88k-omron ;; magnum | m3230) basic_machine=mips-mips os=-sysv ;; merlin) basic_machine=ns32k-utek os=-sysv ;; microblaze) basic_machine=microblaze-xilinx ;; mingw32) basic_machine=i386-pc os=-mingw32 ;; mingw32ce) basic_machine=arm-unknown os=-mingw32ce ;; miniframe) basic_machine=m68000-convergent ;; *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) basic_machine=m68k-atari os=-mint ;; mips3*-*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` ;; mips3*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown ;; monitor) basic_machine=m68k-rom68k os=-coff ;; morphos) basic_machine=powerpc-unknown os=-morphos ;; msdos) basic_machine=i386-pc os=-msdos ;; ms1-*) basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` ;; msys) basic_machine=i386-pc os=-msys ;; mvs) basic_machine=i370-ibm os=-mvs ;; nacl) basic_machine=le32-unknown os=-nacl ;; ncr3000) basic_machine=i486-ncr os=-sysv4 ;; netbsd386) basic_machine=i386-unknown os=-netbsd ;; netwinder) basic_machine=armv4l-rebel os=-linux ;; news | news700 | news800 | news900) basic_machine=m68k-sony os=-newsos ;; news1000) basic_machine=m68030-sony os=-newsos ;; news-3600 | risc-news) basic_machine=mips-sony os=-newsos ;; necv70) basic_machine=v70-nec os=-sysv ;; next | m*-next ) basic_machine=m68k-next case $os in -nextstep* ) ;; -ns2*) os=-nextstep2 ;; *) os=-nextstep3 ;; esac ;; nh3000) basic_machine=m68k-harris os=-cxux ;; nh[45]000) basic_machine=m88k-harris os=-cxux ;; nindy960) basic_machine=i960-intel os=-nindy ;; mon960) basic_machine=i960-intel os=-mon960 ;; nonstopux) basic_machine=mips-compaq os=-nonstopux ;; np1) basic_machine=np1-gould ;; neo-tandem) basic_machine=neo-tandem ;; nse-tandem) basic_machine=nse-tandem ;; nsr-tandem) basic_machine=nsr-tandem ;; op50n-* | op60c-*) basic_machine=hppa1.1-oki os=-proelf ;; openrisc | openrisc-*) basic_machine=or32-unknown ;; os400) basic_machine=powerpc-ibm os=-os400 ;; OSE68000 | ose68000) basic_machine=m68000-ericsson os=-ose ;; os68k) basic_machine=m68k-none os=-os68k ;; pa-hitachi) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; paragon) basic_machine=i860-intel os=-osf ;; parisc) basic_machine=hppa-unknown os=-linux ;; parisc-*) basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; pbd) basic_machine=sparc-tti ;; pbb) basic_machine=m68k-tti ;; pc532 | pc532-*) basic_machine=ns32k-pc532 ;; pc98) basic_machine=i386-pc ;; pc98-*) basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentium | p5 | k5 | k6 | nexgen | viac3) basic_machine=i586-pc ;; pentiumpro | p6 | 6x86 | athlon | athlon_*) basic_machine=i686-pc ;; pentiumii | pentium2 | pentiumiii | pentium3) basic_machine=i686-pc ;; pentium4) basic_machine=i786-pc ;; pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumpro-* | p6-* | 6x86-* | athlon-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentium4-*) basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pn) basic_machine=pn-gould ;; power) basic_machine=power-ibm ;; ppc | ppcbe) basic_machine=powerpc-unknown ;; ppc-* | ppcbe-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppcle | powerpclittle | ppc-le | powerpc-little) basic_machine=powerpcle-unknown ;; ppcle-* | powerpclittle-*) basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64) basic_machine=powerpc64-unknown ;; ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64le | powerpc64little | ppc64-le | powerpc64-little) basic_machine=powerpc64le-unknown ;; ppc64le-* | powerpc64little-*) basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ps2) basic_machine=i386-ibm ;; pw32) basic_machine=i586-unknown os=-pw32 ;; rdos) basic_machine=i386-pc os=-rdos ;; rom68k) basic_machine=m68k-rom68k os=-coff ;; rm[46]00) basic_machine=mips-siemens ;; rtpc | rtpc-*) basic_machine=romp-ibm ;; s390 | s390-*) basic_machine=s390-ibm ;; s390x | s390x-*) basic_machine=s390x-ibm ;; sa29200) basic_machine=a29k-amd os=-udi ;; sb1) basic_machine=mipsisa64sb1-unknown ;; sb1el) basic_machine=mipsisa64sb1el-unknown ;; sde) basic_machine=mipsisa32-sde os=-elf ;; sei) basic_machine=mips-sei os=-seiux ;; sequent) basic_machine=i386-sequent ;; sh) basic_machine=sh-hitachi os=-hms ;; sh5el) basic_machine=sh5le-unknown ;; sh64) basic_machine=sh64-unknown ;; sparclite-wrs | simso-wrs) basic_machine=sparclite-wrs os=-vxworks ;; sps7) basic_machine=m68k-bull os=-sysv2 ;; spur) basic_machine=spur-unknown ;; st2000) basic_machine=m68k-tandem ;; stratus) basic_machine=i860-stratus os=-sysv4 ;; strongarm-* | thumb-*) basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'` ;; sun2) basic_machine=m68000-sun ;; sun2os3) basic_machine=m68000-sun os=-sunos3 ;; sun2os4) basic_machine=m68000-sun os=-sunos4 ;; sun3os3) basic_machine=m68k-sun os=-sunos3 ;; sun3os4) basic_machine=m68k-sun os=-sunos4 ;; sun4os3) basic_machine=sparc-sun os=-sunos3 ;; sun4os4) basic_machine=sparc-sun os=-sunos4 ;; sun4sol2) basic_machine=sparc-sun os=-solaris2 ;; sun3 | sun3-*) basic_machine=m68k-sun ;; sun4) basic_machine=sparc-sun ;; sun386 | sun386i | roadrunner) basic_machine=i386-sun ;; sv1) basic_machine=sv1-cray os=-unicos ;; symmetry) basic_machine=i386-sequent os=-dynix ;; t3e) basic_machine=alphaev5-cray os=-unicos ;; t90) basic_machine=t90-cray os=-unicos ;; tile*) basic_machine=$basic_machine-unknown os=-linux-gnu ;; tx39) basic_machine=mipstx39-unknown ;; tx39el) basic_machine=mipstx39el-unknown ;; toad1) basic_machine=pdp10-xkl os=-tops20 ;; tower | tower-32) basic_machine=m68k-ncr ;; tpf) basic_machine=s390x-ibm os=-tpf ;; udi29k) basic_machine=a29k-amd os=-udi ;; ultra3) basic_machine=a29k-nyu os=-sym1 ;; v810 | necv810) basic_machine=v810-nec os=-none ;; vaxv) basic_machine=vax-dec os=-sysv ;; vms) basic_machine=vax-dec os=-vms ;; vpp*|vx|vx-*) basic_machine=f301-fujitsu ;; vxworks960) basic_machine=i960-wrs os=-vxworks ;; vxworks68) basic_machine=m68k-wrs os=-vxworks ;; vxworks29k) basic_machine=a29k-wrs os=-vxworks ;; w65*) basic_machine=w65-wdc os=-none ;; w89k-*) basic_machine=hppa1.1-winbond os=-proelf ;; xbox) basic_machine=i686-pc os=-mingw32 ;; xps | xps100) basic_machine=xps100-honeywell ;; xscale-* | xscalee[bl]-*) basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'` ;; ymp) basic_machine=ymp-cray os=-unicos ;; z8k-*-coff) basic_machine=z8k-unknown os=-sim ;; z80-*-coff) basic_machine=z80-unknown os=-sim ;; none) basic_machine=none-none os=-none ;; # Here we handle the default manufacturer of certain CPU types. It is in # some cases the only manufacturer, in others, it is the most popular. w89k) basic_machine=hppa1.1-winbond ;; op50n) basic_machine=hppa1.1-oki ;; op60c) basic_machine=hppa1.1-oki ;; romp) basic_machine=romp-ibm ;; mmix) basic_machine=mmix-knuth ;; rs6000) basic_machine=rs6000-ibm ;; vax) basic_machine=vax-dec ;; pdp10) # there are many clones, so DEC is not a safe bet basic_machine=pdp10-unknown ;; pdp11) basic_machine=pdp11-dec ;; we32k) basic_machine=we32k-att ;; sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele) basic_machine=sh-unknown ;; sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) basic_machine=sparc-sun ;; cydra) basic_machine=cydra-cydrome ;; orion) basic_machine=orion-highlevel ;; orion105) basic_machine=clipper-highlevel ;; mac | mpw | mac-mpw) basic_machine=m68k-apple ;; pmac | pmac-mpw) basic_machine=powerpc-apple ;; *-unknown) # Make sure to match an already-canonicalized machine name. ;; *) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; esac # Here we canonicalize certain aliases for manufacturers. case $basic_machine in *-digital*) basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` ;; *-commodore*) basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` ;; *) ;; esac # Decode manufacturer-specific aliases for certain operating systems. if [ x"$os" != x"" ] then case $os in # First match some system type aliases # that might get confused with valid system types. # -solaris* is a basic system type, with this one exception. -auroraux) os=-auroraux ;; -solaris1 | -solaris1.*) os=`echo $os | sed -e 's|solaris1|sunos4|'` ;; -solaris) os=-solaris2 ;; -svr4*) os=-sysv4 ;; -unixware*) os=-sysv4.2uw ;; -gnu/linux*) os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` ;; # First accept the basic system types. # The portable systems comes first. # Each alternative MUST END IN A *, to match a version number. # -sysv* is not here because it comes later, after sysvr4. -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \ | -sym* | -kopensolaris* \ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ | -aos* | -aros* \ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ | -openbsd* | -solidbsd* \ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ | -chorusos* | -chorusrdb* | -cegcc* \ | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ | -mingw32* | -linux-gnu* | -linux-android* \ | -linux-newlib* | -linux-uclibc* \ | -uxpv* | -beos* | -mpeix* | -udk* \ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*) # Remember, each alternative MUST END IN *, to match a version number. ;; -qnx*) case $basic_machine in x86-* | i*86-*) ;; *) os=-nto$os ;; esac ;; -nto-qnx*) ;; -nto*) os=`echo $os | sed -e 's|nto|nto-qnx|'` ;; -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) ;; -mac*) os=`echo $os | sed -e 's|mac|macos|'` ;; -linux-dietlibc) os=-linux-dietlibc ;; -linux*) os=`echo $os | sed -e 's|linux|linux-gnu|'` ;; -sunos5*) os=`echo $os | sed -e 's|sunos5|solaris2|'` ;; -sunos6*) os=`echo $os | sed -e 's|sunos6|solaris3|'` ;; -opened*) os=-openedition ;; -os400*) os=-os400 ;; -wince*) os=-wince ;; -osfrose*) os=-osfrose ;; -osf*) os=-osf ;; -utek*) os=-bsd ;; -dynix*) os=-bsd ;; -acis*) os=-aos ;; -atheos*) os=-atheos ;; -syllable*) os=-syllable ;; -386bsd) os=-bsd ;; -ctix* | -uts*) os=-sysv ;; -nova*) os=-rtmk-nova ;; -ns2 ) os=-nextstep2 ;; -nsk*) os=-nsk ;; # Preserve the version number of sinix5. -sinix5.*) os=`echo $os | sed -e 's|sinix|sysv|'` ;; -sinix*) os=-sysv4 ;; -tpf*) os=-tpf ;; -triton*) os=-sysv3 ;; -oss*) os=-sysv3 ;; -svr4) os=-sysv4 ;; -svr3) os=-sysv3 ;; -sysvr4) os=-sysv4 ;; # This must come after -sysvr4. -sysv*) ;; -ose*) os=-ose ;; -es1800*) os=-ose ;; -xenix) os=-xenix ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) os=-mint ;; -aros*) os=-aros ;; -kaos*) os=-kaos ;; -zvmoe) os=-zvmoe ;; -dicos*) os=-dicos ;; -nacl*) ;; -none) ;; *) # Get rid of the `-' at the beginning of $os. os=`echo $os | sed 's/[^-]*-//'` echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 exit 1 ;; esac else # Here we handle the default operating systems that come with various machines. # The value should be what the vendor currently ships out the door with their # machine or put another way, the most popular os provided with the machine. # Note that if you're going to try to match "-MANUFACTURER" here (say, # "-sun"), then you have to tell the case statement up towards the top # that MANUFACTURER isn't an operating system. Otherwise, code above # will signal an error saying that MANUFACTURER isn't an operating # system, and we'll never get to this point. case $basic_machine in score-*) os=-elf ;; spu-*) os=-elf ;; *-acorn) os=-riscix1.2 ;; arm*-rebel) os=-linux ;; arm*-semi) os=-aout ;; c4x-* | tic4x-*) os=-coff ;; hexagon-*) os=-elf ;; tic54x-*) os=-coff ;; tic55x-*) os=-coff ;; tic6x-*) os=-coff ;; # This must come before the *-dec entry. pdp10-*) os=-tops20 ;; pdp11-*) os=-none ;; *-dec | vax-*) os=-ultrix4.2 ;; m68*-apollo) os=-domain ;; i386-sun) os=-sunos4.0.2 ;; m68000-sun) os=-sunos3 ;; m68*-cisco) os=-aout ;; mep-*) os=-elf ;; mips*-cisco) os=-elf ;; mips*-*) os=-elf ;; or32-*) os=-coff ;; *-tti) # must be before sparc entry or we get the wrong os. os=-sysv3 ;; sparc-* | *-sun) os=-sunos4.1.1 ;; *-be) os=-beos ;; *-haiku) os=-haiku ;; *-ibm) os=-aix ;; *-knuth) os=-mmixware ;; *-wec) os=-proelf ;; *-winbond) os=-proelf ;; *-oki) os=-proelf ;; *-hp) os=-hpux ;; *-hitachi) os=-hiux ;; i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) os=-sysv ;; *-cbm) os=-amigaos ;; *-dg) os=-dgux ;; *-dolphin) os=-sysv3 ;; m68k-ccur) os=-rtu ;; m88k-omron*) os=-luna ;; *-next ) os=-nextstep ;; *-sequent) os=-ptx ;; *-crds) os=-unos ;; *-ns) os=-genix ;; i370-*) os=-mvs ;; *-next) os=-nextstep3 ;; *-gould) os=-sysv ;; *-highlevel) os=-bsd ;; *-encore) os=-bsd ;; *-sgi) os=-irix ;; *-siemens) os=-sysv4 ;; *-masscomp) os=-rtu ;; f30[01]-fujitsu | f700-fujitsu) os=-uxpv ;; *-rom68k) os=-coff ;; *-*bug) os=-coff ;; *-apple) os=-macos ;; *-atari*) os=-mint ;; *) os=-none ;; esac fi # Here we handle the case where we know the os, and the CPU type, but not the # manufacturer. We pick the logical manufacturer. vendor=unknown case $basic_machine in *-unknown) case $os in -riscix*) vendor=acorn ;; -sunos*) vendor=sun ;; -cnk*|-aix*) vendor=ibm ;; -beos*) vendor=be ;; -hpux*) vendor=hp ;; -mpeix*) vendor=hp ;; -hiux*) vendor=hitachi ;; -unos*) vendor=crds ;; -dgux*) vendor=dg ;; -luna*) vendor=omron ;; -genix*) vendor=ns ;; -mvs* | -opened*) vendor=ibm ;; -os400*) vendor=ibm ;; -ptx*) vendor=sequent ;; -tpf*) vendor=ibm ;; -vxsim* | -vxworks* | -windiss*) vendor=wrs ;; -aux*) vendor=apple ;; -hms*) vendor=hitachi ;; -mpw* | -macos*) vendor=apple ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) vendor=atari ;; -vos*) vendor=stratus ;; esac basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` ;; esac echo $basic_machine$os exit # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: sauerbraten-0.0.20130203.dfsg/enet/unix.c0000644000175000017500000002507512061673417017477 0ustar vincentvincent/** @file unix.c @brief ENet Unix system specific functions */ #ifndef WIN32 #include #include #include #include #include #include #include #include #include #include #define ENET_BUILDING_LIB 1 #include "enet/enet.h" #ifdef __APPLE__ #ifdef HAS_POLL #undef HAS_POLL #endif #ifndef HAS_FCNTL #define HAS_FCNTL 1 #endif #ifndef HAS_INET_PTON #define HAS_INET_PTON 1 #endif #ifndef HAS_INET_NTOP #define HAS_INET_NTOP 1 #endif #ifndef HAS_MSGHDR_FLAGS #define HAS_MSGHDR_FLAGS 1 #endif #ifndef HAS_SOCKLEN_T #define HAS_SOCKLEN_T 1 #endif #endif #ifdef HAS_FCNTL #include #endif #ifdef HAS_POLL #include #endif #ifndef HAS_SOCKLEN_T typedef int socklen_t; #endif #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif static enet_uint32 timeBase = 0; int enet_initialize (void) { return 0; } void enet_deinitialize (void) { } enet_uint32 enet_time_get (void) { struct timeval timeVal; gettimeofday (& timeVal, NULL); return timeVal.tv_sec * 1000 + timeVal.tv_usec / 1000 - timeBase; } void enet_time_set (enet_uint32 newTimeBase) { struct timeval timeVal; gettimeofday (& timeVal, NULL); timeBase = timeVal.tv_sec * 1000 + timeVal.tv_usec / 1000 - newTimeBase; } int enet_address_set_host (ENetAddress * address, const char * name) { struct hostent * hostEntry = NULL; #ifdef HAS_GETHOSTBYNAME_R struct hostent hostData; char buffer [2048]; int errnum; #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) gethostbyname_r (name, & hostData, buffer, sizeof (buffer), & hostEntry, & errnum); #else hostEntry = gethostbyname_r (name, & hostData, buffer, sizeof (buffer), & errnum); #endif #else hostEntry = gethostbyname (name); #endif if (hostEntry == NULL || hostEntry -> h_addrtype != AF_INET) { #ifdef HAS_INET_PTON if (! inet_pton (AF_INET, name, & address -> host)) #else if (! inet_aton (name, (struct in_addr *) & address -> host)) #endif return -1; return 0; } address -> host = * (enet_uint32 *) hostEntry -> h_addr_list [0]; return 0; } int enet_address_get_host_ip (const ENetAddress * address, char * name, size_t nameLength) { #ifdef HAS_INET_NTOP if (inet_ntop (AF_INET, & address -> host, name, nameLength) == NULL) #else char * addr = inet_ntoa (* (struct in_addr *) & address -> host); if (addr != NULL) strncpy (name, addr, nameLength); else #endif return -1; return 0; } int enet_address_get_host (const ENetAddress * address, char * name, size_t nameLength) { struct in_addr in; struct hostent * hostEntry = NULL; #ifdef HAS_GETHOSTBYADDR_R struct hostent hostData; char buffer [2048]; int errnum; in.s_addr = address -> host; #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) gethostbyaddr_r ((char *) & in, sizeof (struct in_addr), AF_INET, & hostData, buffer, sizeof (buffer), & hostEntry, & errnum); #else hostEntry = gethostbyaddr_r ((char *) & in, sizeof (struct in_addr), AF_INET, & hostData, buffer, sizeof (buffer), & errnum); #endif #else in.s_addr = address -> host; hostEntry = gethostbyaddr ((char *) & in, sizeof (struct in_addr), AF_INET); #endif if (hostEntry == NULL) return enet_address_get_host_ip (address, name, nameLength); strncpy (name, hostEntry -> h_name, nameLength); return 0; } int enet_socket_bind (ENetSocket socket, const ENetAddress * address) { struct sockaddr_in sin; memset (& sin, 0, sizeof (struct sockaddr_in)); sin.sin_family = AF_INET; if (address != NULL) { sin.sin_port = ENET_HOST_TO_NET_16 (address -> port); sin.sin_addr.s_addr = address -> host; } else { sin.sin_port = 0; sin.sin_addr.s_addr = INADDR_ANY; } return bind (socket, (struct sockaddr *) & sin, sizeof (struct sockaddr_in)); } int enet_socket_listen (ENetSocket socket, int backlog) { return listen (socket, backlog < 0 ? SOMAXCONN : backlog); } ENetSocket enet_socket_create (ENetSocketType type) { return socket (PF_INET, type == ENET_SOCKET_TYPE_DATAGRAM ? SOCK_DGRAM : SOCK_STREAM, 0); } int enet_socket_set_option (ENetSocket socket, ENetSocketOption option, int value) { int result = -1; switch (option) { case ENET_SOCKOPT_NONBLOCK: #ifdef HAS_FCNTL result = fcntl (socket, F_SETFL, O_NONBLOCK | fcntl (socket, F_GETFL)); #else result = ioctl (socket, FIONBIO, & value); #endif break; case ENET_SOCKOPT_BROADCAST: result = setsockopt (socket, SOL_SOCKET, SO_BROADCAST, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_REUSEADDR: result = setsockopt (socket, SOL_SOCKET, SO_REUSEADDR, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_RCVBUF: result = setsockopt (socket, SOL_SOCKET, SO_RCVBUF, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_SNDBUF: result = setsockopt (socket, SOL_SOCKET, SO_SNDBUF, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_RCVTIMEO: result = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, (char *) & value, sizeof (int)); break; case ENET_SOCKOPT_SNDTIMEO: result = setsockopt (socket, SOL_SOCKET, SO_SNDTIMEO, (char *) & value, sizeof (int)); break; default: break; } return result == -1 ? -1 : 0; } int enet_socket_connect (ENetSocket socket, const ENetAddress * address) { struct sockaddr_in sin; int result; memset (& sin, 0, sizeof (struct sockaddr_in)); sin.sin_family = AF_INET; sin.sin_port = ENET_HOST_TO_NET_16 (address -> port); sin.sin_addr.s_addr = address -> host; result = connect (socket, (struct sockaddr *) & sin, sizeof (struct sockaddr_in)); if (result == -1 && errno == EINPROGRESS) return 0; return result; } ENetSocket enet_socket_accept (ENetSocket socket, ENetAddress * address) { int result; struct sockaddr_in sin; socklen_t sinLength = sizeof (struct sockaddr_in); result = accept (socket, address != NULL ? (struct sockaddr *) & sin : NULL, address != NULL ? & sinLength : NULL); if (result == -1) return ENET_SOCKET_NULL; if (address != NULL) { address -> host = (enet_uint32) sin.sin_addr.s_addr; address -> port = ENET_NET_TO_HOST_16 (sin.sin_port); } return result; } int enet_socket_shutdown (ENetSocket socket, ENetSocketShutdown how) { return shutdown (socket, (int) how); } void enet_socket_destroy (ENetSocket socket) { if (socket != -1) close (socket); } int enet_socket_send (ENetSocket socket, const ENetAddress * address, const ENetBuffer * buffers, size_t bufferCount) { struct msghdr msgHdr; struct sockaddr_in sin; int sentLength; memset (& msgHdr, 0, sizeof (struct msghdr)); if (address != NULL) { memset (& sin, 0, sizeof (struct sockaddr_in)); sin.sin_family = AF_INET; sin.sin_port = ENET_HOST_TO_NET_16 (address -> port); sin.sin_addr.s_addr = address -> host; msgHdr.msg_name = & sin; msgHdr.msg_namelen = sizeof (struct sockaddr_in); } msgHdr.msg_iov = (struct iovec *) buffers; msgHdr.msg_iovlen = bufferCount; sentLength = sendmsg (socket, & msgHdr, MSG_NOSIGNAL); if (sentLength == -1) { if (errno == EWOULDBLOCK) return 0; return -1; } return sentLength; } int enet_socket_receive (ENetSocket socket, ENetAddress * address, ENetBuffer * buffers, size_t bufferCount) { struct msghdr msgHdr; struct sockaddr_in sin; int recvLength; memset (& msgHdr, 0, sizeof (struct msghdr)); if (address != NULL) { msgHdr.msg_name = & sin; msgHdr.msg_namelen = sizeof (struct sockaddr_in); } msgHdr.msg_iov = (struct iovec *) buffers; msgHdr.msg_iovlen = bufferCount; recvLength = recvmsg (socket, & msgHdr, MSG_NOSIGNAL); if (recvLength == -1) { if (errno == EWOULDBLOCK) return 0; return -1; } #ifdef HAS_MSGHDR_FLAGS if (msgHdr.msg_flags & MSG_TRUNC) return -1; #endif if (address != NULL) { address -> host = (enet_uint32) sin.sin_addr.s_addr; address -> port = ENET_NET_TO_HOST_16 (sin.sin_port); } return recvLength; } int enet_socketset_select (ENetSocket maxSocket, ENetSocketSet * readSet, ENetSocketSet * writeSet, enet_uint32 timeout) { struct timeval timeVal; timeVal.tv_sec = timeout / 1000; timeVal.tv_usec = (timeout % 1000) * 1000; return select (maxSocket + 1, readSet, writeSet, NULL, & timeVal); } int enet_socket_wait (ENetSocket socket, enet_uint32 * condition, enet_uint32 timeout) { #ifdef HAS_POLL struct pollfd pollSocket; int pollCount; pollSocket.fd = socket; pollSocket.events = 0; if (* condition & ENET_SOCKET_WAIT_SEND) pollSocket.events |= POLLOUT; if (* condition & ENET_SOCKET_WAIT_RECEIVE) pollSocket.events |= POLLIN; pollCount = poll (& pollSocket, 1, timeout); if (pollCount < 0) return -1; * condition = ENET_SOCKET_WAIT_NONE; if (pollCount == 0) return 0; if (pollSocket.revents & POLLOUT) * condition |= ENET_SOCKET_WAIT_SEND; if (pollSocket.revents & POLLIN) * condition |= ENET_SOCKET_WAIT_RECEIVE; return 0; #else fd_set readSet, writeSet; struct timeval timeVal; int selectCount; timeVal.tv_sec = timeout / 1000; timeVal.tv_usec = (timeout % 1000) * 1000; FD_ZERO (& readSet); FD_ZERO (& writeSet); if (* condition & ENET_SOCKET_WAIT_SEND) FD_SET (socket, & writeSet); if (* condition & ENET_SOCKET_WAIT_RECEIVE) FD_SET (socket, & readSet); selectCount = select (socket + 1, & readSet, & writeSet, NULL, & timeVal); if (selectCount < 0) return -1; * condition = ENET_SOCKET_WAIT_NONE; if (selectCount == 0) return 0; if (FD_ISSET (socket, & writeSet)) * condition |= ENET_SOCKET_WAIT_SEND; if (FD_ISSET (socket, & readSet)) * condition |= ENET_SOCKET_WAIT_RECEIVE; return 0; #endif } #endif sauerbraten-0.0.20130203.dfsg/enet/packet.c0000644000175000017500000000744512061673417017764 0ustar vincentvincent/** @file packet.c @brief ENet packet management functions */ #include #define ENET_BUILDING_LIB 1 #include "enet/enet.h" /** @defgroup Packet ENet packet functions @{ */ /** Creates a packet that may be sent to a peer. @param dataContents initial contents of the packet's data; the packet's data will remain uninitialized if dataContents is NULL. @param dataLength size of the data allocated for this packet @param flags flags for this packet as described for the ENetPacket structure. @returns the packet on success, NULL on failure */ ENetPacket * enet_packet_create (const void * data, size_t dataLength, enet_uint32 flags) { ENetPacket * packet = (ENetPacket *) enet_malloc (sizeof (ENetPacket)); if (packet == NULL) return NULL; if (flags & ENET_PACKET_FLAG_NO_ALLOCATE) packet -> data = (enet_uint8 *) data; else if (dataLength <= 0) packet -> data = NULL; else { packet -> data = (enet_uint8 *) enet_malloc (dataLength); if (packet -> data == NULL) { enet_free (packet); return NULL; } if (data != NULL) memcpy (packet -> data, data, dataLength); } packet -> referenceCount = 0; packet -> flags = flags; packet -> dataLength = dataLength; packet -> freeCallback = NULL; return packet; } /** Destroys the packet and deallocates its data. @param packet packet to be destroyed */ void enet_packet_destroy (ENetPacket * packet) { if (packet == NULL) return; if (packet -> freeCallback != NULL) (* packet -> freeCallback) (packet); if (! (packet -> flags & ENET_PACKET_FLAG_NO_ALLOCATE) && packet -> data != NULL) enet_free (packet -> data); enet_free (packet); } /** Attempts to resize the data in the packet to length specified in the dataLength parameter @param packet packet to resize @param dataLength new size for the packet data @returns 0 on success, < 0 on failure */ int enet_packet_resize (ENetPacket * packet, size_t dataLength) { enet_uint8 * newData; if (dataLength <= packet -> dataLength || (packet -> flags & ENET_PACKET_FLAG_NO_ALLOCATE)) { packet -> dataLength = dataLength; return 0; } newData = (enet_uint8 *) enet_malloc (dataLength); if (newData == NULL) return -1; memcpy (newData, packet -> data, packet -> dataLength); enet_free (packet -> data); packet -> data = newData; packet -> dataLength = dataLength; return 0; } static int initializedCRC32 = 0; static enet_uint32 crcTable [256]; static enet_uint32 reflect_crc (int val, int bits) { int result = 0, bit; for (bit = 0; bit < bits; bit ++) { if(val & 1) result |= 1 << (bits - 1 - bit); val >>= 1; } return result; } static void initialize_crc32 () { int byte; for (byte = 0; byte < 256; ++ byte) { enet_uint32 crc = reflect_crc (byte, 8) << 24; int offset; for(offset = 0; offset < 8; ++ offset) { if (crc & 0x80000000) crc = (crc << 1) ^ 0x04c11db7; else crc <<= 1; } crcTable [byte] = reflect_crc (crc, 32); } initializedCRC32 = 1; } enet_uint32 enet_crc32 (const ENetBuffer * buffers, size_t bufferCount) { enet_uint32 crc = 0xFFFFFFFF; if (! initializedCRC32) initialize_crc32 (); while (bufferCount -- > 0) { const enet_uint8 * data = (const enet_uint8 *) buffers -> data, * dataEnd = & data [buffers -> dataLength]; while (data < dataEnd) { crc = (crc >> 8) ^ crcTable [(crc & 0xFF) ^ *data++]; } ++ buffers; } return ENET_HOST_TO_NET_32 (~ crc); } /** @} */ sauerbraten-0.0.20130203.dfsg/enet/depcomp0000755000175000017500000005064312006035707017715 0ustar vincentvincent#! /bin/sh # depcomp - compile a program generating dependencies as side-effects scriptversion=2012-03-27.16; # UTC # Copyright (C) 1999, 2000, 2003, 2004, 2005, 2006, 2007, 2009, 2010, # 2011, 2012 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program 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 General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Originally written by Alexandre Oliva . case $1 in '') echo "$0: No command. Try '$0 --help' for more information." 1>&2 exit 1; ;; -h | --h*) cat <<\EOF Usage: depcomp [--help] [--version] PROGRAM [ARGS] Run PROGRAMS ARGS to compile a file, generating dependencies as side-effects. Environment variables: depmode Dependency tracking mode. source Source file read by 'PROGRAMS ARGS'. object Object file output by 'PROGRAMS ARGS'. DEPDIR directory where to store dependencies. depfile Dependency file to output. tmpdepfile Temporary file to use when outputting dependencies. libtool Whether libtool is used (yes/no). Report bugs to . EOF exit $? ;; -v | --v*) echo "depcomp $scriptversion" exit $? ;; esac # A tabulation character. tab=' ' # A newline character. nl=' ' if test -z "$depmode" || test -z "$source" || test -z "$object"; then echo "depcomp: Variables source, object and depmode must be set" 1>&2 exit 1 fi # Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po. depfile=${depfile-`echo "$object" | sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`} tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} rm -f "$tmpdepfile" # Some modes work just like other modes, but use different flags. We # parameterize here, but still list the modes in the big case below, # to make depend.m4 easier to write. Note that we *cannot* use a case # here, because this file can only contain one case statement. if test "$depmode" = hp; then # HP compiler uses -M and no extra arg. gccflag=-M depmode=gcc fi if test "$depmode" = dashXmstdout; then # This is just like dashmstdout with a different argument. dashmflag=-xM depmode=dashmstdout fi cygpath_u="cygpath -u -f -" if test "$depmode" = msvcmsys; then # This is just like msvisualcpp but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvisualcpp fi if test "$depmode" = msvc7msys; then # This is just like msvc7 but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvc7 fi if test "$depmode" = xlc; then # IBM C/C++ Compilers xlc/xlC can output gcc-like dependency informations. gccflag=-qmakedep=gcc,-MF depmode=gcc fi case "$depmode" in gcc3) ## gcc 3 implements dependency tracking that does exactly what ## we want. Yay! Note: for some reason libtool 1.4 doesn't like ## it if -MD -MP comes after the -MF stuff. Hmm. ## Unfortunately, FreeBSD c89 acceptance of flags depends upon ## the command line argument order; so add the flags where they ## appear in depend2.am. Note that the slowdown incurred here ## affects only configure: in makefiles, %FASTDEP% shortcuts this. for arg do case $arg in -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;; *) set fnord "$@" "$arg" ;; esac shift # fnord shift # $arg done "$@" stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile" exit $stat fi mv "$tmpdepfile" "$depfile" ;; gcc) ## There are various ways to get dependency output from gcc. Here's ## why we pick this rather obscure method: ## - Don't want to use -MD because we'd like the dependencies to end ## up in a subdir. Having to rename by hand is ugly. ## (We might end up doing this anyway to support other compilers.) ## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like ## -MM, not -M (despite what the docs say). ## - Using -M directly means running the compiler twice (even worse ## than renaming). if test -z "$gccflag"; then gccflag=-MD, fi "$@" -Wp,"$gccflag$tmpdepfile" stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ## The second -e expression handles DOS-style file names with drive letters. sed -e 's/^[^:]*: / /' \ -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile" ## This next piece of magic avoids the "deleted header file" problem. ## The problem is that when a header file which appears in a .P file ## is deleted, the dependency causes make to die (because there is ## typically no way to rebuild the header). We avoid this by adding ## dummy dependencies for each header file. Too bad gcc doesn't do ## this for us directly. tr ' ' "$nl" < "$tmpdepfile" | ## Some versions of gcc put a space before the ':'. On the theory ## that the space means something, we add a space to the output as ## well. hp depmode also adds that space, but also prefixes the VPATH ## to the object. Take care to not repeat it in the output. ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; hp) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; sgi) if test "$libtool" = yes; then "$@" "-Wp,-MDupdate,$tmpdepfile" else "$@" -MDupdate "$tmpdepfile" fi stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files echo "$object : \\" > "$depfile" # Clip off the initial element (the dependent). Don't try to be # clever and replace this with sed code, as IRIX sed won't handle # lines with more than a fixed number of characters (4096 in # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines; # the IRIX cc adds comments like '#:fec' to the end of the # dependency line. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \ tr "$nl" ' ' >> "$depfile" echo >> "$depfile" # The second pass generates a dummy entry for each header file. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \ >> "$depfile" else # The sourcefile does not contain any dependencies, so just # store a dummy comment line, to avoid errors with the Makefile # "include basename.Plo" scheme. echo "#dummy" > "$depfile" fi rm -f "$tmpdepfile" ;; xlc) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; aix) # The C for AIX Compiler uses -M and outputs the dependencies # in a .u file. In older versions, this file always lives in the # current directory. Also, the AIX compiler puts '$object:' at the # start of each line; $object doesn't have directory information. # Version 6 uses the directory in both cases. dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` test "x$dir" = "x$object" && dir= base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` if test "$libtool" = yes; then tmpdepfile1=$dir$base.u tmpdepfile2=$base.u tmpdepfile3=$dir.libs/$base.u "$@" -Wc,-M else tmpdepfile1=$dir$base.u tmpdepfile2=$dir$base.u tmpdepfile3=$dir$base.u "$@" -M fi stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then # Each line is of the form 'foo.o: dependent.h'. # Do two passes, one to just change these to # '$object: dependent.h' and one to simply 'dependent.h:'. sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile" sed -e 's,^.*\.[a-z]*:['"$tab"' ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile" else # The sourcefile does not contain any dependencies, so just # store a dummy comment line, to avoid errors with the Makefile # "include basename.Plo" scheme. echo "#dummy" > "$depfile" fi rm -f "$tmpdepfile" ;; icc) # Intel's C compiler anf tcc (Tiny C Compiler) understand '-MD -MF file'. # However on # $CC -MD -MF foo.d -c -o sub/foo.o sub/foo.c # ICC 7.0 will fill foo.d with something like # foo.o: sub/foo.c # foo.o: sub/foo.h # which is wrong. We want # sub/foo.o: sub/foo.c # sub/foo.o: sub/foo.h # sub/foo.c: # sub/foo.h: # ICC 7.1 will output # foo.o: sub/foo.c sub/foo.h # and will wrap long lines using '\': # foo.o: sub/foo.c ... \ # sub/foo.h ... \ # ... # tcc 0.9.26 (FIXME still under development at the moment of writing) # will emit a similar output, but also prepend the continuation lines # with horizontal tabulation characters. "$@" -MD -MF "$tmpdepfile" stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" # Each line is of the form 'foo.o: dependent.h', # or 'foo.o: dep1.h dep2.h \', or ' dep3.h dep4.h \'. # Do two passes, one to just change these to # '$object: dependent.h' and one to simply 'dependent.h:'. sed -e "s/^[ $tab][ $tab]*/ /" -e "s,^[^:]*:,$object :," \ < "$tmpdepfile" > "$depfile" sed ' s/[ '"$tab"'][ '"$tab"']*/ /g s/^ *// s/ *\\*$// s/^[^:]*: *// /^$/d /:$/d s/$/ :/ ' < "$tmpdepfile" >> "$depfile" rm -f "$tmpdepfile" ;; hp2) # The "hp" stanza above does not work with aCC (C++) and HP's ia64 # compilers, which have integrated preprocessors. The correct option # to use with these is +Maked; it writes dependencies to a file named # 'foo.d', which lands next to the object file, wherever that # happens to be. # Much of this is similar to the tru64 case; see comments there. dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` test "x$dir" = "x$object" && dir= base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` if test "$libtool" = yes; then tmpdepfile1=$dir$base.d tmpdepfile2=$dir.libs/$base.d "$@" -Wc,+Maked else tmpdepfile1=$dir$base.d tmpdepfile2=$dir$base.d "$@" +Maked fi stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile1" "$tmpdepfile2" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then sed -e "s,^.*\.[a-z]*:,$object:," "$tmpdepfile" > "$depfile" # Add 'dependent.h:' lines. sed -ne '2,${ s/^ *// s/ \\*$// s/$/:/ p }' "$tmpdepfile" >> "$depfile" else echo "#dummy" > "$depfile" fi rm -f "$tmpdepfile" "$tmpdepfile2" ;; tru64) # The Tru64 compiler uses -MD to generate dependencies as a side # effect. 'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'. # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put # dependencies in 'foo.d' instead, so we check for that too. # Subdirectories are respected. dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` test "x$dir" = "x$object" && dir= base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` if test "$libtool" = yes; then # With Tru64 cc, shared objects can also be used to make a # static library. This mechanism is used in libtool 1.4 series to # handle both shared and static libraries in a single compilation. # With libtool 1.4, dependencies were output in $dir.libs/$base.lo.d. # # With libtool 1.5 this exception was removed, and libtool now # generates 2 separate objects for the 2 libraries. These two # compilations output dependencies in $dir.libs/$base.o.d and # in $dir$base.o.d. We have to check for both files, because # one of the two compilations can be disabled. We should prefer # $dir$base.o.d over $dir.libs/$base.o.d because the latter is # automatically cleaned when .libs/ is deleted, while ignoring # the former would cause a distcleancheck panic. tmpdepfile1=$dir.libs/$base.lo.d # libtool 1.4 tmpdepfile2=$dir$base.o.d # libtool 1.5 tmpdepfile3=$dir.libs/$base.o.d # libtool 1.5 tmpdepfile4=$dir.libs/$base.d # Compaq CCC V6.2-504 "$@" -Wc,-MD else tmpdepfile1=$dir$base.o.d tmpdepfile2=$dir$base.d tmpdepfile3=$dir$base.d tmpdepfile4=$dir$base.d "$@" -MD fi stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile" sed -e 's,^.*\.[a-z]*:['"$tab"' ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile" else echo "#dummy" > "$depfile" fi rm -f "$tmpdepfile" ;; msvc7) if test "$libtool" = yes; then showIncludes=-Wc,-showIncludes else showIncludes=-showIncludes fi "$@" $showIncludes > "$tmpdepfile" stat=$? grep -v '^Note: including file: ' "$tmpdepfile" if test "$stat" = 0; then : else rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" # The first sed program below extracts the file names and escapes # backslashes for cygpath. The second sed program outputs the file # name when reading, but also accumulates all include files in the # hold buffer in order to output them again at the end. This only # works with sed implementations that can handle large buffers. sed < "$tmpdepfile" -n ' /^Note: including file: *\(.*\)/ { s//\1/ s/\\/\\\\/g p }' | $cygpath_u | sort -u | sed -n ' s/ /\\ /g s/\(.*\)/'"$tab"'\1 \\/p s/.\(.*\) \\/\1:/ H $ { s/.*/'"$tab"'/ G p }' >> "$depfile" rm -f "$tmpdepfile" ;; msvc7msys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; #nosideeffect) # This comment above is used by automake to tell side-effect # dependency tracking mechanisms from slower ones. dashmstdout) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout, regardless of -o. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done test -z "$dashmflag" && dashmflag=-M # Require at least two characters before searching for ':' # in the target name. This is to cope with DOS-style filenames: # a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise. "$@" $dashmflag | sed 's:^['"$tab"' ]*[^:'"$tab"' ][^:][^:]*\:['"$tab"' ]*:'"$object"'\: :' > "$tmpdepfile" rm -f "$depfile" cat < "$tmpdepfile" > "$depfile" tr ' ' "$nl" < "$tmpdepfile" | \ ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; dashXmstdout) # This case only exists to satisfy depend.m4. It is never actually # run, as this mode is specially recognized in the preamble. exit 1 ;; makedepend) "$@" || exit $? # Remove any Libtool call if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # X makedepend shift cleared=no eat=no for arg do case $cleared in no) set ""; shift cleared=yes ;; esac if test $eat = yes; then eat=no continue fi case "$arg" in -D*|-I*) set fnord "$@" "$arg"; shift ;; # Strip any option that makedepend may not understand. Remove # the object too, otherwise makedepend will parse it as a source file. -arch) eat=yes ;; -*|$object) ;; *) set fnord "$@" "$arg"; shift ;; esac done obj_suffix=`echo "$object" | sed 's/^.*\././'` touch "$tmpdepfile" ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@" rm -f "$depfile" # makedepend may prepend the VPATH from the source file name to the object. # No need to regex-escape $object, excess matching of '.' is harmless. sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile" sed '1,2d' "$tmpdepfile" | tr ' ' "$nl" | \ ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" "$tmpdepfile".bak ;; cpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done "$@" -E | sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' | sed '$ s: \\$::' > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" cat < "$tmpdepfile" >> "$depfile" sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; msvisualcpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi IFS=" " for arg do case "$arg" in -o) shift ;; $object) shift ;; "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI") set fnord "$@" shift shift ;; *) set fnord "$@" "$arg" shift shift ;; esac done "$@" -E 2>/dev/null | sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile" echo "$tab" >> "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile" rm -f "$tmpdepfile" ;; msvcmsys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; none) exec "$@" ;; *) echo "Unknown depmode $depmode" 1>&2 exit 1 ;; esac exit 0 # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: sauerbraten-0.0.20130203.dfsg/enet/LICENSE0000644000175000017500000000204411761204106017333 0ustar vincentvincentCopyright (c) 2002-2012 Lee Salzman Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. sauerbraten-0.0.20130203.dfsg/enet/README0000644000175000017500000000045611373036002017210 0ustar vincentvincentPlease visit the ENet homepage at http://enet.bespin.org for installation and usage instructions. If you obtained this package from CVS, the quick description on how to build is: # Generate the build system. autoreconf -vfi # Compile and install the library. ./configure && make && make install sauerbraten-0.0.20130203.dfsg/enet/enet.dsp0000644000175000017500000000770711377327351020017 0ustar vincentvincent# Microsoft Developer Studio Project File - Name="enet" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Static Library" 0x0104 CFG=enet - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "enet.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "enet.mak" CFG="enet - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "enet - Win32 Release" (based on "Win32 (x86) Static Library") !MESSAGE "enet - Win32 Debug" (based on "Win32 (x86) Static Library") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe !IF "$(CFG)" == "enet - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release" # PROP Intermediate_Dir "Release" # PROP Target_Dir "" MTL=midl.exe # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c # ADD CPP /nologo /W3 /O2 /I "include" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /FD /c # SUBTRACT CPP /YX # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LIB32=link.exe -lib # ADD BASE LIB32 /nologo # ADD LIB32 /nologo !ELSEIF "$(CFG)" == "enet - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug" # PROP Intermediate_Dir "Debug" # PROP Target_Dir "" MTL=midl.exe # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c # ADD CPP /nologo /G6 /MTd /W3 /ZI /Od /I "include" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /FR /FD /GZ /c # SUBTRACT CPP /YX # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LIB32=link.exe -lib # ADD BASE LIB32 /nologo # ADD LIB32 /nologo !ENDIF # Begin Target # Name "enet - Win32 Release" # Name "enet - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\host.c # End Source File # Begin Source File SOURCE=.\list.c # End Source File # Begin Source File SOURCE=.\callbacks.c # End Source File # Begin Source File SOURCE=.\compress.c # End Source File # Begin Source File SOURCE=.\packet.c # End Source File # Begin Source File SOURCE=.\peer.c # End Source File # Begin Source File SOURCE=.\protocol.c # End Source File # Begin Source File SOURCE=.\unix.c # End Source File # Begin Source File SOURCE=.\win32.c # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE=.\include\enet\enet.h # End Source File # Begin Source File SOURCE=.\include\enet\list.h # End Source File # Begin Source File SOURCE=.\include\enet\callbacks.h # End Source File # Begin Source File SOURCE=.\include\enet\protocol.h # End Source File # Begin Source File SOURCE=.\include\enet\time.h # End Source File # Begin Source File SOURCE=.\include\enet\types.h # End Source File # Begin Source File SOURCE=.\include\enet\unix.h # End Source File # Begin Source File SOURCE=.\include\enet\utility.h # End Source File # Begin Source File SOURCE=.\include\enet\win32.h # End Source File # End Group # End Target # End Project sauerbraten-0.0.20130203.dfsg/enet/configure0000755000175000017500000142545212061673417020263 0ustar vincentvincent#! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.69 for libenet 1.3.6. # # # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. # # # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Use a proper internal environment variable to ensure we don't fall # into an infinite loop, continuously re-executing ourselves. if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then _as_can_reexec=no; export _as_can_reexec; # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 as_fn_exit 255 fi # We don't want this to propagate to other subprocesses. { _as_can_reexec=; unset _as_can_reexec;} if test "x$CONFIG_SHELL" = x; then as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi " as_required="as_fn_return () { (exit \$1); } as_fn_success () { as_fn_return 0; } as_fn_failure () { as_fn_return 1; } as_fn_ret_success () { return 0; } as_fn_ret_failure () { return 1; } exitcode=0 as_fn_success || { exitcode=1; echo as_fn_success failed.; } as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : else exitcode=1; echo positional parameters were not saved. fi test x\$exitcode = x0 || exit 1 test -x / || exit 1" as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 test -n \"\${ZSH_VERSION+set}\${BASH_VERSION+set}\" || ( ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO PATH=/empty FPATH=/empty; export PATH FPATH test \"X\`printf %s \$ECHO\`\" = \"X\$ECHO\" \\ || test \"X\`print -r -- \$ECHO\`\" = \"X\$ECHO\" ) || exit 1 test \$(( 1 + 1 )) = 2 || exit 1" if (eval "$as_required") 2>/dev/null; then : as_have_required=yes else as_have_required=no fi if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. as_found=: case $as_dir in #( /*) for as_base in sh bash ksh sh5; do # Try only shells that exist, to save several forks. as_shell=$as_dir/$as_base if { test -f "$as_shell" || test -f "$as_shell.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : CONFIG_SHELL=$as_shell as_have_required=yes if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : break 2 fi fi done;; esac as_found=false done $as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : CONFIG_SHELL=$SHELL as_have_required=yes fi; } IFS=$as_save_IFS if test "x$CONFIG_SHELL" != x; then : export CONFIG_SHELL # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi if test x$as_have_required = xno; then : $as_echo "$0: This script requires a shell more modern than all" $as_echo "$0: the shells that I found on your system." if test x${ZSH_VERSION+set} = xset ; then $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" $as_echo "$0: be upgraded to zsh 4.3.4 or later." else $as_echo "$0: Please tell bug-autoconf@gnu.org about your system, $0: including any error possibly output before this $0: message. Then install a modern shell, or manually run $0: the script under such a shell if you do have one." fi exit 1 fi fi fi SHELL=${CONFIG_SHELL-/bin/sh} export SHELL # Unset more variables known to interfere with behavior of common tools. CLICOLOR_FORCE= GREP_OPTIONS= unset CLICOLOR_FORCE GREP_OPTIONS ## --------------------- ## ## M4sh Shell Functions. ## ## --------------------- ## # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_lineno_1=$LINENO as_lineno_1a=$LINENO as_lineno_2=$LINENO as_lineno_2a=$LINENO eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # If we had to re-execute with $CONFIG_SHELL, we're ensured to have # already done that, so ensure we don't try to do so again and fall # in an infinite loop. This has already happened in practice. _as_can_reexec=no; export _as_can_reexec # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" SHELL=${CONFIG_SHELL-/bin/sh} test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= # Identity of this package. PACKAGE_NAME='libenet' PACKAGE_TARNAME='libenet' PACKAGE_VERSION='1.3.6' PACKAGE_STRING='libenet 1.3.6' PACKAGE_BUGREPORT='' PACKAGE_URL='' ac_unique_file="include/enet/enet.h" # Factoring default headers for most tests. ac_includes_default="\ #include #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef STDC_HEADERS # include # include #else # ifdef HAVE_STDLIB_H # include # endif #endif #ifdef HAVE_STRING_H # if !defined STDC_HEADERS && defined HAVE_MEMORY_H # include # endif # include #endif #ifdef HAVE_STRINGS_H # include #endif #ifdef HAVE_INTTYPES_H # include #endif #ifdef HAVE_STDINT_H # include #endif #ifdef HAVE_UNISTD_H # include #endif" ac_subst_vars='am__EXEEXT_FALSE am__EXEEXT_TRUE LTLIBOBJS LIBOBJS CPP OTOOL64 OTOOL LIPO NMEDIT DSYMUTIL MANIFEST_TOOL RANLIB ac_ct_AR AR DLLTOOL OBJDUMP LN_S NM ac_ct_DUMPBIN DUMPBIN LD FGREP EGREP GREP SED host_os host_vendor host_cpu host build_os build_vendor build_cpu build LIBTOOL am__fastdepCC_FALSE am__fastdepCC_TRUE CCDEPMODE am__nodep AMDEPBACKSLASH AMDEP_FALSE AMDEP_TRUE am__quote am__include DEPDIR OBJEXT EXEEXT ac_ct_CC CPPFLAGS LDFLAGS CFLAGS CC MAINT MAINTAINER_MODE_FALSE MAINTAINER_MODE_TRUE am__untar am__tar AMTAR am__leading_dot SET_MAKE AWK mkdir_p MKDIR_P INSTALL_STRIP_PROGRAM STRIP install_sh MAKEINFO AUTOHEADER AUTOMAKE AUTOCONF ACLOCAL VERSION PACKAGE CYGPATH_W am__isrc INSTALL_DATA INSTALL_SCRIPT INSTALL_PROGRAM target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_URL PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking enable_maintainer_mode enable_dependency_tracking enable_shared enable_static with_pic enable_fast_install with_gnu_ld with_sysroot enable_libtool_lock ' ac_precious_vars='build_alias host_alias target_alias CC CFLAGS LDFLAGS LIBS CPPFLAGS CPP' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *=) ac_optarg= ;; *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) as_fn_error $? "unrecognized option: \`$ac_option' Try \`$0 --help' for more information" ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` as_fn_error $? "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures libenet 1.3.6 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/libenet] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF Program names: --program-prefix=PREFIX prepend PREFIX to installed program names --program-suffix=SUFFIX append SUFFIX to installed program names --program-transform-name=PROGRAM run sed PROGRAM on installed program names System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in short | recursive ) echo "Configuration of libenet 1.3.6:";; esac cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --disable-maintainer-mode disable make rules and dependencies not useful (and sometimes confusing) to the casual installer --disable-dependency-tracking speeds up one-time build --enable-dependency-tracking do not reject slow dependency extractors --enable-shared[=PKGS] build shared libraries [default=yes] --enable-static[=PKGS] build static libraries [default=yes] --enable-fast-install[=PKGS] optimize for fast installation [default=yes] --disable-libtool-lock avoid locking (might break parallel builds) Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-pic[=PKGS] try to use only PIC/non-PIC objects [default=use both] --with-gnu-ld assume the C compiler uses GNU ld [default=no] --with-sysroot=DIR Search for dependent libraries within DIR (or the compiler's sysroot if not specified). Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to the package provider. _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for guested configure. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF libenet configure 1.3.6 generated by GNU Autoconf 2.69 Copyright (C) 2012 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi ## ------------------------ ## ## Autoconf initialization. ## ## ------------------------ ## # ac_fn_c_try_compile LINENO # -------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_compile # ac_fn_c_try_link LINENO # ----------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_link # ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists and can be compiled using the include files in # INCLUDES, setting the cache variable VAR accordingly. ac_fn_c_check_header_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_compile # ac_fn_c_try_cpp LINENO # ---------------------- # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_cpp # ac_fn_c_try_run LINENO # ---------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes # that executables *can* be run. ac_fn_c_try_run () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then : ac_retval=0 else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_run # ac_fn_c_check_func LINENO FUNC VAR # ---------------------------------- # Tests whether FUNC exists, setting the cache variable VAR accordingly ac_fn_c_check_func () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Define $2 to an innocuous variant, in case declares $2. For example, HP-UX 11i declares gettimeofday. */ #define $2 innocuous_$2 /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $2 (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $2 /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char $2 (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined __stub_$2 || defined __stub___$2 choke me #endif int main () { return $2 (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_func # ac_fn_c_check_member LINENO AGGR MEMBER VAR INCLUDES # ---------------------------------------------------- # Tries to find if the field MEMBER exists in type AGGR, after including # INCLUDES, setting cache variable VAR accordingly. ac_fn_c_check_member () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5 $as_echo_n "checking for $2.$3... " >&6; } if eval \${$4+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $5 int main () { static $2 ac_aggr; if (ac_aggr.$3) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$4=yes" else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $5 int main () { static $2 ac_aggr; if (sizeof ac_aggr.$3) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$4=yes" else eval "$4=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$4 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_member # ac_fn_c_check_type LINENO TYPE VAR INCLUDES # ------------------------------------------- # Tests whether TYPE exists after having included INCLUDES, setting cache # variable VAR accordingly. ac_fn_c_check_type () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=no" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { if (sizeof ($2)) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { if (sizeof (($2))) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else eval "$3=yes" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_type cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by libenet $as_me 1.3.6, which was generated by GNU Autoconf 2.69. Invocation command line was $ $0 $@ _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. $as_echo "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; 2) as_fn_append ac_configure_args1 " '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi as_fn_append ac_configure_args " '$ac_arg'" ;; esac done done { ac_configure_args0=; unset ac_configure_args0;} { ac_configure_args1=; unset ac_configure_args1;} # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { echo $as_echo "## ---------------- ## ## Cache variables. ## ## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo $as_echo "## ----------------- ## ## Output variables. ## ## ----------------- ##" echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then $as_echo "## ------------------- ## ## File substitutions. ## ## ------------------- ##" echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then $as_echo "## ----------- ## ## confdefs.h. ## ## ----------- ##" echo cat confdefs.h echo fi test "$ac_signal" != 0 && $as_echo "$as_me: caught signal $ac_signal" $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h $as_echo "/* confdefs.h */" > confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_URL "$PACKAGE_URL" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then # We do not want a PATH search for config.site. case $CONFIG_SITE in #(( -*) ac_site_file1=./$CONFIG_SITE;; */*) ac_site_file1=$CONFIG_SITE;; *) ac_site_file1=./$CONFIG_SITE;; esac elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site else ac_site_file1=$ac_default_prefix/share/config.site ac_site_file2=$ac_default_prefix/etc/config.site fi for ac_site_file in "$ac_site_file1" "$ac_site_file2" do test "x$ac_site_file" = xNONE && continue if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" \ || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file See \`config.log' for more details" "$LINENO" 5; } fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special files # actually), so we avoid doing that. DJGPP emulates it as a regular file. if test /dev/null != "$cache_file" && test -f "$cache_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 $as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 $as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 $as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 $as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 $as_echo "$as_me: former value: \`$ac_old_val'" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 $as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) as_fn_append ac_configure_args " '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## ## Main body of script. ## ## -------------------- ## ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu am__api_version='1.11' ac_aux_dir= for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do if test -f "$ac_dir/install-sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install-sh -c" break elif test -f "$ac_dir/install.sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install.sh -c" break elif test -f "$ac_dir/shtool"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/shtool install -c" break fi done if test -z "$ac_aux_dir"; then as_fn_error $? "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5 fi # These three variables are undocumented and unsupported, # and are intended to be withdrawn in a future Autoconf release. # They can cause serious problems if a builder's source tree is in a directory # whose full name contains unusual characters. ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. # Find a good install program. We prefer a C program (faster), # so one script is as good as another. But avoid the broken or # incompatible versions: # SysV /etc/install, /usr/sbin/install # SunOS /usr/etc/install # IRIX /sbin/install # AIX /bin/install # AmigaOS /C/install, which installs bootblocks on floppy discs # AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag # AFS /usr/afsws/bin/install, which mishandles nonexistent args # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. # Reject install programs that cannot install multiple files. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 $as_echo_n "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then if ${ac_cv_path_install+:} false; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. # Account for people who put trailing slashes in PATH elements. case $as_dir/ in #(( ./ | .// | /[cC]/* | \ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ /usr/ucb/* ) ;; *) # OSF1 and SCO ODT 3.0 have their own names for install. # Don't use installbsd from OSF since it installs stuff as root # by default. for ac_prog in ginstall scoinst install; do for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then if test $ac_prog = install && grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # AIX install. It has an incompatible calling convention. : elif test $ac_prog = install && grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # program-specific install script used by HP pwplus--don't use. : else rm -rf conftest.one conftest.two conftest.dir echo one > conftest.one echo two > conftest.two mkdir conftest.dir if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && test -s conftest.one && test -s conftest.two && test -s conftest.dir/conftest.one && test -s conftest.dir/conftest.two then ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" break 3 fi fi fi done done ;; esac done IFS=$as_save_IFS rm -rf conftest.one conftest.two conftest.dir fi if test "${ac_cv_path_install+set}" = set; then INSTALL=$ac_cv_path_install else # As a last resort, use the slow shell script. Don't cache a # value for INSTALL within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. INSTALL=$ac_install_sh fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 $as_echo "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build environment is sane" >&5 $as_echo_n "checking whether build environment is sane... " >&6; } # Just in case sleep 1 echo timestamp > conftest.file # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[\\\"\#\$\&\'\`$am_lf]*) as_fn_error $? "unsafe absolute working directory name" "$LINENO" 5;; esac case $srcdir in *[\\\"\#\$\&\'\`$am_lf\ \ ]*) as_fn_error $? "unsafe srcdir value: \`$srcdir'" "$LINENO" 5;; esac # Do `set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` if test "$*" = "X"; then # -L didn't work. set X `ls -t "$srcdir/configure" conftest.file` fi rm -f conftest.file if test "$*" != "X $srcdir/configure conftest.file" \ && test "$*" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". as_fn_error $? "ls -t appears to fail. Make sure there is not a broken alias in your environment" "$LINENO" 5 fi test "$2" = conftest.file ) then # Ok. : else as_fn_error $? "newly created file is older than distributed files! Check your system clock" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } test "$program_prefix" != NONE && program_transform_name="s&^&$program_prefix&;$program_transform_name" # Use a double $ so make ignores it. test "$program_suffix" != NONE && program_transform_name="s&\$&$program_suffix&;$program_transform_name" # Double any \ or $. # By default was `s,x,x', remove it if useless. ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"` # expand $ac_aux_dir to an absolute path am_aux_dir=`cd $ac_aux_dir && pwd` if test x"${MISSING+set}" != xset; then case $am_aux_dir in *\ * | *\ *) MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; *) MISSING="\${SHELL} $am_aux_dir/missing" ;; esac fi # Use eval to expand $SHELL if eval "$MISSING --run true"; then am_missing_run="$MISSING --run " else am_missing_run= { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`missing' script is too old or missing" >&5 $as_echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;} fi if test x"${install_sh}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi # Installed binaries are usually stripped using `strip' when the user # run `make install-strip'. However `strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the `STRIP' environment variable to overrule this program. if test "$cross_compiling" != no; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 $as_echo "$STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 $as_echo "$ac_ct_STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a thread-safe mkdir -p" >&5 $as_echo_n "checking for a thread-safe mkdir -p... " >&6; } if test -z "$MKDIR_P"; then if ${ac_cv_path_mkdir+:} false; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in mkdir gmkdir; do for ac_exec_ext in '' $ac_executable_extensions; do as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext" || continue case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #( 'mkdir (GNU coreutils) '* | \ 'mkdir (coreutils) '* | \ 'mkdir (fileutils) '4.1*) ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext break 3;; esac done done done IFS=$as_save_IFS fi test -d ./--version && rmdir ./--version if test "${ac_cv_path_mkdir+set}" = set; then MKDIR_P="$ac_cv_path_mkdir -p" else # As a last resort, use the slow shell script. Don't cache a # value for MKDIR_P within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. MKDIR_P="$ac_install_sh -d" fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5 $as_echo "$MKDIR_P" >&6; } mkdir_p="$MKDIR_P" case $mkdir_p in [\\/$]* | ?:[\\/]*) ;; */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; esac for ac_prog in gawk mawk nawk awk do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AWK+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AWK"; then ac_cv_prog_AWK="$AWK" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AWK="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AWK=$ac_cv_prog_AWK if test -n "$AWK"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 $as_echo "$AWK" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AWK" && break done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 $as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } set x ${MAKE-make} ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then : $as_echo_n "(cached) " >&6 else cat >conftest.make <<\_ACEOF SHELL = /bin/sh all: @echo '@@@%%%=$(MAKE)=@@@%%%' _ACEOF # GNU make sometimes prints "make[1]: Entering ...", which would confuse us. case `${MAKE-make} -f conftest.make 2>/dev/null` in *@@@%%%=?*=@@@%%%*) eval ac_cv_prog_make_${ac_make}_set=yes;; *) eval ac_cv_prog_make_${ac_make}_set=no;; esac rm -f conftest.make fi if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } SET_MAKE= else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } SET_MAKE="MAKE=${MAKE-make}" fi rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." am__isrc=' -I$(srcdir)' # test to see if srcdir already configured if test -f $srcdir/config.status; then as_fn_error $? "source directory already configured; run \"make distclean\" there first" "$LINENO" 5 fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi # Define the identity of the package. PACKAGE='libenet' VERSION='1.3.6' cat >>confdefs.h <<_ACEOF #define PACKAGE "$PACKAGE" _ACEOF cat >>confdefs.h <<_ACEOF #define VERSION "$VERSION" _ACEOF # Some tools Automake needs. ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} # We need awk for the "check" target. The system "awk" is bad on # some platforms. # Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AMTAR='$${TAR-tar}' am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -' { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable maintainer-specific portions of Makefiles" >&5 $as_echo_n "checking whether to enable maintainer-specific portions of Makefiles... " >&6; } # Check whether --enable-maintainer-mode was given. if test "${enable_maintainer_mode+set}" = set; then : enableval=$enable_maintainer_mode; USE_MAINTAINER_MODE=$enableval else USE_MAINTAINER_MODE=yes fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $USE_MAINTAINER_MODE" >&5 $as_echo "$USE_MAINTAINER_MODE" >&6; } if test $USE_MAINTAINER_MODE = yes; then MAINTAINER_MODE_TRUE= MAINTAINER_MODE_FALSE='#' else MAINTAINER_MODE_TRUE='#' MAINTAINER_MODE_FALSE= fi MAINT=$MAINTAINER_MODE_TRUE ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 $as_echo_n "checking whether the C compiler works... " >&6; } ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` # The possible output files: ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" ac_rmfiles= for ac_file in $ac_files do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link_default") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not # safe: cross compilers may not add the suffix if given an `-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. break;; * ) break;; esac done test "$ac_cv_exeext" = no && ac_cv_exeext= else ac_file='' fi if test -z "$ac_file"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "C compiler cannot create executables See \`config.log' for more details" "$LINENO" 5; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 $as_echo_n "checking for C compiler default output file name... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 $as_echo "$ac_file" >&6; } ac_exeext=$ac_cv_exeext rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 $as_echo_n "checking for suffix of executables... " >&6; } if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with # `rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest conftest$ac_cv_exeext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 $as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { FILE *f = fopen ("conftest.out", "w"); return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF ac_clean_files="$ac_clean_files conftest.out" # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 $as_echo_n "checking whether we are cross compiling... " >&6; } if test "$cross_compiling" != yes; then { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if { ac_try='./conftest$ac_cv_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details" "$LINENO" 5; } fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 $as_echo "$cross_compiling" >&6; } rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 $as_echo_n "checking for suffix of object files... " >&6; } if ${ac_cv_objext+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 $as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac if test "x$ac_cv_prog_cc_c89" != xno; then : fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu DEPDIR="${am__leading_dot}deps" ac_config_commands="$ac_config_commands depfiles" am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo this is the am__doit target .PHONY: am__doit END # If we don't find an include directive, just comment out the code. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for style of include used by $am_make" >&5 $as_echo_n "checking for style of include used by $am_make... " >&6; } am__include="#" am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf # Ignore all kinds of additional output from `make'. case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=include am__quote= _am_result=GNU ;; esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=.include am__quote="\"" _am_result=BSD ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $_am_result" >&5 $as_echo "$_am_result" >&6; } rm -f confinc confmf # Check whether --enable-dependency-tracking was given. if test "${enable_dependency_tracking+set}" = set; then : enableval=$enable_dependency_tracking; fi if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi if test "x$enable_dependency_tracking" != xno; then AMDEP_TRUE= AMDEP_FALSE='#' else AMDEP_TRUE='#' AMDEP_FALSE= fi depcc="$CC" am_compiler_list= { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 $as_echo_n "checking dependency style of $depcc... " >&6; } if ${am_cv_CC_dependencies_compiler_type+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named `D' -- because `-MD' means `put the output # in D'. rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_CC_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi am__universal=false case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with # Solaris 8's {/usr,}/bin/sh. touch sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with `-c' and `-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle `-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # after this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok `-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_CC_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_CC_dependencies_compiler_type=none fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5 $as_echo "$am_cv_CC_dependencies_compiler_type" >&6; } CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then am__fastdepCC_TRUE= am__fastdepCC_FALSE='#' else am__fastdepCC_TRUE='#' am__fastdepCC_FALSE= fi case `pwd` in *\ * | *\ *) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5 $as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;; esac macro_version='2.4.2' macro_revision='1.3337' ltmain="$ac_aux_dir/ltmain.sh" # Make sure we can run config.sub. $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 $as_echo_n "checking build system type... " >&6; } if ${ac_cv_build+:} false; then : $as_echo_n "(cached) " >&6 else ac_build_alias=$build_alias test "x$ac_build_alias" = x && ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` test "x$ac_build_alias" = x && as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 $as_echo "$ac_cv_build" >&6; } case $ac_cv_build in *-*-*) ;; *) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; esac build=$ac_cv_build ac_save_IFS=$IFS; IFS='-' set x $ac_cv_build shift build_cpu=$1 build_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: build_os=$* IFS=$ac_save_IFS case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 $as_echo_n "checking host system type... " >&6; } if ${ac_cv_host+:} false; then : $as_echo_n "(cached) " >&6 else if test "x$host_alias" = x; then ac_cv_host=$ac_cv_build else ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 $as_echo "$ac_cv_host" >&6; } case $ac_cv_host in *-*-*) ;; *) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; esac host=$ac_cv_host ac_save_IFS=$IFS; IFS='-' set x $ac_cv_host shift host_cpu=$1 host_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: host_os=$* IFS=$ac_save_IFS case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac # Backslashify metacharacters that are still active within # double-quoted strings. sed_quote_subst='s/\(["`$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution to delay expansion of an escaped shell variable in a # double_quote_subst'ed string. delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' # Sed substitution to delay expansion of an escaped single quote. delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' # Sed substitution to avoid accidental globbing in evaled expressions no_glob_subst='s/\*/\\\*/g' ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5 $as_echo_n "checking how to print strings... " >&6; } # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "" } case "$ECHO" in printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5 $as_echo "printf" >&6; } ;; print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5 $as_echo "print -r" >&6; } ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: cat" >&5 $as_echo "cat" >&6; } ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 $as_echo_n "checking for a sed that does not truncate output... " >&6; } if ${ac_cv_path_SED+:} false; then : $as_echo_n "(cached) " >&6 else ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for ac_i in 1 2 3 4 5 6 7; do ac_script="$ac_script$as_nl$ac_script" done echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed { ac_script=; unset ac_script;} if test -z "$SED"; then ac_path_SED_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in sed gsed; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_SED="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_SED" || continue # Check for GNU ac_path_SED and select it if it is found. # Check for GNU $ac_path_SED case `"$ac_path_SED" --version 2>&1` in *GNU*) ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo '' >> "conftest.nl" "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_SED_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_SED="$ac_path_SED" ac_path_SED_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_SED_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_SED"; then as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5 fi else ac_cv_path_SED=$SED fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 $as_echo "$ac_cv_path_SED" >&6; } SED="$ac_cv_path_SED" rm -f conftest.sed test -z "$SED" && SED=sed Xsed="$SED -e 1s/^X//" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 $as_echo_n "checking for grep that handles long lines and -e... " >&6; } if ${ac_cv_path_GREP+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$GREP"; then ac_path_GREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in grep ggrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_GREP" || continue # Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_GREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_GREP"; then as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_GREP=$GREP fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 $as_echo "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 $as_echo_n "checking for egrep... " >&6; } if ${ac_cv_path_EGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else if test -z "$EGREP"; then ac_path_EGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in egrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_EGREP" || continue # Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_EGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_EGREP"; then as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_EGREP=$EGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 $as_echo "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5 $as_echo_n "checking for fgrep... " >&6; } if ${ac_cv_path_FGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 then ac_cv_path_FGREP="$GREP -F" else if test -z "$FGREP"; then ac_path_FGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in fgrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_FGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_FGREP" || continue # Check for GNU ac_path_FGREP and select it if it is found. # Check for GNU $ac_path_FGREP case `"$ac_path_FGREP" --version 2>&1` in *GNU*) ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'FGREP' >> "conftest.nl" "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_FGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_FGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_FGREP"; then as_fn_error $? "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_FGREP=$FGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5 $as_echo "$ac_cv_path_FGREP" >&6; } FGREP="$ac_cv_path_FGREP" test -z "$GREP" && GREP=grep # Check whether --with-gnu-ld was given. if test "${with_gnu_ld+set}" = set; then : withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes else with_gnu_ld=no fi ac_prog=ld if test "$GCC" = yes; then # Check if gcc -print-prog-name=ld gives a path. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 $as_echo_n "checking for ld used by $CC... " >&6; } case $host in *-*-mingw*) # gcc leaves a trailing carriage return which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [\\/]* | ?:[\\/]*) re_direlt='/[^/][^/]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD="$ac_prog" ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test "$with_gnu_ld" = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 $as_echo_n "checking for GNU ld... " >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 $as_echo_n "checking for non-GNU ld... " >&6; } fi if ${lt_cv_path_LD+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$LD"; then lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD="$ac_dir/$ac_prog" # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &5 $as_echo "$LD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 $as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } if ${lt_cv_prog_gnu_ld+:} false; then : $as_echo_n "(cached) " >&6 else # I'd rather use --version here, but apparently some GNU lds only accept -v. case `$LD -v 2>&1 &5 $as_echo "$lt_cv_prog_gnu_ld" >&6; } with_gnu_ld=$lt_cv_prog_gnu_ld { $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5 $as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; } if ${lt_cv_path_NM+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM="$NM" else lt_nm_to_check="${ac_tool_prefix}nm" if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. tmp_nm="$ac_dir/$lt_tmp_nm" if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then # Check to see if the nm accepts a BSD-compat flag. # Adding the `sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in */dev/null* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS="$lt_save_ifs" done : ${lt_cv_path_NM=no} fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5 $as_echo "$lt_cv_path_NM" >&6; } if test "$lt_cv_path_NM" != "no"; then NM="$lt_cv_path_NM" else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else if test -n "$ac_tool_prefix"; then for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DUMPBIN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DUMPBIN"; then ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DUMPBIN=$ac_cv_prog_DUMPBIN if test -n "$DUMPBIN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5 $as_echo "$DUMPBIN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$DUMPBIN" && break done fi if test -z "$DUMPBIN"; then ac_ct_DUMPBIN=$DUMPBIN for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DUMPBIN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DUMPBIN"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN if test -n "$ac_ct_DUMPBIN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5 $as_echo "$ac_ct_DUMPBIN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_DUMPBIN" && break done if test "x$ac_ct_DUMPBIN" = x; then DUMPBIN=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DUMPBIN=$ac_ct_DUMPBIN fi fi case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols" ;; *) DUMPBIN=: ;; esac fi if test "$DUMPBIN" != ":"; then NM="$DUMPBIN" fi fi test -z "$NM" && NM=nm { $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5 $as_echo_n "checking the name lister ($NM) interface... " >&6; } if ${lt_cv_nm_interface+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: output\"" >&5) cat conftest.out >&5 if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5 $as_echo "$lt_cv_nm_interface" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 $as_echo_n "checking whether ln -s works... " >&6; } LN_S=$as_ln_s if test "$LN_S" = "ln -s"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 $as_echo "no, using $LN_S" >&6; } fi # find the maximum length of command line arguments { $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5 $as_echo_n "checking the maximum length of command line arguments... " >&6; } if ${lt_cv_sys_max_cmd_len+:} false; then : $as_echo_n "(cached) " >&6 else i=0 teststring="ABCD" case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[ ]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8 ; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test $i != 17 # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac fi if test -n $lt_cv_sys_max_cmd_len ; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5 $as_echo "$lt_cv_sys_max_cmd_len" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5 $as_echo "none" >&6; } fi max_cmd_len=$lt_cv_sys_max_cmd_len : ${CP="cp -f"} : ${MV="mv -f"} : ${RM="rm -f"} { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands some XSI constructs" >&5 $as_echo_n "checking whether the shell understands some XSI constructs... " >&6; } # Try some XSI features xsi_shell=no ( _lt_dummy="a/b/c" test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \ = c,a/b,b/c, \ && eval 'test $(( 1 + 1 )) -eq 2 \ && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ && xsi_shell=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $xsi_shell" >&5 $as_echo "$xsi_shell" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands \"+=\"" >&5 $as_echo_n "checking whether the shell understands \"+=\"... " >&6; } lt_shell_append=no ( foo=bar; set foo baz; eval "$1+=\$2" && test "$foo" = barbaz ) \ >/dev/null 2>&1 \ && lt_shell_append=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_shell_append" >&5 $as_echo "$lt_shell_append" >&6; } if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then lt_unset=unset else lt_unset=false fi # test EBCDIC or ASCII case `echo X|tr X '\101'` in A) # ASCII based system # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr lt_SP2NL='tr \040 \012' lt_NL2SP='tr \015\012 \040\040' ;; *) # EBCDIC based system lt_SP2NL='tr \100 \n' lt_NL2SP='tr \r\n \100\100' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to $host format" >&5 $as_echo_n "checking how to convert $build file names to $host format... " >&6; } if ${lt_cv_to_host_file_cmd+:} false; then : $as_echo_n "(cached) " >&6 else case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 ;; esac ;; *-*-cygwin* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_noop ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin ;; esac ;; * ) # unhandled hosts (and "normal" native builds) lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac fi to_host_file_cmd=$lt_cv_to_host_file_cmd { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" >&5 $as_echo "$lt_cv_to_host_file_cmd" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to toolchain format" >&5 $as_echo_n "checking how to convert $build file names to toolchain format... " >&6; } if ${lt_cv_to_tool_file_cmd+:} false; then : $as_echo_n "(cached) " >&6 else #assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac fi to_tool_file_cmd=$lt_cv_to_tool_file_cmd { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" >&5 $as_echo "$lt_cv_to_tool_file_cmd" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5 $as_echo_n "checking for $LD option to reload object files... " >&6; } if ${lt_cv_ld_reload_flag+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_reload_flag='-r' fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5 $as_echo "$lt_cv_ld_reload_flag" >&6; } reload_flag=$lt_cv_ld_reload_flag case $reload_flag in "" | " "*) ;; *) reload_flag=" $reload_flag" ;; esac reload_cmds='$LD$reload_flag -o $output$reload_objs' case $host_os in cygwin* | mingw* | pw32* | cegcc*) if test "$GCC" != yes; then reload_cmds=false fi ;; darwin*) if test "$GCC" = yes; then reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs' else reload_cmds='$LD$reload_flag -o $output$reload_objs' fi ;; esac if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args. set dummy ${ac_tool_prefix}objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OBJDUMP"; then ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OBJDUMP=$ac_cv_prog_OBJDUMP if test -n "$OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5 $as_echo "$OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OBJDUMP"; then ac_ct_OBJDUMP=$OBJDUMP # Extract the first word of "objdump", so it can be a program name with args. set dummy objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OBJDUMP"; then ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OBJDUMP="objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP if test -n "$ac_ct_OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5 $as_echo "$ac_ct_OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OBJDUMP" = x; then OBJDUMP="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OBJDUMP=$ac_ct_OBJDUMP fi else OBJDUMP="$ac_cv_prog_OBJDUMP" fi test -z "$OBJDUMP" && OBJDUMP=objdump { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5 $as_echo_n "checking how to recognize dependent libraries... " >&6; } if ${lt_cv_deplibs_check_method+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_file_magic_cmd='$MAGIC_CMD' lt_cv_file_magic_test_file= lt_cv_deplibs_check_method='unknown' # Need to set the preceding variable on all platforms that support # interlibrary dependencies. # 'none' -- dependencies not supported. # `unknown' -- same as none, but documents that we really don't know. # 'pass_all' -- all dependencies passed with no checks. # 'test_compile' -- check by making test program. # 'file_magic [[regex]]' -- check by looking for files in library path # which responds to the $file_magic_cmd with a given extended regex. # If you have `file' or equivalent on your system and you're not sure # whether `pass_all' will *always* work, you probably want this one. case $host_os in aix[4-9]*) lt_cv_deplibs_check_method=pass_all ;; beos*) lt_cv_deplibs_check_method=pass_all ;; bsdi[45]*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)' lt_cv_file_magic_cmd='/usr/bin/file -L' lt_cv_file_magic_test_file=/shlib/libc.so ;; cygwin*) # func_win32_libid is a shell function defined in ltmain.sh lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' ;; mingw* | pw32*) # Base MSYS/MinGW do not provide the 'file' command needed by # func_win32_libid shell function, so use a weaker test based on 'objdump', # unless we find 'file', for example because we are cross-compiling. # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin. if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; cegcc*) # use the weaker test based on 'objdump'. See mingw*. lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' lt_cv_file_magic_cmd='$OBJDUMP -f' ;; darwin* | rhapsody*) lt_cv_deplibs_check_method=pass_all ;; freebsd* | dragonfly*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then case $host_cpu in i*86 ) # Not sure whether the presence of OpenBSD here was a mistake. # Let's accept both of them until this is cleared up. lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` ;; esac else lt_cv_deplibs_check_method=pass_all fi ;; haiku*) lt_cv_deplibs_check_method=pass_all ;; hpux10.20* | hpux11*) lt_cv_file_magic_cmd=/usr/bin/file case $host_cpu in ia64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64' lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so ;; hppa*64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]' lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl ;; *) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9]\.[0-9]) shared library' lt_cv_file_magic_test_file=/usr/lib/libc.sl ;; esac ;; interix[3-9]*) # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$' ;; irix5* | irix6* | nonstopux*) case $LD in *-32|*"-32 ") libmagic=32-bit;; *-n32|*"-n32 ") libmagic=N32;; *-64|*"-64 ") libmagic=64-bit;; *) libmagic=never-match;; esac lt_cv_deplibs_check_method=pass_all ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) lt_cv_deplibs_check_method=pass_all ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$' fi ;; newos6*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=/usr/lib/libnls.so ;; *nto* | *qnx*) lt_cv_deplibs_check_method=pass_all ;; openbsd*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' fi ;; osf3* | osf4* | osf5*) lt_cv_deplibs_check_method=pass_all ;; rdos*) lt_cv_deplibs_check_method=pass_all ;; solaris*) lt_cv_deplibs_check_method=pass_all ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) lt_cv_deplibs_check_method=pass_all ;; sysv4 | sysv4.3*) case $host_vendor in motorola) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]' lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` ;; ncr) lt_cv_deplibs_check_method=pass_all ;; sequent) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' ;; sni) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib" lt_cv_file_magic_test_file=/lib/libc.so ;; siemens) lt_cv_deplibs_check_method=pass_all ;; pc) lt_cv_deplibs_check_method=pass_all ;; esac ;; tpf*) lt_cv_deplibs_check_method=pass_all ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5 $as_echo "$lt_cv_deplibs_check_method" >&6; } file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in mingw* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"` fi ;; esac fi file_magic_cmd=$lt_cv_file_magic_cmd deplibs_check_method=$lt_cv_deplibs_check_method test -z "$deplibs_check_method" && deplibs_check_method=unknown if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args. set dummy ${ac_tool_prefix}dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DLLTOOL"; then ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DLLTOOL=$ac_cv_prog_DLLTOOL if test -n "$DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5 $as_echo "$DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DLLTOOL"; then ac_ct_DLLTOOL=$DLLTOOL # Extract the first word of "dlltool", so it can be a program name with args. set dummy dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DLLTOOL"; then ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DLLTOOL="dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL if test -n "$ac_ct_DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5 $as_echo "$ac_ct_DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DLLTOOL" = x; then DLLTOOL="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DLLTOOL=$ac_ct_DLLTOOL fi else DLLTOOL="$ac_cv_prog_DLLTOOL" fi test -z "$DLLTOOL" && DLLTOOL=dlltool { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to associate runtime and link libraries" >&5 $as_echo_n "checking how to associate runtime and link libraries... " >&6; } if ${lt_cv_sharedlib_from_linklib_cmd+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in cygwin* | mingw* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh # decide which to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in *--identify-strict*) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib ;; *) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback ;; esac ;; *) # fallback: assume linklib IS sharedlib lt_cv_sharedlib_from_linklib_cmd="$ECHO" ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5 $as_echo "$lt_cv_sharedlib_from_linklib_cmd" >&6; } sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO if test -n "$ac_tool_prefix"; then for ac_prog in ar do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AR="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AR=$ac_cv_prog_AR if test -n "$AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 $as_echo "$AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AR" && break done fi if test -z "$AR"; then ac_ct_AR=$AR for ac_prog in ar do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_AR"; then ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_AR="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_AR=$ac_cv_prog_ac_ct_AR if test -n "$ac_ct_AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 $as_echo "$ac_ct_AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_AR" && break done if test "x$ac_ct_AR" = x; then AR="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac AR=$ac_ct_AR fi fi : ${AR=ar} : ${AR_FLAGS=cru} { $as_echo "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE support" >&5 $as_echo_n "checking for archiver @FILE support... " >&6; } if ${lt_cv_ar_at_file+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ar_at_file=no cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : echo conftest.$ac_objext > conftest.lst lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&5' { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -eq 0; then # Ensure the archiver fails upon bogus file names. rm -f conftest.$ac_objext libconftest.a { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -ne 0; then lt_cv_ar_at_file=@ fi fi rm -f conftest.* libconftest.a fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5 $as_echo "$lt_cv_ar_at_file" >&6; } if test "x$lt_cv_ar_at_file" = xno; then archiver_list_spec= else archiver_list_spec=$lt_cv_ar_at_file fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 $as_echo "$STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 $as_echo "$ac_ct_STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi test -z "$STRIP" && STRIP=: if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. set dummy ${ac_tool_prefix}ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$RANLIB"; then ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi RANLIB=$ac_cv_prog_RANLIB if test -n "$RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 $as_echo "$RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_RANLIB"; then ac_ct_RANLIB=$RANLIB # Extract the first word of "ranlib", so it can be a program name with args. set dummy ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_RANLIB"; then ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_RANLIB="ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB if test -n "$ac_ct_RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 $as_echo "$ac_ct_RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_RANLIB" = x; then RANLIB=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac RANLIB=$ac_ct_RANLIB fi else RANLIB="$ac_cv_prog_RANLIB" fi test -z "$RANLIB" && RANLIB=: # Determine commands to create old-style static archives. old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then case $host_os in openbsd*) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" ;; *) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" ;; esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in darwin*) lock_old_archive_extraction=yes ;; *) lock_old_archive_extraction=no ;; esac # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Check for command to grab the raw symbol name followed by C symbol from nm. { $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5 $as_echo_n "checking command to parse $NM output from $compiler object... " >&6; } if ${lt_cv_sys_global_symbol_pipe+:} false; then : $as_echo_n "(cached) " >&6 else # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] # Character class describing NM global symbol codes. symcode='[BCDEGRST]' # Regexp to match symbols that can be accessed directly from C. sympat='\([_A-Za-z][_A-Za-z0-9]*\)' # Define system-specific variables. case $host_os in aix*) symcode='[BCDT]' ;; cygwin* | mingw* | pw32* | cegcc*) symcode='[ABCDGISTW]' ;; hpux*) if test "$host_cpu" = ia64; then symcode='[ABCDEGRST]' fi ;; irix* | nonstopux*) symcode='[BCDEGRST]' ;; osf*) symcode='[BCDEGQRST]' ;; solaris*) symcode='[BDRT]' ;; sco3.2v5*) symcode='[DT]' ;; sysv4.2uw2*) symcode='[DT]' ;; sysv5* | sco5v6* | unixware* | OpenUNIX*) symcode='[ABDT]' ;; sysv4) symcode='[DFNSTU]' ;; esac # If we're using GNU nm, then use its standard symbol codes. case `$NM -V 2>&1` in *GNU* | *'with BFD'*) symcode='[ABCDGIRSTW]' ;; esac # Transform an extracted symbol line into a proper C declaration. # Some systems (esp. on ia64) link data and code symbols differently, # so use this general approach. lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" # Transform an extracted symbol line into symbol name and symbol address lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\)[ ]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (void *) \&\2},/p'" lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([^ ]*\)[ ]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \(lib[^ ]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"lib\2\", (void *) \&\2},/p'" # Handle CRLF in mingw tool chain opt_cr= case $build_os in mingw*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac # Try without a prefix underscore, then with it. for ac_symprfx in "" "_"; do # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. symxfrm="\\1 $ac_symprfx\\2 \\2" # Write the raw and C identifiers. if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Fake it for dumpbin and say T for any non-static function # and D for any global variable. # Also find C++ and __fastcall symbols from MSVC++, # which start with @ or ?. lt_cv_sys_global_symbol_pipe="$AWK '"\ " {last_section=section; section=\$ 3};"\ " /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ " /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ " \$ 0!~/External *\|/{next};"\ " / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ " {if(hide[section]) next};"\ " {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ " {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ " s[1]~/^[@?]/{print s[1], s[1]; next};"\ " s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ " ' prfx=^$ac_symprfx" else lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" fi lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'" # Check to see that the pipe works correctly. pipe_works=no rm -f conftest* cat > conftest.$ac_ext <<_LT_EOF #ifdef __cplusplus extern "C" { #endif char nm_test_var; void nm_test_func(void); void nm_test_func(void){} #ifdef __cplusplus } #endif int main(){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then # Now try to grab the symbols. nlist=conftest.nm if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist\""; } >&5 (eval $NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s "$nlist"; then # Try sorting and uniquifying the output. if sort "$nlist" | uniq > "$nlist"T; then mv -f "$nlist"T "$nlist" else rm -f "$nlist"T fi # Make sure that we snagged all the symbols we need. if $GREP ' nm_test_var$' "$nlist" >/dev/null; then if $GREP ' nm_test_func$' "$nlist" >/dev/null; then cat <<_LT_EOF > conftest.$ac_ext /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif #ifdef __cplusplus extern "C" { #endif _LT_EOF # Now generate the symbol file. eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' cat <<_LT_EOF >> conftest.$ac_ext /* The mapping between symbol names and symbols. */ LT_DLSYM_CONST struct { const char *name; void *address; } lt__PROGRAM__LTX_preloaded_symbols[] = { { "@PROGRAM@", (void *) 0 }, _LT_EOF $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext cat <<\_LT_EOF >> conftest.$ac_ext {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt__PROGRAM__LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif _LT_EOF # Now try linking the two files. mv conftest.$ac_objext conftstm.$ac_objext lt_globsym_save_LIBS=$LIBS lt_globsym_save_CFLAGS=$CFLAGS LIBS="conftstm.$ac_objext" CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag" if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext}; then pipe_works=yes fi LIBS=$lt_globsym_save_LIBS CFLAGS=$lt_globsym_save_CFLAGS else echo "cannot find nm_test_func in $nlist" >&5 fi else echo "cannot find nm_test_var in $nlist" >&5 fi else echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5 fi else echo "$progname: failed program was:" >&5 cat conftest.$ac_ext >&5 fi rm -rf conftest* conftst* # Do not use the global_symbol_pipe unless it works. if test "$pipe_works" = yes; then break else lt_cv_sys_global_symbol_pipe= fi done fi if test -z "$lt_cv_sys_global_symbol_pipe"; then lt_cv_sys_global_symbol_to_cdecl= fi if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: failed" >&5 $as_echo "failed" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } fi # Response file support. if test "$lt_cv_nm_interface" = "MS dumpbin"; then nm_file_list_spec='@' elif $NM --help 2>/dev/null | grep '[@]FILE' >/dev/null; then nm_file_list_spec='@' fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sysroot" >&5 $as_echo_n "checking for sysroot... " >&6; } # Check whether --with-sysroot was given. if test "${with_sysroot+set}" = set; then : withval=$with_sysroot; else with_sysroot=no fi lt_sysroot= case ${with_sysroot} in #( yes) if test "$GCC" = yes; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${with_sysroot}" >&5 $as_echo "${with_sysroot}" >&6; } as_fn_error $? "The sysroot must be an absolute path." "$LINENO" 5 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${lt_sysroot:-no}" >&5 $as_echo "${lt_sysroot:-no}" >&6; } # Check whether --enable-libtool-lock was given. if test "${enable_libtool_lock+set}" = set; then : enableval=$enable_libtool_lock; fi test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes # Some flags need to be propagated to the compiler or linker for good # libtool support. case $host in ia64-*-hpux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.$ac_objext` in *ELF-32*) HPUX_IA64_MODE="32" ;; *ELF-64*) HPUX_IA64_MODE="64" ;; esac fi rm -rf conftest* ;; *-*-irix6*) # Find out which ABI we are using. echo '#line '$LINENO' "configure"' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then if test "$lt_cv_prog_gnu_ld" = yes; then case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -melf32bsmip" ;; *N32*) LD="${LD-ld} -melf32bmipn32" ;; *64-bit*) LD="${LD-ld} -melf64bmip" ;; esac else case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -32" ;; *N32*) LD="${LD-ld} -n32" ;; *64-bit*) LD="${LD-ld} -64" ;; esac fi fi rm -rf conftest* ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.o` in *32-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_i386" ;; ppc64-*linux*|powerpc64-*linux*) LD="${LD-ld} -m elf32ppclinux" ;; s390x-*linux*) LD="${LD-ld} -m elf_s390" ;; sparc64-*linux*) LD="${LD-ld} -m elf32_sparc" ;; esac ;; *64-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_x86_64" ;; ppc*-*linux*|powerpc*-*linux*) LD="${LD-ld} -m elf64ppc" ;; s390*-*linux*|s390*-*tpf*) LD="${LD-ld} -m elf64_s390" ;; sparc*-*linux*) LD="${LD-ld} -m elf64_sparc" ;; esac ;; esac fi rm -rf conftest* ;; *-*-sco3.2v5*) # On SCO OpenServer 5, we need -belf to get full-featured binaries. SAVE_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS -belf" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5 $as_echo_n "checking whether the C compiler needs -belf... " >&6; } if ${lt_cv_cc_needs_belf+:} false; then : $as_echo_n "(cached) " >&6 else ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_cc_needs_belf=yes else lt_cv_cc_needs_belf=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5 $as_echo "$lt_cv_cc_needs_belf" >&6; } if test x"$lt_cv_cc_needs_belf" != x"yes"; then # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf CFLAGS="$SAVE_CFLAGS" fi ;; *-*solaris*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.o` in *64-bit*) case $lt_cv_prog_gnu_ld in yes*) case $host in i?86-*-solaris*) LD="${LD-ld} -m elf_x86_64" ;; sparc*-*-solaris*) LD="${LD-ld} -m elf64_sparc" ;; esac # GNU ld 2.21 introduced _sol2 emulations. Use them if available. if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then LD="${LD-ld}_sol2" fi ;; *) if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then LD="${LD-ld} -64" fi ;; esac ;; esac fi rm -rf conftest* ;; esac need_locks="$enable_libtool_lock" if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}mt", so it can be a program name with args. set dummy ${ac_tool_prefix}mt; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_MANIFEST_TOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$MANIFEST_TOOL"; then ac_cv_prog_MANIFEST_TOOL="$MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_MANIFEST_TOOL="${ac_tool_prefix}mt" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi MANIFEST_TOOL=$ac_cv_prog_MANIFEST_TOOL if test -n "$MANIFEST_TOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MANIFEST_TOOL" >&5 $as_echo "$MANIFEST_TOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_MANIFEST_TOOL"; then ac_ct_MANIFEST_TOOL=$MANIFEST_TOOL # Extract the first word of "mt", so it can be a program name with args. set dummy mt; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_MANIFEST_TOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_MANIFEST_TOOL"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="$ac_ct_MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="mt" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_MANIFEST_TOOL=$ac_cv_prog_ac_ct_MANIFEST_TOOL if test -n "$ac_ct_MANIFEST_TOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_MANIFEST_TOOL" >&5 $as_echo "$ac_ct_MANIFEST_TOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_MANIFEST_TOOL" = x; then MANIFEST_TOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac MANIFEST_TOOL=$ac_ct_MANIFEST_TOOL fi else MANIFEST_TOOL="$ac_cv_prog_MANIFEST_TOOL" fi test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $MANIFEST_TOOL is a manifest tool" >&5 $as_echo_n "checking if $MANIFEST_TOOL is a manifest tool... " >&6; } if ${lt_cv_path_mainfest_tool+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_path_mainfest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&5 $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&5 if $GREP 'Manifest Tool' conftest.out > /dev/null; then lt_cv_path_mainfest_tool=yes fi rm -f conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool" >&5 $as_echo "$lt_cv_path_mainfest_tool" >&6; } if test "x$lt_cv_path_mainfest_tool" != xyes; then MANIFEST_TOOL=: fi case $host_os in rhapsody* | darwin*) if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args. set dummy ${ac_tool_prefix}dsymutil; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DSYMUTIL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DSYMUTIL"; then ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DSYMUTIL="${ac_tool_prefix}dsymutil" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DSYMUTIL=$ac_cv_prog_DSYMUTIL if test -n "$DSYMUTIL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DSYMUTIL" >&5 $as_echo "$DSYMUTIL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DSYMUTIL"; then ac_ct_DSYMUTIL=$DSYMUTIL # Extract the first word of "dsymutil", so it can be a program name with args. set dummy dsymutil; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DSYMUTIL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DSYMUTIL"; then ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DSYMUTIL="dsymutil" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL if test -n "$ac_ct_DSYMUTIL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DSYMUTIL" >&5 $as_echo "$ac_ct_DSYMUTIL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DSYMUTIL" = x; then DSYMUTIL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DSYMUTIL=$ac_ct_DSYMUTIL fi else DSYMUTIL="$ac_cv_prog_DSYMUTIL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args. set dummy ${ac_tool_prefix}nmedit; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_NMEDIT+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$NMEDIT"; then ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_NMEDIT="${ac_tool_prefix}nmedit" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi NMEDIT=$ac_cv_prog_NMEDIT if test -n "$NMEDIT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NMEDIT" >&5 $as_echo "$NMEDIT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_NMEDIT"; then ac_ct_NMEDIT=$NMEDIT # Extract the first word of "nmedit", so it can be a program name with args. set dummy nmedit; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_NMEDIT+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_NMEDIT"; then ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_NMEDIT="nmedit" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT if test -n "$ac_ct_NMEDIT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_NMEDIT" >&5 $as_echo "$ac_ct_NMEDIT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_NMEDIT" = x; then NMEDIT=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac NMEDIT=$ac_ct_NMEDIT fi else NMEDIT="$ac_cv_prog_NMEDIT" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args. set dummy ${ac_tool_prefix}lipo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_LIPO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$LIPO"; then ac_cv_prog_LIPO="$LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_LIPO="${ac_tool_prefix}lipo" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi LIPO=$ac_cv_prog_LIPO if test -n "$LIPO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIPO" >&5 $as_echo "$LIPO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_LIPO"; then ac_ct_LIPO=$LIPO # Extract the first word of "lipo", so it can be a program name with args. set dummy lipo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_LIPO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_LIPO"; then ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_LIPO="lipo" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO if test -n "$ac_ct_LIPO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_LIPO" >&5 $as_echo "$ac_ct_LIPO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_LIPO" = x; then LIPO=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac LIPO=$ac_ct_LIPO fi else LIPO="$ac_cv_prog_LIPO" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args. set dummy ${ac_tool_prefix}otool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OTOOL"; then ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL="${ac_tool_prefix}otool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OTOOL=$ac_cv_prog_OTOOL if test -n "$OTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL" >&5 $as_echo "$OTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL"; then ac_ct_OTOOL=$OTOOL # Extract the first word of "otool", so it can be a program name with args. set dummy otool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OTOOL"; then ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL="otool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL if test -n "$ac_ct_OTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL" >&5 $as_echo "$ac_ct_OTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OTOOL" = x; then OTOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL=$ac_ct_OTOOL fi else OTOOL="$ac_cv_prog_OTOOL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args. set dummy ${ac_tool_prefix}otool64; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OTOOL64+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OTOOL64"; then ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL64="${ac_tool_prefix}otool64" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OTOOL64=$ac_cv_prog_OTOOL64 if test -n "$OTOOL64"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL64" >&5 $as_echo "$OTOOL64" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL64"; then ac_ct_OTOOL64=$OTOOL64 # Extract the first word of "otool64", so it can be a program name with args. set dummy otool64; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OTOOL64+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OTOOL64"; then ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL64="otool64" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64 if test -n "$ac_ct_OTOOL64"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL64" >&5 $as_echo "$ac_ct_OTOOL64" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OTOOL64" = x; then OTOOL64=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL64=$ac_ct_OTOOL64 fi else OTOOL64="$ac_cv_prog_OTOOL64" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -single_module linker flag" >&5 $as_echo_n "checking for -single_module linker flag... " >&6; } if ${lt_cv_apple_cc_single_mod+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_apple_cc_single_mod=no if test -z "${LT_MULTI_MODULE}"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE # non-empty at configure time, or by adding -multi_module to the # link flags. rm -rf libconftest.dylib* echo "int foo(void){return 1;}" > conftest.c echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c" >&5 $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c 2>conftest.err _lt_result=$? # If there is a non-empty error log, and "single_module" # appears in it, assume the flag caused a linker warning if test -s conftest.err && $GREP single_module conftest.err; then cat conftest.err >&5 # Otherwise, if the output was created with a 0 exit code from # the compiler, it worked. elif test -f libconftest.dylib && test $_lt_result -eq 0; then lt_cv_apple_cc_single_mod=yes else cat conftest.err >&5 fi rm -rf libconftest.dylib* rm -f conftest.* fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5 $as_echo "$lt_cv_apple_cc_single_mod" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5 $as_echo_n "checking for -exported_symbols_list linker flag... " >&6; } if ${lt_cv_ld_exported_symbols_list+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_ld_exported_symbols_list=yes else lt_cv_ld_exported_symbols_list=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5 $as_echo "$lt_cv_ld_exported_symbols_list" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -force_load linker flag" >&5 $as_echo_n "checking for -force_load linker flag... " >&6; } if ${lt_cv_ld_force_load+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&5 $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&5 echo "$AR cru libconftest.a conftest.o" >&5 $AR cru libconftest.a conftest.o 2>&5 echo "$RANLIB libconftest.a" >&5 $RANLIB libconftest.a 2>&5 cat > conftest.c << _LT_EOF int main() { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&5 $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err _lt_result=$? if test -s conftest.err && $GREP force_load conftest.err; then cat conftest.err >&5 elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then lt_cv_ld_force_load=yes else cat conftest.err >&5 fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_force_load" >&5 $as_echo "$lt_cv_ld_force_load" >&6; } case $host_os in rhapsody* | darwin1.[012]) _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; darwin1.*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; darwin*) # darwin 5.x on # if running on 10.5 or later, the deployment target defaults # to the OS version, if on x86, and 10.4, the deployment # target defaults to 10.4. Don't you love it? case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in 10.0,*86*-darwin8*|10.0,*-darwin[91]*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; 10.[012]*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; 10.*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; esac ;; esac if test "$lt_cv_apple_cc_single_mod" = "yes"; then _lt_dar_single_mod='$single_module' fi if test "$lt_cv_ld_exported_symbols_list" = "yes"; then _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' else _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' fi if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then _lt_dsymutil='~$DSYMUTIL $lib || :' else _lt_dsymutil= fi ;; esac ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 $as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if ${ac_cv_prog_CPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" do ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CPP=$CPP fi CPP=$ac_cv_prog_CPP else ac_cv_prog_CPP=$CPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 $as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if ${ac_cv_header_stdc+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : : else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : else ac_cv_header_stdc=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then $as_echo "#define STDC_HEADERS 1" >>confdefs.h fi # On IRIX 5.3, sys/types and inttypes.h are conflicting. for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ inttypes.h stdint.h unistd.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default " if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done for ac_header in dlfcn.h do : ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default " if test "x$ac_cv_header_dlfcn_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_DLFCN_H 1 _ACEOF fi done # Set options enable_dlopen=no enable_win32_dll=no # Check whether --enable-shared was given. if test "${enable_shared+set}" = set; then : enableval=$enable_shared; p=${PACKAGE-default} case $enableval in yes) enable_shared=yes ;; no) enable_shared=no ;; *) enable_shared=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_shared=yes fi done IFS="$lt_save_ifs" ;; esac else enable_shared=yes fi # Check whether --enable-static was given. if test "${enable_static+set}" = set; then : enableval=$enable_static; p=${PACKAGE-default} case $enableval in yes) enable_static=yes ;; no) enable_static=no ;; *) enable_static=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_static=yes fi done IFS="$lt_save_ifs" ;; esac else enable_static=yes fi # Check whether --with-pic was given. if test "${with_pic+set}" = set; then : withval=$with_pic; lt_p=${PACKAGE-default} case $withval in yes|no) pic_mode=$withval ;; *) pic_mode=default # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for lt_pkg in $withval; do IFS="$lt_save_ifs" if test "X$lt_pkg" = "X$lt_p"; then pic_mode=yes fi done IFS="$lt_save_ifs" ;; esac else pic_mode=default fi test -z "$pic_mode" && pic_mode=default # Check whether --enable-fast-install was given. if test "${enable_fast_install+set}" = set; then : enableval=$enable_fast_install; p=${PACKAGE-default} case $enableval in yes) enable_fast_install=yes ;; no) enable_fast_install=no ;; *) enable_fast_install=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_fast_install=yes fi done IFS="$lt_save_ifs" ;; esac else enable_fast_install=yes fi # This can be used to rebuild libtool when needed LIBTOOL_DEPS="$ltmain" # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' test -z "$LN_S" && LN_S="ln -s" if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5 $as_echo_n "checking for objdir... " >&6; } if ${lt_cv_objdir+:} false; then : $as_echo_n "(cached) " >&6 else rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi rmdir .libs 2>/dev/null fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5 $as_echo "$lt_cv_objdir" >&6; } objdir=$lt_cv_objdir cat >>confdefs.h <<_ACEOF #define LT_OBJDIR "$lt_cv_objdir/" _ACEOF case $host_os in aix3*) # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi ;; esac # Global variables: ofile=libtool can_build_shared=yes # All known linkers require a `.a' archive for static linking (except MSVC, # which needs '.lib'). libext=a with_gnu_ld="$lt_cv_prog_gnu_ld" old_CC="$CC" old_CFLAGS="$CFLAGS" # Set sane defaults for various variables test -z "$CC" && CC=cc test -z "$LTCC" && LTCC=$CC test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS test -z "$LD" && LD=ld test -z "$ac_objext" && ac_objext=o for cc_temp in $compiler""; do case $cc_temp in compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; \-*) ;; *) break;; esac done cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` # Only perform the check for file, if the check method requires it test -z "$MAGIC_CMD" && MAGIC_CMD=file case $deplibs_check_method in file_magic*) if test "$file_magic_cmd" = '$MAGIC_CMD'; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix}file" >&5 $as_echo_n "checking for ${ac_tool_prefix}file... " >&6; } if ${lt_cv_path_MAGIC_CMD+:} false; then : $as_echo_n "(cached) " >&6 else case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/${ac_tool_prefix}file; then lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac fi MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 $as_echo "$MAGIC_CMD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test -z "$lt_cv_path_MAGIC_CMD"; then if test -n "$ac_tool_prefix"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for file" >&5 $as_echo_n "checking for file... " >&6; } if ${lt_cv_path_MAGIC_CMD+:} false; then : $as_echo_n "(cached) " >&6 else case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/file; then lt_cv_path_MAGIC_CMD="$ac_dir/file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac fi MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 $as_echo "$MAGIC_CMD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi else MAGIC_CMD=: fi fi fi ;; esac # Use C for the default configuration in the libtool script lt_save_CC="$CC" ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # Source file extension for C test sources. ac_ext=c # Object file extension for compiled C test sources. objext=o objext=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(){return(0);}' # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Save the default compiler, since it gets overwritten when the other # tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. compiler_DEFAULT=$CC # save warnings/boilerplate of simple test code ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then lt_prog_compiler_no_builtin_flag= if test "$GCC" = yes; then case $cc_basename in nvcc*) lt_prog_compiler_no_builtin_flag=' -Xcompiler -fno-builtin' ;; *) lt_prog_compiler_no_builtin_flag=' -fno-builtin' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 $as_echo_n "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; } if ${lt_cv_prog_compiler_rtti_exceptions+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_rtti_exceptions=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-fno-rtti -fno-exceptions" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_rtti_exceptions=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 $as_echo "$lt_cv_prog_compiler_rtti_exceptions" >&6; } if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions" else : fi fi lt_prog_compiler_wl= lt_prog_compiler_pic= lt_prog_compiler_static= if test "$GCC" = yes; then lt_prog_compiler_wl='-Wl,' lt_prog_compiler_static='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support lt_prog_compiler_pic='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries lt_prog_compiler_pic='-DDLL_EXPORT' ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files lt_prog_compiler_pic='-fno-common' ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. lt_prog_compiler_static= ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) # +Z the default ;; *) lt_prog_compiler_pic='-fPIC' ;; esac ;; interix[3-9]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; msdosdjgpp*) # Just because we use GCC doesn't mean we suddenly get shared libraries # on systems that don't support them. lt_prog_compiler_can_build_shared=no enable_shared=no ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; sysv4*MP*) if test -d /usr/nec; then lt_prog_compiler_pic=-Kconform_pic fi ;; *) lt_prog_compiler_pic='-fPIC' ;; esac case $cc_basename in nvcc*) # Cuda Compiler Driver 2.2 lt_prog_compiler_wl='-Xlinker ' if test -n "$lt_prog_compiler_pic"; then lt_prog_compiler_pic="-Xcompiler $lt_prog_compiler_pic" fi ;; esac else # PORTME Check for flag to pass linker flags through the system compiler. case $host_os in aix*) lt_prog_compiler_wl='-Wl,' if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' else lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' fi ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). lt_prog_compiler_pic='-DDLL_EXPORT' ;; hpux9* | hpux10* | hpux11*) lt_prog_compiler_wl='-Wl,' # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but # not for PA HP-UX. case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) lt_prog_compiler_pic='+Z' ;; esac # Is there a better lt_prog_compiler_static that works with the bundled CC? lt_prog_compiler_static='${wl}-a ${wl}archive' ;; irix5* | irix6* | nonstopux*) lt_prog_compiler_wl='-Wl,' # PIC (with -KPIC) is the default. lt_prog_compiler_static='-non_shared' ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in # old Intel for x86_64 which still supported -KPIC. ecc*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-static' ;; # icc used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. icc* | ifort*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; # Lahey Fortran 8.1. lf95*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='--shared' lt_prog_compiler_static='--static' ;; nagfor*) # NAG Fortran compiler lt_prog_compiler_wl='-Wl,-Wl,,' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group compilers (*not* the Pentium gcc compiler, # which looks to be a dead project) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; ccc*) lt_prog_compiler_wl='-Wl,' # All Alpha code is PIC. lt_prog_compiler_static='-non_shared' ;; xl* | bgxl* | bgf* | mpixl*) # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-qpic' lt_prog_compiler_static='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [1-7].* | *Sun*Fortran*\ 8.[0-3]*) # Sun Fortran 8.3 passes all unrecognized flags to the linker lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='' ;; *Sun\ F* | *Sun*Fortran*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Qoption ld ' ;; *Sun\ C*) # Sun C 5.9 lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Wl,' ;; *Intel*\ [CF]*Compiler*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; *Portland\ Group*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; esac ;; esac ;; newsos6) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; osf3* | osf4* | osf5*) lt_prog_compiler_wl='-Wl,' # All OSF/1 code is PIC. lt_prog_compiler_static='-non_shared' ;; rdos*) lt_prog_compiler_static='-non_shared' ;; solaris*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' case $cc_basename in f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) lt_prog_compiler_wl='-Qoption ld ';; *) lt_prog_compiler_wl='-Wl,';; esac ;; sunos4*) lt_prog_compiler_wl='-Qoption ld ' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; sysv4 | sysv4.2uw2* | sysv4.3*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; sysv4*MP*) if test -d /usr/nec ;then lt_prog_compiler_pic='-Kconform_pic' lt_prog_compiler_static='-Bstatic' fi ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; unicos*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_can_build_shared=no ;; uts4*) lt_prog_compiler_pic='-pic' lt_prog_compiler_static='-Bstatic' ;; *) lt_prog_compiler_can_build_shared=no ;; esac fi case $host_os in # For platforms which do not support PIC, -DPIC is meaningless: *djgpp*) lt_prog_compiler_pic= ;; *) lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 $as_echo_n "checking for $compiler option to produce PIC... " >&6; } if ${lt_cv_prog_compiler_pic+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic=$lt_prog_compiler_pic fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic" >&5 $as_echo "$lt_cv_prog_compiler_pic" >&6; } lt_prog_compiler_pic=$lt_cv_prog_compiler_pic # # Check to make sure the PIC flag actually works. # if test -n "$lt_prog_compiler_pic"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 $as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; } if ${lt_cv_prog_compiler_pic_works+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic_works=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$lt_prog_compiler_pic -DPIC" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_pic_works=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5 $as_echo "$lt_cv_prog_compiler_pic_works" >&6; } if test x"$lt_cv_prog_compiler_pic_works" = xyes; then case $lt_prog_compiler_pic in "" | " "*) ;; *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; esac else lt_prog_compiler_pic= lt_prog_compiler_can_build_shared=no fi fi # # Check to make sure the static flag actually works. # wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 $as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } if ${lt_cv_prog_compiler_static_works+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_static_works=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS $lt_tmp_static_flag" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_static_works=yes fi else lt_cv_prog_compiler_static_works=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5 $as_echo "$lt_cv_prog_compiler_static_works" >&6; } if test x"$lt_cv_prog_compiler_static_works" = xyes; then : else lt_prog_compiler_static= fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 $as_echo "$lt_cv_prog_compiler_c_o" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 $as_echo "$lt_cv_prog_compiler_c_o" >&6; } hard_links="nottested" if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then # do not overwrite the value of need_locks provided by the user { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 $as_echo_n "checking if we can lock with hard links... " >&6; } hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 $as_echo "$hard_links" >&6; } if test "$hard_links" = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 $as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} need_locks=warn fi else need_locks=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 $as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } runpath_var= allow_undefined_flag= always_export_symbols=no archive_cmds= archive_expsym_cmds= compiler_needs_object=no enable_shared_with_static_runtimes=no export_dynamic_flag_spec= export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' hardcode_automatic=no hardcode_direct=no hardcode_direct_absolute=no hardcode_libdir_flag_spec= hardcode_libdir_separator= hardcode_minus_L=no hardcode_shlibpath_var=unsupported inherit_rpath=no link_all_deplibs=unknown module_cmds= module_expsym_cmds= old_archive_from_new_cmds= old_archive_from_expsyms_cmds= thread_safe_flag_spec= whole_archive_flag_spec= # include_expsyms should be a list of space-separated symbols to be *always* # included in the symbol list include_expsyms= # exclude_expsyms can be an extended regexp of symbols to exclude # it will be wrapped by ` (' and `)$', so one must not match beginning or # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', # as well as any symbol that contains `d'. exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out # platforms (ab)use it in PIC code, but their linkers get confused if # the symbol is explicitly referenced. Since portable code cannot # rely on this symbol name, it's probably fine to never include it in # preloaded symbol tables. # Exclude shared library initialization/finalization symbols. extract_expsyms_cmds= case $host_os in cygwin* | mingw* | pw32* | cegcc*) # FIXME: the MSVC++ port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++. if test "$GCC" != yes; then with_gnu_ld=no fi ;; interix*) # we just hope/assume this is gcc and not c89 (= MSVC++) with_gnu_ld=yes ;; openbsd*) with_gnu_ld=no ;; linux* | k*bsd*-gnu | gnu*) link_all_deplibs=no ;; esac ld_shlibs=yes # On some targets, GNU ld is compatible enough with the native linker # that we're better off using the native interface for both. lt_use_gnu_ld_interface=no if test "$with_gnu_ld" = yes; then case $host_os in aix*) # The AIX port of GNU ld has always aspired to compatibility # with the native linker. However, as the warning in the GNU ld # block says, versions before 2.19.5* couldn't really create working # shared libraries, regardless of the interface used. case `$LD -v 2>&1` in *\ \(GNU\ Binutils\)\ 2.19.5*) ;; *\ \(GNU\ Binutils\)\ 2.[2-9]*) ;; *\ \(GNU\ Binutils\)\ [3-9]*) ;; *) lt_use_gnu_ld_interface=yes ;; esac ;; *) lt_use_gnu_ld_interface=yes ;; esac fi if test "$lt_use_gnu_ld_interface" = yes; then # If archive_cmds runs LD, not CC, wlarc should be empty wlarc='${wl}' # Set some defaults for GNU ld with shared library support. These # are reset later if shared libraries are not supported. Putting them # here allows them to be overridden if necessary. runpath_var=LD_RUN_PATH hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' export_dynamic_flag_spec='${wl}--export-dynamic' # ancient GNU ld didn't support --whole-archive et. al. if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else whole_archive_flag_spec= fi supports_anon_versioning=no case `$LD -v 2>&1` in *GNU\ gold*) supports_anon_versioning=yes ;; *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... *\ 2.11.*) ;; # other 2.11 versions *) supports_anon_versioning=yes ;; esac # See if GNU ld supports shared libraries. case $host_os in aix[3-9]*) # On AIX/PPC, the GNU linker is very broken if test "$host_cpu" != ia64; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: the GNU linker, at least up to release 2.19, is reported *** to be unable to reliably create shared libraries on AIX. *** Therefore, libtool is disabling shared libraries support. If you *** really care for shared libraries, you may want to install binutils *** 2.20 or above, or modify your PATH so that a non-GNU linker is found. *** You will then need to restart the configuration process. _LT_EOF fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then allow_undefined_flag=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else ld_shlibs=no fi ;; cygwin* | mingw* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, # as there is no search path for DLLs. hardcode_libdir_flag_spec='-L$libdir' export_dynamic_flag_spec='${wl}--export-all-symbols' allow_undefined_flag=unsupported always_export_symbols=no enable_shared_with_static_runtimes=yes export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else ld_shlibs=no fi ;; haiku*) archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' link_all_deplibs=yes ;; interix[3-9]*) hardcode_direct=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='${wl}-rpath,$libdir' export_dynamic_flag_spec='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) tmp_diet=no if test "$host_os" = linux-dietlibc; then case $cc_basename in diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) esac fi if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ && test "$tmp_diet" = no then tmp_addflag=' $pic_flag' tmp_sharedflag='-shared' case $cc_basename,$host_cpu in pgcc*) # Portland Group C compiler whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag' ;; pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group f77 and f90 compilers whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag -Mnomain' ;; ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 tmp_addflag=' -i_dynamic' ;; efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 tmp_addflag=' -i_dynamic -nofor_main' ;; ifc* | ifort*) # Intel Fortran compiler tmp_addflag=' -nofor_main' ;; lf95*) # Lahey Fortran 8.1 whole_archive_flag_spec= tmp_sharedflag='--shared' ;; xl[cC]* | bgxl[cC]* | mpixl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below) tmp_sharedflag='-qmkshrobj' tmp_addflag= ;; nvcc*) # Cuda Compiler Driver 2.2 whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' compiler_needs_object=yes ;; esac case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C 5.9 whole_archive_flag_spec='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' compiler_needs_object=yes tmp_sharedflag='-G' ;; *Sun\ F*) # Sun Fortran 8.3 tmp_sharedflag='-G' ;; esac archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi case $cc_basename in xlf* | bgf* | bgxlf* | mpixlf*) # IBM XL Fortran 10.1 on PPC cannot create shared libs itself whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' if test "x$supports_anon_versioning" = xyes; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' fi ;; esac else ld_shlibs=no fi ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' wlarc= else archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' fi ;; solaris*) if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: The releases 2.8.* of the GNU linker cannot reliably *** create shared libraries on Solaris systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.9.1 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) case `$LD -v 2>&1` in *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not *** reliably create shared libraries on SCO systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.16.91.0.3 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF ;; *) # For security reasons, it is highly recommended that you always # use absolute paths for naming shared libraries, and exclude the # DT_RUNPATH tag from executables and libraries. But doing so # requires that you compile everything twice, which is a pain. if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac ;; sunos4*) archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' wlarc= hardcode_direct=yes hardcode_shlibpath_var=no ;; *) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac if test "$ld_shlibs" = no; then runpath_var= hardcode_libdir_flag_spec= export_dynamic_flag_spec= whole_archive_flag_spec= fi else # PORTME fill in a description of your system's linker (not GNU ld) case $host_os in aix3*) allow_undefined_flag=unsupported always_export_symbols=yes archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' # Note: this linker hardcodes the directories in LIBPATH if there # are no directories specified by -L. hardcode_minus_L=yes if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then # Neither direct hardcoding nor static linking is supported with a # broken collect2. hardcode_direct=unsupported fi ;; aix[4-9]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global # defined symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) for ld_flag in $LDFLAGS; do if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then aix_use_runtimelinking=yes break fi done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. archive_cmds='' hardcode_direct=yes hardcode_direct_absolute=yes hardcode_libdir_separator=':' link_all_deplibs=yes file_list_spec='${wl}-f,' if test "$GCC" = yes; then case $host_os in aix4.[012]|aix4.[012].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 hardcode_direct=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking hardcode_minus_L=yes hardcode_libdir_flag_spec='-L$libdir' hardcode_libdir_separator= fi ;; esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi link_all_deplibs=no else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi export_dynamic_flag_spec='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to export. always_export_symbols=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. allow_undefined_flag='-berok' # Determine the default libpath from the value encoded in an # empty executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath_+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib' allow_undefined_flag="-z nodefs" archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath_+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. no_undefined_flag=' ${wl}-bernotok' allow_undefined_flag=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. whole_archive_flag_spec='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives whole_archive_flag_spec='$convenience' fi archive_cmds_need_lc=yes # This is similar to how AIX traditionally builds its shared libraries. archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; bsdi[45]*) export_dynamic_flag_spec=-rdynamic ;; cygwin* | mingw* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++. # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. case $cc_basename in cl*) # Native MSVC hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported always_export_symbols=yes file_list_spec='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, )='true' enable_shared_with_static_runtimes=yes exclude_expsyms='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1,DATA/'\'' | $SED -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' # Don't use ranlib old_postinstall_cmds='chmod 644 $oldlib' postlink_cmds='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # Assume MSVC wrapper hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' # The linker will automatically build a .lib file if we build a DLL. old_archive_from_new_cmds='true' # FIXME: Should let the user specify the lib program. old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs' enable_shared_with_static_runtimes=yes ;; esac ;; darwin* | rhapsody*) archive_cmds_need_lc=no hardcode_direct=no hardcode_automatic=yes hardcode_shlibpath_var=unsupported if test "$lt_cv_ld_force_load" = "yes"; then whole_archive_flag_spec='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' else whole_archive_flag_spec='' fi link_all_deplibs=yes allow_undefined_flag="$_lt_dar_allow_undefined" case $cc_basename in ifort*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test "$_lt_dar_can_shared" = "yes"; then output_verbose_link_cmd=func_echo_all archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" module_expsym_cmds="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" else ld_shlibs=no fi ;; dgux*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor # support. Future versions do this automatically, but an explicit c++rt0.o # does not break anything, and helps significantly (at the cost of a little # extra space). freebsd2.2*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; # Unfortunately, older versions of FreeBSD 2 do not have this feature. freebsd2.*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. freebsd* | dragonfly*) archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; hpux9*) if test "$GCC" = yes; then archive_cmds='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' fi hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: hardcode_direct=yes # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes export_dynamic_flag_spec='${wl}-E' ;; hpux10*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi if test "$with_gnu_ld" = no; then hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes fi ;; hpux11*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then case $host_cpu in hppa*64*) archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' ;; esac else case $host_cpu in hppa*64*) archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) # Older versions of the 11.00 compiler do not understand -b yet # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $CC understands -b" >&5 $as_echo_n "checking if $CC understands -b... " >&6; } if ${lt_cv_prog_compiler__b+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler__b=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -b" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler__b=yes fi else lt_cv_prog_compiler__b=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" >&5 $as_echo "$lt_cv_prog_compiler__b" >&6; } if test x"$lt_cv_prog_compiler__b" = xyes; then archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi ;; esac fi if test "$with_gnu_ld" = no; then hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: case $host_cpu in hppa*64*|ia64*) hardcode_direct=no hardcode_shlibpath_var=no ;; *) hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes ;; esac fi ;; irix5* | irix6* | nonstopux*) if test "$GCC" = yes; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' # Try to use the -exported_symbol ld option, if it does not # work, assume that -exports_file does not work either and # implicitly export all symbols. # This should be the same for all languages, so no per-tag cache variable. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $host_os linker accepts -exported_symbol" >&5 $as_echo_n "checking whether the $host_os linker accepts -exported_symbol... " >&6; } if ${lt_cv_irix_exported_symbol+:} false; then : $as_echo_n "(cached) " >&6 else save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int foo (void) { return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_irix_exported_symbol=yes else lt_cv_irix_exported_symbol=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symbol" >&5 $as_echo "$lt_cv_irix_exported_symbol" >&6; } if test "$lt_cv_irix_exported_symbol" = yes; then archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' fi else archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: inherit_rpath=yes link_all_deplibs=yes ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out else archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF fi hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; newsos6) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: hardcode_shlibpath_var=no ;; *nto* | *qnx*) ;; openbsd*) if test -f /usr/libexec/ld.so; then hardcode_direct=yes hardcode_shlibpath_var=no hardcode_direct_absolute=yes if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' hardcode_libdir_flag_spec='${wl}-rpath,$libdir' export_dynamic_flag_spec='${wl}-E' else case $host_os in openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-R$libdir' ;; *) archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='${wl}-rpath,$libdir' ;; esac fi else ld_shlibs=no fi ;; os2*) hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes allow_undefined_flag=unsupported archive_cmds='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' old_archive_from_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' ;; osf3*) if test "$GCC" = yes; then allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: ;; osf4* | osf5*) # as osf3* with the addition of -msym flag if test "$GCC" = yes; then allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' archive_cmds='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' # Both c and cxx compiler support -rpath directly hardcode_libdir_flag_spec='-rpath $libdir' fi archive_cmds_need_lc='no' hardcode_libdir_separator=: ;; solaris*) no_undefined_flag=' -z defs' if test "$GCC" = yes; then wlarc='${wl}' archive_cmds='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' else case `$CC -V 2>&1` in *"Compilers 5.0"*) wlarc='' archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' ;; *) wlarc='${wl}' archive_cmds='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' ;; esac fi hardcode_libdir_flag_spec='-R$libdir' hardcode_shlibpath_var=no case $host_os in solaris2.[0-5] | solaris2.[0-5].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. GCC discards it without `$wl', # but is careful enough not to reorder. # Supported since Solaris 2.6 (maybe 2.5.1?) if test "$GCC" = yes; then whole_archive_flag_spec='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' else whole_archive_flag_spec='-z allextract$convenience -z defaultextract' fi ;; esac link_all_deplibs=yes ;; sunos4*) if test "x$host_vendor" = xsequent; then # Use $CC to link under sequent, because it throws in some extra .o # files that make .init and .fini sections work. archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' fi hardcode_libdir_flag_spec='-L$libdir' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; sysv4) case $host_vendor in sni) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes # is this really true??? ;; siemens) ## LD is ld it makes a PLAMLIB ## CC just makes a GrossModule. archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' reload_cmds='$CC -r -o $output$reload_objs' hardcode_direct=no ;; motorola) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=no #Motorola manual says yes, but my tests say they lie ;; esac runpath_var='LD_RUN_PATH' hardcode_shlibpath_var=no ;; sysv4.3*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no export_dynamic_flag_spec='-Bexport' ;; sysv4*MP*) if test -d /usr/nec; then archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no runpath_var=LD_RUN_PATH hardcode_runpath_var=yes ld_shlibs=yes fi ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) no_undefined_flag='${wl}-z,text' archive_cmds_need_lc=no hardcode_shlibpath_var=no runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. no_undefined_flag='${wl}-z,text' allow_undefined_flag='${wl}-z,nodefs' archive_cmds_need_lc=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='${wl}-R,$libdir' hardcode_libdir_separator=':' link_all_deplibs=yes export_dynamic_flag_spec='${wl}-Bexport' runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; uts4*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; *) ld_shlibs=no ;; esac if test x$host_vendor = xsni; then case $host in sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) export_dynamic_flag_spec='${wl}-Blargedynsym' ;; esac fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5 $as_echo "$ld_shlibs" >&6; } test "$ld_shlibs" = no && can_build_shared=no with_gnu_ld=$with_gnu_ld # # Do we need to explicitly link libc? # case "x$archive_cmds_need_lc" in x|xyes) # Assume -lc should be added archive_cmds_need_lc=yes if test "$enable_shared" = yes && test "$GCC" = yes; then case $archive_cmds in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 $as_echo_n "checking whether -lc should be explicitly linked in... " >&6; } if ${lt_cv_archive_cmds_need_lc+:} false; then : $as_echo_n "(cached) " >&6 else $RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$lt_prog_compiler_wl pic_flag=$lt_prog_compiler_pic compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$allow_undefined_flag allow_undefined_flag= if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then lt_cv_archive_cmds_need_lc=no else lt_cv_archive_cmds_need_lc=yes fi allow_undefined_flag=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc" >&5 $as_echo "$lt_cv_archive_cmds_need_lc" >&6; } archive_cmds_need_lc=$lt_cv_archive_cmds_need_lc ;; esac fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 $as_echo_n "checking dynamic linker characteristics... " >&6; } if test "$GCC" = yes; then case $host_os in darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; *) lt_awk_arg="/^libraries:/" ;; esac case $host_os in mingw* | cegcc*) lt_sed_strip_eq="s,=\([A-Za-z]:\),\1,g" ;; *) lt_sed_strip_eq="s,=/,/,g" ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` case $lt_search_path_spec in *\;*) # if the path contains ";" then we assume it to be the separator # otherwise default to the standard path separator (i.e. ":") - it is # assumed that no part of a normal pathname contains ";" but that should # okay in the real world where ";" in dirpaths is itself problematic. lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` ;; *) lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` ;; esac # Ok, now we have the path, separated by spaces, we can step through it # and add multilib dir if necessary. lt_tmp_lt_search_path_spec= lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` for lt_sys_path in $lt_search_path_spec; do if test -d "$lt_sys_path/$lt_multi_os_dir"; then lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" else test -d "$lt_sys_path" && \ lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" fi done lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' BEGIN {RS=" "; FS="/|\n";} { lt_foo=""; lt_count=0; for (lt_i = NF; lt_i > 0; lt_i--) { if ($lt_i != "" && $lt_i != ".") { if ($lt_i == "..") { lt_count++; } else { if (lt_count == 0) { lt_foo="/" $lt_i lt_foo; } else { lt_count--; } } } } if (lt_foo != "") { lt_freq[lt_foo]++; } if (lt_freq[lt_foo] == 1) { print lt_foo; } }'` # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's,/\([A-Za-z]:\),\1,g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` else sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" fi library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=".so" postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='${libname}${release}${shared_ext}$major' ;; aix[4-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test "$host_cpu" = ia64; then # AIX 5 supports IA64 library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line `#! .'. This would cause the generated library to # depend on `.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[01] | aix4.[01].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # AIX (on Power*) has no versioning support, so currently we can not hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. if test "$aix_use_runtimelinking" = yes; then # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' else # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='${libname}${release}.a $libname.a' soname_spec='${libname}${release}${shared_ext}$major' fi shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='${libname}${shared_ext}' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[45]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=".dll" need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api" ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' library_names_spec='${libname}.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec="$LIB" if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' soname_spec='${libname}${release}${major}$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib" sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[23].*) objformat=aout ;; *) objformat=elf ;; esac fi version_type=freebsd-$objformat case $version_type in freebsd-elf*) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' need_version=yes ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[01]* | freebsdelf3.[01]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=yes sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' if test "X$HPUX_IA64_MODE" = X32; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" fi sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[3-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test "$lt_cv_prog_gnu_ld" = yes; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH if ${lt_cv_shlibpath_overrides_runpath+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \ LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\"" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then : lt_cv_shlibpath_overrides_runpath=yes fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS libdir=$save_libdir fi shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsdelf*-gnu) version_type=linux need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='NetBSD ld.elf_so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd*) version_type=sunos sys_lib_dlsearch_path_spec="/usr/lib" need_lib_prefix=no # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. case $host_os in openbsd3.3 | openbsd3.3.*) need_version=yes ;; *) need_version=no ;; esac library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then case $host_os in openbsd2.[89] | openbsd2.[89].*) shlibpath_overrides_runpath=no ;; *) shlibpath_overrides_runpath=yes ;; esac else shlibpath_overrides_runpath=yes fi ;; os2*) libname_spec='$name' shrext_cmds=".dll" need_lib_prefix=no library_names_spec='$libname${shared_ext} $libname.a' dynamic_linker='OS/2 ld.exe' shlibpath_var=LIBPATH ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test "$with_gnu_ld" = yes; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec ;then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' soname_spec='$libname${shared_ext}.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=freebsd-elf need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test "$with_gnu_ld" = yes; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 $as_echo "$dynamic_linker" >&6; } test "$dynamic_linker" = no && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test "$GCC" = yes; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" fi if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 $as_echo_n "checking how to hardcode library paths into programs... " >&6; } hardcode_action= if test -n "$hardcode_libdir_flag_spec" || test -n "$runpath_var" || test "X$hardcode_automatic" = "Xyes" ; then # We can hardcode non-existent directories. if test "$hardcode_direct" != no && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" != no && test "$hardcode_minus_L" != no; then # Linking always hardcodes the temporary library directory. hardcode_action=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. hardcode_action=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. hardcode_action=unsupported fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5 $as_echo "$hardcode_action" >&6; } if test "$hardcode_action" = relink || test "$inherit_rpath" = yes; then # Fast installation is not supported enable_fast_install=no elif test "$shlibpath_overrides_runpath" = yes || test "$enable_shared" = no; then # Fast installation is not necessary enable_fast_install=needless fi if test "x$enable_dlopen" != xyes; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen="load_add_on" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen="LoadLibrary" lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen="dlopen" lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dl_dlopen=yes else ac_cv_lib_dl_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" else lt_cv_dlopen="dyld" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes fi ;; *) ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load" if test "x$ac_cv_func_shl_load" = xyes; then : lt_cv_dlopen="shl_load" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 $as_echo_n "checking for shl_load in -ldld... " >&6; } if ${ac_cv_lib_dld_shl_load+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char shl_load (); int main () { return shl_load (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dld_shl_load=yes else ac_cv_lib_dld_shl_load=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 $as_echo "$ac_cv_lib_dld_shl_load" >&6; } if test "x$ac_cv_lib_dld_shl_load" = xyes; then : lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld" else ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" if test "x$ac_cv_func_dlopen" = xyes; then : lt_cv_dlopen="dlopen" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dl_dlopen=yes else ac_cv_lib_dl_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5 $as_echo_n "checking for dlopen in -lsvld... " >&6; } if ${ac_cv_lib_svld_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lsvld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_svld_dlopen=yes else ac_cv_lib_svld_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5 $as_echo "$ac_cv_lib_svld_dlopen" >&6; } if test "x$ac_cv_lib_svld_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5 $as_echo_n "checking for dld_link in -ldld... " >&6; } if ${ac_cv_lib_dld_dld_link+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dld_link (); int main () { return dld_link (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dld_dld_link=yes else ac_cv_lib_dld_dld_link=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5 $as_echo "$ac_cv_lib_dld_dld_link" >&6; } if test "x$ac_cv_lib_dld_dld_link" = xyes; then : lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld" fi fi fi fi fi fi ;; esac if test "x$lt_cv_dlopen" != xno; then enable_dlopen=yes else enable_dlopen=no fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS="$CPPFLAGS" test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS="$LDFLAGS" wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS="$LIBS" LIBS="$lt_cv_dlopen_libs $LIBS" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5 $as_echo_n "checking whether a program can dlopen itself... " >&6; } if ${lt_cv_dlopen_self+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : lt_cv_dlopen_self=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;; esac else : # compilation failed lt_cv_dlopen_self=no fi fi rm -fr conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5 $as_echo "$lt_cv_dlopen_self" >&6; } if test "x$lt_cv_dlopen_self" = xyes; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5 $as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; } if ${lt_cv_dlopen_self_static+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : lt_cv_dlopen_self_static=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;; esac else : # compilation failed lt_cv_dlopen_self_static=no fi fi rm -fr conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5 $as_echo "$lt_cv_dlopen_self_static" >&6; } fi CPPFLAGS="$save_CPPFLAGS" LDFLAGS="$save_LDFLAGS" LIBS="$save_LIBS" ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi striplib= old_striplib= { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5 $as_echo_n "checking whether stripping libraries is possible... " >&6; } if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" test -z "$striplib" && striplib="$STRIP --strip-unneeded" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else # FIXME - insert some real tests, host_os isn't really good enough case $host_os in darwin*) if test -n "$STRIP" ; then striplib="$STRIP -x" old_striplib="$STRIP -S" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } ;; esac fi # Report which library types will actually be built { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5 $as_echo_n "checking if libtool supports shared libraries... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5 $as_echo "$can_build_shared" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5 $as_echo_n "checking whether to build shared libraries... " >&6; } test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[4-9]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5 $as_echo "$enable_shared" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5 $as_echo_n "checking whether to build static libraries... " >&6; } # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5 $as_echo "$enable_static" >&6; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CC="$lt_save_CC" ac_config_commands="$ac_config_commands libtool" # Only expand once: ac_fn_c_check_func "$LINENO" "gethostbyaddr_r" "ac_cv_func_gethostbyaddr_r" if test "x$ac_cv_func_gethostbyaddr_r" = xyes; then : $as_echo "#define HAS_GETHOSTBYADDR_R 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "gethostbyname_r" "ac_cv_func_gethostbyname_r" if test "x$ac_cv_func_gethostbyname_r" = xyes; then : $as_echo "#define HAS_GETHOSTBYNAME_R 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "poll" "ac_cv_func_poll" if test "x$ac_cv_func_poll" = xyes; then : $as_echo "#define HAS_POLL 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "fcntl" "ac_cv_func_fcntl" if test "x$ac_cv_func_fcntl" = xyes; then : $as_echo "#define HAS_FCNTL 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "inet_pton" "ac_cv_func_inet_pton" if test "x$ac_cv_func_inet_pton" = xyes; then : $as_echo "#define HAS_INET_PTON 1" >>confdefs.h fi ac_fn_c_check_func "$LINENO" "inet_ntop" "ac_cv_func_inet_ntop" if test "x$ac_cv_func_inet_ntop" = xyes; then : $as_echo "#define HAS_INET_NTOP 1" >>confdefs.h fi ac_fn_c_check_member "$LINENO" "struct msghdr" "msg_flags" "ac_cv_member_struct_msghdr_msg_flags" "#include " if test "x$ac_cv_member_struct_msghdr_msg_flags" = xyes; then : $as_echo "#define HAS_MSGHDR_FLAGS 1" >>confdefs.h fi ac_fn_c_check_type "$LINENO" "socklen_t" "ac_cv_type_socklen_t" "#include #include " if test "x$ac_cv_type_socklen_t" = xyes; then : $as_echo "#define HAS_SOCKLEN_T 1" >>confdefs.h fi cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "MSG_MAXIOVLEN" >/dev/null 2>&1; then : $as_echo "#define ENET_BUFFER_MAXIMUM MSG_MAXIOVLEN" >>confdefs.h fi rm -f conftest* cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "MSG_MAXIOVLEN" >/dev/null 2>&1; then : $as_echo "#define ENET_BUFFER_MAXIMUM MSG_MAXIOVLEN" >>confdefs.h fi rm -f conftest* ac_config_files="$ac_config_files Makefile libenet.pc" cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # `ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* `ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. ( for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) # `set' does not quote correctly, so add quotes: double-quote # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) # `set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) | sed ' /^ac_cv_env_/b end t clear :clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then if test "x$cache_file" != "x/dev/null"; then { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} if test ! -f "$cache_file" || test -h "$cache_file"; then cat confcache >"$cache_file" else case $cache_file in #( */* | ?:*) mv -f confcache "$cache_file"$$ && mv -f "$cache_file"$$ "$cache_file" ;; #( *) mv -f confcache "$cache_file" ;; esac fi fi else { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' # Transform confdefs.h into DEFS. # Protect against shell expansion while executing Makefile rules. # Protect against Makefile macro expansion. # # If the first sed substitution is executed (which looks for macros that # take arguments), then branch to the quote section. Otherwise, # look for a macro that doesn't take arguments. ac_script=' :mline /\\$/{ N s,\\\n,, b mline } t clear :clear s/^[ ]*#[ ]*define[ ][ ]*\([^ (][^ (]*([^)]*)\)[ ]*\(.*\)/-D\1=\2/g t quote s/^[ ]*#[ ]*define[ ][ ]*\([^ ][^ ]*\)[ ]*\(.*\)/-D\1=\2/g t quote b any :quote s/[ `~#$^&*(){}\\|;'\''"<>?]/\\&/g s/\[/\\&/g s/\]/\\&/g s/\$/$$/g H :any ${ g s/^\n// s/\n/ /g p } ' DEFS=`sed -n "$ac_script" confdefs.h` ac_libobjs= ac_ltlibobjs= U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs if test -n "$EXEEXT"; then am__EXEEXT_TRUE= am__EXEEXT_FALSE='#' else am__EXEEXT_TRUE='#' am__EXEEXT_FALSE= fi if test -z "${MAINTAINER_MODE_TRUE}" && test -z "${MAINTAINER_MODE_FALSE}"; then as_fn_error $? "conditional \"MAINTAINER_MODE\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then as_fn_error $? "conditional \"AMDEP\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then as_fn_error $? "conditional \"am__fastdepCC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi : "${CONFIG_STATUS=./config.status}" ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 $as_echo "$as_me: creating $CONFIG_STATUS" >&6;} as_write_fail=0 cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 6>&1 ## ----------------------------------- ## ## Main body of $CONFIG_STATUS script. ## ## ----------------------------------- ## _ASEOF test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by libenet $as_me 1.3.6, which was generated by GNU Autoconf 2.69. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ on `(hostname || uname -n) 2>/dev/null | sed 1q` " _ACEOF case $ac_config_files in *" "*) set x $ac_config_files; shift; ac_config_files=$*;; esac cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_commands="$ac_config_commands" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files and other configuration actions from templates according to the current configuration. Unless the files and actions are specified as TAGs, all are instantiated by default. Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit --config print configuration, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE Configuration files: $config_files Configuration commands: $config_commands Report bugs to the package provider." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ libenet config.status 1.3.6 configured by $0, generated by GNU Autoconf 2.69, with options \\"\$ac_cs_config\\" Copyright (C) 2012 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' MKDIR_P='$MKDIR_P' AWK='$AWK' test -n "\$AWK" || AWK=awk _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do case $1 in --*=?*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; --*=) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg= ac_shift=: ;; *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; esac case $ac_option in # Handling of the options. -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) $as_echo "$ac_cs_version"; exit ;; --config | --confi | --conf | --con | --co | --c ) $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; '') as_fn_error $? "missing file argument" ;; esac as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --he | --h | --help | --hel | -h ) $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) as_fn_error $? "unrecognized option: \`$1' Try \`$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion shift \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 CONFIG_SHELL='$SHELL' export CONFIG_SHELL exec "\$@" fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX $as_echo "$ac_log" } >&5 _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # # INIT-COMMANDS # AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir" # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH sed_quote_subst='$sed_quote_subst' double_quote_subst='$double_quote_subst' delay_variable_subst='$delay_variable_subst' macro_version='`$ECHO "$macro_version" | $SED "$delay_single_quote_subst"`' macro_revision='`$ECHO "$macro_revision" | $SED "$delay_single_quote_subst"`' enable_shared='`$ECHO "$enable_shared" | $SED "$delay_single_quote_subst"`' enable_static='`$ECHO "$enable_static" | $SED "$delay_single_quote_subst"`' pic_mode='`$ECHO "$pic_mode" | $SED "$delay_single_quote_subst"`' enable_fast_install='`$ECHO "$enable_fast_install" | $SED "$delay_single_quote_subst"`' SHELL='`$ECHO "$SHELL" | $SED "$delay_single_quote_subst"`' ECHO='`$ECHO "$ECHO" | $SED "$delay_single_quote_subst"`' PATH_SEPARATOR='`$ECHO "$PATH_SEPARATOR" | $SED "$delay_single_quote_subst"`' host_alias='`$ECHO "$host_alias" | $SED "$delay_single_quote_subst"`' host='`$ECHO "$host" | $SED "$delay_single_quote_subst"`' host_os='`$ECHO "$host_os" | $SED "$delay_single_quote_subst"`' build_alias='`$ECHO "$build_alias" | $SED "$delay_single_quote_subst"`' build='`$ECHO "$build" | $SED "$delay_single_quote_subst"`' build_os='`$ECHO "$build_os" | $SED "$delay_single_quote_subst"`' SED='`$ECHO "$SED" | $SED "$delay_single_quote_subst"`' Xsed='`$ECHO "$Xsed" | $SED "$delay_single_quote_subst"`' GREP='`$ECHO "$GREP" | $SED "$delay_single_quote_subst"`' EGREP='`$ECHO "$EGREP" | $SED "$delay_single_quote_subst"`' FGREP='`$ECHO "$FGREP" | $SED "$delay_single_quote_subst"`' LD='`$ECHO "$LD" | $SED "$delay_single_quote_subst"`' NM='`$ECHO "$NM" | $SED "$delay_single_quote_subst"`' LN_S='`$ECHO "$LN_S" | $SED "$delay_single_quote_subst"`' max_cmd_len='`$ECHO "$max_cmd_len" | $SED "$delay_single_quote_subst"`' ac_objext='`$ECHO "$ac_objext" | $SED "$delay_single_quote_subst"`' exeext='`$ECHO "$exeext" | $SED "$delay_single_quote_subst"`' lt_unset='`$ECHO "$lt_unset" | $SED "$delay_single_quote_subst"`' lt_SP2NL='`$ECHO "$lt_SP2NL" | $SED "$delay_single_quote_subst"`' lt_NL2SP='`$ECHO "$lt_NL2SP" | $SED "$delay_single_quote_subst"`' lt_cv_to_host_file_cmd='`$ECHO "$lt_cv_to_host_file_cmd" | $SED "$delay_single_quote_subst"`' lt_cv_to_tool_file_cmd='`$ECHO "$lt_cv_to_tool_file_cmd" | $SED "$delay_single_quote_subst"`' reload_flag='`$ECHO "$reload_flag" | $SED "$delay_single_quote_subst"`' reload_cmds='`$ECHO "$reload_cmds" | $SED "$delay_single_quote_subst"`' OBJDUMP='`$ECHO "$OBJDUMP" | $SED "$delay_single_quote_subst"`' deplibs_check_method='`$ECHO "$deplibs_check_method" | $SED "$delay_single_quote_subst"`' file_magic_cmd='`$ECHO "$file_magic_cmd" | $SED "$delay_single_quote_subst"`' file_magic_glob='`$ECHO "$file_magic_glob" | $SED "$delay_single_quote_subst"`' want_nocaseglob='`$ECHO "$want_nocaseglob" | $SED "$delay_single_quote_subst"`' DLLTOOL='`$ECHO "$DLLTOOL" | $SED "$delay_single_quote_subst"`' sharedlib_from_linklib_cmd='`$ECHO "$sharedlib_from_linklib_cmd" | $SED "$delay_single_quote_subst"`' AR='`$ECHO "$AR" | $SED "$delay_single_quote_subst"`' AR_FLAGS='`$ECHO "$AR_FLAGS" | $SED "$delay_single_quote_subst"`' archiver_list_spec='`$ECHO "$archiver_list_spec" | $SED "$delay_single_quote_subst"`' STRIP='`$ECHO "$STRIP" | $SED "$delay_single_quote_subst"`' RANLIB='`$ECHO "$RANLIB" | $SED "$delay_single_quote_subst"`' old_postinstall_cmds='`$ECHO "$old_postinstall_cmds" | $SED "$delay_single_quote_subst"`' old_postuninstall_cmds='`$ECHO "$old_postuninstall_cmds" | $SED "$delay_single_quote_subst"`' old_archive_cmds='`$ECHO "$old_archive_cmds" | $SED "$delay_single_quote_subst"`' lock_old_archive_extraction='`$ECHO "$lock_old_archive_extraction" | $SED "$delay_single_quote_subst"`' CC='`$ECHO "$CC" | $SED "$delay_single_quote_subst"`' CFLAGS='`$ECHO "$CFLAGS" | $SED "$delay_single_quote_subst"`' compiler='`$ECHO "$compiler" | $SED "$delay_single_quote_subst"`' GCC='`$ECHO "$GCC" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_pipe='`$ECHO "$lt_cv_sys_global_symbol_pipe" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_cdecl='`$ECHO "$lt_cv_sys_global_symbol_to_cdecl" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $SED "$delay_single_quote_subst"`' nm_file_list_spec='`$ECHO "$nm_file_list_spec" | $SED "$delay_single_quote_subst"`' lt_sysroot='`$ECHO "$lt_sysroot" | $SED "$delay_single_quote_subst"`' objdir='`$ECHO "$objdir" | $SED "$delay_single_quote_subst"`' MAGIC_CMD='`$ECHO "$MAGIC_CMD" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_no_builtin_flag='`$ECHO "$lt_prog_compiler_no_builtin_flag" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_pic='`$ECHO "$lt_prog_compiler_pic" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_wl='`$ECHO "$lt_prog_compiler_wl" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_static='`$ECHO "$lt_prog_compiler_static" | $SED "$delay_single_quote_subst"`' lt_cv_prog_compiler_c_o='`$ECHO "$lt_cv_prog_compiler_c_o" | $SED "$delay_single_quote_subst"`' need_locks='`$ECHO "$need_locks" | $SED "$delay_single_quote_subst"`' MANIFEST_TOOL='`$ECHO "$MANIFEST_TOOL" | $SED "$delay_single_quote_subst"`' DSYMUTIL='`$ECHO "$DSYMUTIL" | $SED "$delay_single_quote_subst"`' NMEDIT='`$ECHO "$NMEDIT" | $SED "$delay_single_quote_subst"`' LIPO='`$ECHO "$LIPO" | $SED "$delay_single_quote_subst"`' OTOOL='`$ECHO "$OTOOL" | $SED "$delay_single_quote_subst"`' OTOOL64='`$ECHO "$OTOOL64" | $SED "$delay_single_quote_subst"`' libext='`$ECHO "$libext" | $SED "$delay_single_quote_subst"`' shrext_cmds='`$ECHO "$shrext_cmds" | $SED "$delay_single_quote_subst"`' extract_expsyms_cmds='`$ECHO "$extract_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds_need_lc='`$ECHO "$archive_cmds_need_lc" | $SED "$delay_single_quote_subst"`' enable_shared_with_static_runtimes='`$ECHO "$enable_shared_with_static_runtimes" | $SED "$delay_single_quote_subst"`' export_dynamic_flag_spec='`$ECHO "$export_dynamic_flag_spec" | $SED "$delay_single_quote_subst"`' whole_archive_flag_spec='`$ECHO "$whole_archive_flag_spec" | $SED "$delay_single_quote_subst"`' compiler_needs_object='`$ECHO "$compiler_needs_object" | $SED "$delay_single_quote_subst"`' old_archive_from_new_cmds='`$ECHO "$old_archive_from_new_cmds" | $SED "$delay_single_quote_subst"`' old_archive_from_expsyms_cmds='`$ECHO "$old_archive_from_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds='`$ECHO "$archive_cmds" | $SED "$delay_single_quote_subst"`' archive_expsym_cmds='`$ECHO "$archive_expsym_cmds" | $SED "$delay_single_quote_subst"`' module_cmds='`$ECHO "$module_cmds" | $SED "$delay_single_quote_subst"`' module_expsym_cmds='`$ECHO "$module_expsym_cmds" | $SED "$delay_single_quote_subst"`' with_gnu_ld='`$ECHO "$with_gnu_ld" | $SED "$delay_single_quote_subst"`' allow_undefined_flag='`$ECHO "$allow_undefined_flag" | $SED "$delay_single_quote_subst"`' no_undefined_flag='`$ECHO "$no_undefined_flag" | $SED "$delay_single_quote_subst"`' hardcode_libdir_flag_spec='`$ECHO "$hardcode_libdir_flag_spec" | $SED "$delay_single_quote_subst"`' hardcode_libdir_separator='`$ECHO "$hardcode_libdir_separator" | $SED "$delay_single_quote_subst"`' hardcode_direct='`$ECHO "$hardcode_direct" | $SED "$delay_single_quote_subst"`' hardcode_direct_absolute='`$ECHO "$hardcode_direct_absolute" | $SED "$delay_single_quote_subst"`' hardcode_minus_L='`$ECHO "$hardcode_minus_L" | $SED "$delay_single_quote_subst"`' hardcode_shlibpath_var='`$ECHO "$hardcode_shlibpath_var" | $SED "$delay_single_quote_subst"`' hardcode_automatic='`$ECHO "$hardcode_automatic" | $SED "$delay_single_quote_subst"`' inherit_rpath='`$ECHO "$inherit_rpath" | $SED "$delay_single_quote_subst"`' link_all_deplibs='`$ECHO "$link_all_deplibs" | $SED "$delay_single_quote_subst"`' always_export_symbols='`$ECHO "$always_export_symbols" | $SED "$delay_single_quote_subst"`' export_symbols_cmds='`$ECHO "$export_symbols_cmds" | $SED "$delay_single_quote_subst"`' exclude_expsyms='`$ECHO "$exclude_expsyms" | $SED "$delay_single_quote_subst"`' include_expsyms='`$ECHO "$include_expsyms" | $SED "$delay_single_quote_subst"`' prelink_cmds='`$ECHO "$prelink_cmds" | $SED "$delay_single_quote_subst"`' postlink_cmds='`$ECHO "$postlink_cmds" | $SED "$delay_single_quote_subst"`' file_list_spec='`$ECHO "$file_list_spec" | $SED "$delay_single_quote_subst"`' variables_saved_for_relink='`$ECHO "$variables_saved_for_relink" | $SED "$delay_single_quote_subst"`' need_lib_prefix='`$ECHO "$need_lib_prefix" | $SED "$delay_single_quote_subst"`' need_version='`$ECHO "$need_version" | $SED "$delay_single_quote_subst"`' version_type='`$ECHO "$version_type" | $SED "$delay_single_quote_subst"`' runpath_var='`$ECHO "$runpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_var='`$ECHO "$shlibpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_overrides_runpath='`$ECHO "$shlibpath_overrides_runpath" | $SED "$delay_single_quote_subst"`' libname_spec='`$ECHO "$libname_spec" | $SED "$delay_single_quote_subst"`' library_names_spec='`$ECHO "$library_names_spec" | $SED "$delay_single_quote_subst"`' soname_spec='`$ECHO "$soname_spec" | $SED "$delay_single_quote_subst"`' install_override_mode='`$ECHO "$install_override_mode" | $SED "$delay_single_quote_subst"`' postinstall_cmds='`$ECHO "$postinstall_cmds" | $SED "$delay_single_quote_subst"`' postuninstall_cmds='`$ECHO "$postuninstall_cmds" | $SED "$delay_single_quote_subst"`' finish_cmds='`$ECHO "$finish_cmds" | $SED "$delay_single_quote_subst"`' finish_eval='`$ECHO "$finish_eval" | $SED "$delay_single_quote_subst"`' hardcode_into_libs='`$ECHO "$hardcode_into_libs" | $SED "$delay_single_quote_subst"`' sys_lib_search_path_spec='`$ECHO "$sys_lib_search_path_spec" | $SED "$delay_single_quote_subst"`' sys_lib_dlsearch_path_spec='`$ECHO "$sys_lib_dlsearch_path_spec" | $SED "$delay_single_quote_subst"`' hardcode_action='`$ECHO "$hardcode_action" | $SED "$delay_single_quote_subst"`' enable_dlopen='`$ECHO "$enable_dlopen" | $SED "$delay_single_quote_subst"`' enable_dlopen_self='`$ECHO "$enable_dlopen_self" | $SED "$delay_single_quote_subst"`' enable_dlopen_self_static='`$ECHO "$enable_dlopen_self_static" | $SED "$delay_single_quote_subst"`' old_striplib='`$ECHO "$old_striplib" | $SED "$delay_single_quote_subst"`' striplib='`$ECHO "$striplib" | $SED "$delay_single_quote_subst"`' LTCC='$LTCC' LTCFLAGS='$LTCFLAGS' compiler='$compiler_DEFAULT' # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } # Quote evaled strings. for var in SHELL \ ECHO \ PATH_SEPARATOR \ SED \ GREP \ EGREP \ FGREP \ LD \ NM \ LN_S \ lt_SP2NL \ lt_NL2SP \ reload_flag \ OBJDUMP \ deplibs_check_method \ file_magic_cmd \ file_magic_glob \ want_nocaseglob \ DLLTOOL \ sharedlib_from_linklib_cmd \ AR \ AR_FLAGS \ archiver_list_spec \ STRIP \ RANLIB \ CC \ CFLAGS \ compiler \ lt_cv_sys_global_symbol_pipe \ lt_cv_sys_global_symbol_to_cdecl \ lt_cv_sys_global_symbol_to_c_name_address \ lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \ nm_file_list_spec \ lt_prog_compiler_no_builtin_flag \ lt_prog_compiler_pic \ lt_prog_compiler_wl \ lt_prog_compiler_static \ lt_cv_prog_compiler_c_o \ need_locks \ MANIFEST_TOOL \ DSYMUTIL \ NMEDIT \ LIPO \ OTOOL \ OTOOL64 \ shrext_cmds \ export_dynamic_flag_spec \ whole_archive_flag_spec \ compiler_needs_object \ with_gnu_ld \ allow_undefined_flag \ no_undefined_flag \ hardcode_libdir_flag_spec \ hardcode_libdir_separator \ exclude_expsyms \ include_expsyms \ file_list_spec \ variables_saved_for_relink \ libname_spec \ library_names_spec \ soname_spec \ install_override_mode \ finish_eval \ old_striplib \ striplib; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done # Double-quote double-evaled strings. for var in reload_cmds \ old_postinstall_cmds \ old_postuninstall_cmds \ old_archive_cmds \ extract_expsyms_cmds \ old_archive_from_new_cmds \ old_archive_from_expsyms_cmds \ archive_cmds \ archive_expsym_cmds \ module_cmds \ module_expsym_cmds \ export_symbols_cmds \ prelink_cmds \ postlink_cmds \ postinstall_cmds \ postuninstall_cmds \ finish_cmds \ sys_lib_search_path_spec \ sys_lib_dlsearch_path_spec; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done ac_aux_dir='$ac_aux_dir' xsi_shell='$xsi_shell' lt_shell_append='$lt_shell_append' # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes INIT. if test -n "\${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi PACKAGE='$PACKAGE' VERSION='$VERSION' TIMESTAMP='$TIMESTAMP' RM='$RM' ofile='$ofile' _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets do case $ac_config_target in "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;; "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; "libenet.pc") CONFIG_FILES="$CONFIG_FILES libenet.pc" ;; *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: # after its creation but before its name has been assigned to `$tmp'. $debug || { tmp= ac_tmp= trap 'exit_status=$? : "${ac_tmp:=$tmp}" { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status ' 0 trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 ac_tmp=$tmp # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. # This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then ac_cr=`echo X | tr X '\015'` # On cygwin, bash can eat \r inside `` if the user requested igncr. # But we know of no other shell where ac_cr would be empty at this # point, so we can use a bashism as a fallback. if test "x$ac_cr" = x; then eval ac_cr=\$\'\\r\' fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi echo 'BEGIN {' >"$ac_tmp/subs1.awk" && _ACEOF { echo "cat >conf$$subs.awk <<_ACEOF" && echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h s/^/S["/; s/!.*/"]=/ p g s/^[^!]*!// :repl t repl s/'"$ac_delim"'$// t delim :nl h s/\(.\{148\}\)..*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p n b repl :more1 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t nl :delim h s/\(.\{148\}\)..*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p b :more2 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t delim ' >$CONFIG_STATUS || ac_write_fail=1 rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" } { line = $ 0 nfields = split(line, field, "@") substed = 0 len = length(field[1]) for (i = 2; i < nfields; i++) { key = field[i] keylen = length(key) if (S_is_set[key]) { value = S[key] line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) len += length(value) + length(field[++i]) substed = 1 } else len += 1 + keylen } print line } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF # VPATH may cause trouble with some makes, so we remove sole $(srcdir), # ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ h s/// s/^/:/ s/[ ]*$/:/ s/:\$(srcdir):/:/g s/:\${srcdir}:/:/g s/:@srcdir@:/:/g s/^:*// s/:*$// x s/\(=[ ]*\).*/\1/ G s/\n// s/^[^=]*=[ ]*$// }' fi cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" eval set X " :F $CONFIG_FILES :C $CONFIG_COMMANDS" shift for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac ac_save_IFS=$IFS IFS=: set x $ac_tag IFS=$ac_save_IFS shift ac_file=$1 shift case $ac_mode in :L) ac_source=$1;; :[FH]) ac_file_inputs= for ac_f do case $ac_f in -) ac_f="$ac_tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain `:'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 $as_echo "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. case $configure_input in #( *\&* | *\|* | *\\* ) ac_sed_conf_input=`$as_echo "$configure_input" | sed 's/[\\\\&|]/\\\\&/g'`;; #( *) ac_sed_conf_input=$configure_input;; esac case $ac_tag in *:-:* | *:-) cat >"$ac_tmp/stdin" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix case $ac_mode in :F) # # CONFIG_FILE # case $INSTALL in [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; esac ac_MKDIR_P=$MKDIR_P case $MKDIR_P in [\\/$]* | ?:[\\/]* ) ;; */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; esac _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= ac_sed_dataroot=' /datarootdir/ { p q } /@datadir@/p /@docdir@/p /@infodir@/p /@localedir@/p /@mandir@/p' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 $as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_sed_extra="$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t s&@MKDIR_P@&$ac_MKDIR_P&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ "$ac_tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$ac_tmp/stdin" case $ac_file in -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; esac \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; :C) { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5 $as_echo "$as_me: executing $ac_file commands" >&6;} ;; esac case $ac_file$ac_mode in "depfiles":C) test x"$AMDEP_TRUE" != x"" || { # Autoconf 2.62 quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named `Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`$as_dirname -- "$mf" || $as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$mf" : 'X\(//\)[^/]' \| \ X"$mf" : 'X\(//\)$' \| \ X"$mf" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$mf" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running `make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # When using ansi2knr, U may be empty or an underscore; expand it U=`sed -n 's/^U = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`$as_dirname -- "$file" || $as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$file" : 'X\(//\)[^/]' \| \ X"$file" : 'X\(//\)$' \| \ X"$file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir=$dirpart/$fdir; as_fn_mkdir_p # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done } ;; "libtool":C) # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi cfgfile="${ofile}T" trap "$RM \"$cfgfile\"; exit 1" 1 2 15 $RM "$cfgfile" cat <<_LT_EOF >> "$cfgfile" #! $SHELL # `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. # Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION # Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is part of GNU Libtool. # # GNU Libtool is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, or # obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # The names of the tagged configurations supported by this script. available_tags="" # ### BEGIN LIBTOOL CONFIG # Which release of libtool.m4 was used? macro_version=$macro_version macro_revision=$macro_revision # Whether or not to build shared libraries. build_libtool_libs=$enable_shared # Whether or not to build static libraries. build_old_libs=$enable_static # What type of objects to build. pic_mode=$pic_mode # Whether or not to optimize for fast installation. fast_install=$enable_fast_install # Shell to use when invoking shell scripts. SHELL=$lt_SHELL # An echo program that protects backslashes. ECHO=$lt_ECHO # The PATH separator for the build system. PATH_SEPARATOR=$lt_PATH_SEPARATOR # The host system. host_alias=$host_alias host=$host host_os=$host_os # The build system. build_alias=$build_alias build=$build build_os=$build_os # A sed program that does not truncate output. SED=$lt_SED # Sed that helps us avoid accidentally triggering echo(1) options like -n. Xsed="\$SED -e 1s/^X//" # A grep program that handles long lines. GREP=$lt_GREP # An ERE matcher. EGREP=$lt_EGREP # A literal string matcher. FGREP=$lt_FGREP # A BSD- or MS-compatible name lister. NM=$lt_NM # Whether we need soft or hard links. LN_S=$lt_LN_S # What is the maximum length of a command? max_cmd_len=$max_cmd_len # Object file suffix (normally "o"). objext=$ac_objext # Executable file suffix (normally ""). exeext=$exeext # whether the shell understands "unset". lt_unset=$lt_unset # turn spaces into newlines. SP2NL=$lt_lt_SP2NL # turn newlines into spaces. NL2SP=$lt_lt_NL2SP # convert \$build file names to \$host format. to_host_file_cmd=$lt_cv_to_host_file_cmd # convert \$build files to toolchain format. to_tool_file_cmd=$lt_cv_to_tool_file_cmd # An object symbol dumper. OBJDUMP=$lt_OBJDUMP # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method # Command to use when deplibs_check_method = "file_magic". file_magic_cmd=$lt_file_magic_cmd # How to find potential files when deplibs_check_method = "file_magic". file_magic_glob=$lt_file_magic_glob # Find potential files using nocaseglob when deplibs_check_method = "file_magic". want_nocaseglob=$lt_want_nocaseglob # DLL creation program. DLLTOOL=$lt_DLLTOOL # Command to associate shared and link libraries. sharedlib_from_linklib_cmd=$lt_sharedlib_from_linklib_cmd # The archiver. AR=$lt_AR # Flags to create an archive. AR_FLAGS=$lt_AR_FLAGS # How to feed a file listing to the archiver. archiver_list_spec=$lt_archiver_list_spec # A symbol stripping program. STRIP=$lt_STRIP # Commands used to install an old-style archive. RANLIB=$lt_RANLIB old_postinstall_cmds=$lt_old_postinstall_cmds old_postuninstall_cmds=$lt_old_postuninstall_cmds # Whether to use a lock for old archive extraction. lock_old_archive_extraction=$lock_old_archive_extraction # A C compiler. LTCC=$lt_CC # LTCC compiler flags. LTCFLAGS=$lt_CFLAGS # Take the output of nm and produce a listing of raw symbols and C names. global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe # Transform the output of nm in a proper C declaration. global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl # Transform the output of nm in a C name address pair. global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address # Transform the output of nm in a C name address pair when lib prefix is needed. global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix # Specify filename containing input files for \$NM. nm_file_list_spec=$lt_nm_file_list_spec # The root where to search for dependent libraries,and in which our libraries should be installed. lt_sysroot=$lt_sysroot # The name of the directory that contains temporary libtool files. objdir=$objdir # Used to examine libraries when file_magic_cmd begins with "file". MAGIC_CMD=$MAGIC_CMD # Must we lock files when doing compilation? need_locks=$lt_need_locks # Manifest tool. MANIFEST_TOOL=$lt_MANIFEST_TOOL # Tool to manipulate archived DWARF debug symbol files on Mac OS X. DSYMUTIL=$lt_DSYMUTIL # Tool to change global to local symbols on Mac OS X. NMEDIT=$lt_NMEDIT # Tool to manipulate fat objects and archives on Mac OS X. LIPO=$lt_LIPO # ldd/readelf like tool for Mach-O binaries on Mac OS X. OTOOL=$lt_OTOOL # ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. OTOOL64=$lt_OTOOL64 # Old archive suffix (normally "a"). libext=$libext # Shared library suffix (normally ".so"). shrext_cmds=$lt_shrext_cmds # The commands to extract the exported symbol list from a shared archive. extract_expsyms_cmds=$lt_extract_expsyms_cmds # Variables whose values should be saved in libtool wrapper scripts and # restored at link time. variables_saved_for_relink=$lt_variables_saved_for_relink # Do we need the "lib" prefix for modules? need_lib_prefix=$need_lib_prefix # Do we need a version for libraries? need_version=$need_version # Library versioning type. version_type=$version_type # Shared library runtime path variable. runpath_var=$runpath_var # Shared library path variable. shlibpath_var=$shlibpath_var # Is shlibpath searched before the hard-coded library search path? shlibpath_overrides_runpath=$shlibpath_overrides_runpath # Format of library name prefix. libname_spec=$lt_libname_spec # List of archive names. First name is the real one, the rest are links. # The last name is the one that the linker finds with -lNAME library_names_spec=$lt_library_names_spec # The coded name of the library, if different from the real name. soname_spec=$lt_soname_spec # Permission mode override for installation of shared libraries. install_override_mode=$lt_install_override_mode # Command to use after installation of a shared archive. postinstall_cmds=$lt_postinstall_cmds # Command to use after uninstallation of a shared archive. postuninstall_cmds=$lt_postuninstall_cmds # Commands used to finish a libtool library installation in a directory. finish_cmds=$lt_finish_cmds # As "finish_cmds", except a single script fragment to be evaled but # not shown. finish_eval=$lt_finish_eval # Whether we should hardcode library paths into libraries. hardcode_into_libs=$hardcode_into_libs # Compile-time system search path for libraries. sys_lib_search_path_spec=$lt_sys_lib_search_path_spec # Run-time system search path for libraries. sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec # Whether dlopen is supported. dlopen_support=$enable_dlopen # Whether dlopen of programs is supported. dlopen_self=$enable_dlopen_self # Whether dlopen of statically linked programs is supported. dlopen_self_static=$enable_dlopen_self_static # Commands to strip libraries. old_striplib=$lt_old_striplib striplib=$lt_striplib # The linker used to build libraries. LD=$lt_LD # How to create reloadable object files. reload_flag=$lt_reload_flag reload_cmds=$lt_reload_cmds # Commands used to build an old-style archive. old_archive_cmds=$lt_old_archive_cmds # A language specific compiler. CC=$lt_compiler # Is the compiler the GNU compiler? with_gcc=$GCC # Compiler flag to turn off builtin functions. no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag # Additional compiler flags for building library objects. pic_flag=$lt_lt_prog_compiler_pic # How to pass a linker flag through the compiler. wl=$lt_lt_prog_compiler_wl # Compiler flag to prevent dynamic linking. link_static_flag=$lt_lt_prog_compiler_static # Does compiler simultaneously support -c and -o options? compiler_c_o=$lt_lt_cv_prog_compiler_c_o # Whether or not to add -lc for building shared libraries. build_libtool_need_lc=$archive_cmds_need_lc # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec=$lt_export_dynamic_flag_spec # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec=$lt_whole_archive_flag_spec # Whether the compiler copes with passing no objects directly. compiler_needs_object=$lt_compiler_needs_object # Create an old-style archive from a shared archive. old_archive_from_new_cmds=$lt_old_archive_from_new_cmds # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds # Commands used to build a shared archive. archive_cmds=$lt_archive_cmds archive_expsym_cmds=$lt_archive_expsym_cmds # Commands used to build a loadable module if different from building # a shared archive. module_cmds=$lt_module_cmds module_expsym_cmds=$lt_module_expsym_cmds # Whether we are building with GNU ld or not. with_gnu_ld=$lt_with_gnu_ld # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag=$lt_allow_undefined_flag # Flag that enforces no undefined symbols. no_undefined_flag=$lt_no_undefined_flag # Flag to hardcode \$libdir into a binary during linking. # This must work even if \$libdir does not exist hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator=$lt_hardcode_libdir_separator # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary. hardcode_direct=$hardcode_direct # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting \${shlibpath_var} if the # library is relocated. hardcode_direct_absolute=$hardcode_direct_absolute # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L=$hardcode_minus_L # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var=$hardcode_shlibpath_var # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic=$hardcode_automatic # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath=$inherit_rpath # Whether libtool must link a program against all its dependency libraries. link_all_deplibs=$link_all_deplibs # Set to "yes" if exported symbols are required. always_export_symbols=$always_export_symbols # The commands to list exported symbols. export_symbols_cmds=$lt_export_symbols_cmds # Symbols that should not be listed in the preloaded symbols. exclude_expsyms=$lt_exclude_expsyms # Symbols that must always be exported. include_expsyms=$lt_include_expsyms # Commands necessary for linking programs (against libraries) with templates. prelink_cmds=$lt_prelink_cmds # Commands necessary for finishing linking programs. postlink_cmds=$lt_postlink_cmds # Specify filename containing input files. file_list_spec=$lt_file_list_spec # How to hardcode a shared library path into an executable. hardcode_action=$hardcode_action # ### END LIBTOOL CONFIG _LT_EOF case $host_os in aix3*) cat <<\_LT_EOF >> "$cfgfile" # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi _LT_EOF ;; esac ltmain="$ac_aux_dir/ltmain.sh" # We use sed instead of cat because bash on DJGPP gets confused if # if finds mixed CR/LF and LF-only lines. Since sed operates in # text mode, it properly converts lines to CR/LF. This bash problem # is reportedly fixed, but why not run on old versions too? sed '$q' "$ltmain" >> "$cfgfile" \ || (rm -f "$cfgfile"; exit 1) if test x"$xsi_shell" = xyes; then sed -e '/^func_dirname ()$/,/^} # func_dirname /c\ func_dirname ()\ {\ \ case ${1} in\ \ */*) func_dirname_result="${1%/*}${2}" ;;\ \ * ) func_dirname_result="${3}" ;;\ \ esac\ } # Extended-shell func_dirname implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_basename ()$/,/^} # func_basename /c\ func_basename ()\ {\ \ func_basename_result="${1##*/}"\ } # Extended-shell func_basename implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_dirname_and_basename ()$/,/^} # func_dirname_and_basename /c\ func_dirname_and_basename ()\ {\ \ case ${1} in\ \ */*) func_dirname_result="${1%/*}${2}" ;;\ \ * ) func_dirname_result="${3}" ;;\ \ esac\ \ func_basename_result="${1##*/}"\ } # Extended-shell func_dirname_and_basename implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_stripname ()$/,/^} # func_stripname /c\ func_stripname ()\ {\ \ # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\ \ # positional parameters, so assign one to ordinary parameter first.\ \ func_stripname_result=${3}\ \ func_stripname_result=${func_stripname_result#"${1}"}\ \ func_stripname_result=${func_stripname_result%"${2}"}\ } # Extended-shell func_stripname implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_split_long_opt ()$/,/^} # func_split_long_opt /c\ func_split_long_opt ()\ {\ \ func_split_long_opt_name=${1%%=*}\ \ func_split_long_opt_arg=${1#*=}\ } # Extended-shell func_split_long_opt implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_split_short_opt ()$/,/^} # func_split_short_opt /c\ func_split_short_opt ()\ {\ \ func_split_short_opt_arg=${1#??}\ \ func_split_short_opt_name=${1%"$func_split_short_opt_arg"}\ } # Extended-shell func_split_short_opt implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_lo2o ()$/,/^} # func_lo2o /c\ func_lo2o ()\ {\ \ case ${1} in\ \ *.lo) func_lo2o_result=${1%.lo}.${objext} ;;\ \ *) func_lo2o_result=${1} ;;\ \ esac\ } # Extended-shell func_lo2o implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_xform ()$/,/^} # func_xform /c\ func_xform ()\ {\ func_xform_result=${1%.*}.lo\ } # Extended-shell func_xform implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_arith ()$/,/^} # func_arith /c\ func_arith ()\ {\ func_arith_result=$(( $* ))\ } # Extended-shell func_arith implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_len ()$/,/^} # func_len /c\ func_len ()\ {\ func_len_result=${#1}\ } # Extended-shell func_len implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$lt_shell_append" = xyes; then sed -e '/^func_append ()$/,/^} # func_append /c\ func_append ()\ {\ eval "${1}+=\\${2}"\ } # Extended-shell func_append implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_append_quoted ()$/,/^} # func_append_quoted /c\ func_append_quoted ()\ {\ \ func_quote_for_eval "${2}"\ \ eval "${1}+=\\\\ \\$func_quote_for_eval_result"\ } # Extended-shell func_append_quoted implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: # Save a `func_append' function call where possible by direct use of '+=' sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: else # Save a `func_append' function call even when '+=' is not available sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$_lt_function_replace_fail" = x":"; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Unable to substitute extended shell functions in $ofile" >&5 $as_echo "$as_me: WARNING: Unable to substitute extended shell functions in $ofile" >&2;} fi mv -f "$cfgfile" "$ofile" || (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") chmod +x "$ofile" ;; esac done # for ac_tag as_fn_exit 0 _ACEOF ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || as_fn_exit 1 fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi sauerbraten-0.0.20130203.dfsg/enet/peer.c0000644000175000017500000010754712061673417017454 0ustar vincentvincent/** @file peer.c @brief ENet peer management functions */ #include #define ENET_BUILDING_LIB 1 #include "enet/enet.h" /** @defgroup peer ENet peer functions @{ */ /** Configures throttle parameter for a peer. Unreliable packets are dropped by ENet in response to the varying conditions of the Internet connection to the peer. The throttle represents a probability that an unreliable packet should not be dropped and thus sent by ENet to the peer. The lowest mean round trip time from the sending of a reliable packet to the receipt of its acknowledgement is measured over an amount of time specified by the interval parameter in milliseconds. If a measured round trip time happens to be significantly less than the mean round trip time measured over the interval, then the throttle probability is increased to allow more traffic by an amount specified in the acceleration parameter, which is a ratio to the ENET_PEER_PACKET_THROTTLE_SCALE constant. If a measured round trip time happens to be significantly greater than the mean round trip time measured over the interval, then the throttle probability is decreased to limit traffic by an amount specified in the deceleration parameter, which is a ratio to the ENET_PEER_PACKET_THROTTLE_SCALE constant. When the throttle has a value of ENET_PEER_PACKET_THROTTLE_SCALE, no unreliable packets are dropped by ENet, and so 100% of all unreliable packets will be sent. When the throttle has a value of 0, all unreliable packets are dropped by ENet, and so 0% of all unreliable packets will be sent. Intermediate values for the throttle represent intermediate probabilities between 0% and 100% of unreliable packets being sent. The bandwidth limits of the local and foreign hosts are taken into account to determine a sensible limit for the throttle probability above which it should not raise even in the best of conditions. @param peer peer to configure @param interval interval, in milliseconds, over which to measure lowest mean RTT; the default value is ENET_PEER_PACKET_THROTTLE_INTERVAL. @param acceleration rate at which to increase the throttle probability as mean RTT declines @param deceleration rate at which to decrease the throttle probability as mean RTT increases */ void enet_peer_throttle_configure (ENetPeer * peer, enet_uint32 interval, enet_uint32 acceleration, enet_uint32 deceleration) { ENetProtocol command; peer -> packetThrottleInterval = interval; peer -> packetThrottleAcceleration = acceleration; peer -> packetThrottleDeceleration = deceleration; command.header.command = ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE; command.header.channelID = 0xFF; command.throttleConfigure.packetThrottleInterval = ENET_HOST_TO_NET_32 (interval); command.throttleConfigure.packetThrottleAcceleration = ENET_HOST_TO_NET_32 (acceleration); command.throttleConfigure.packetThrottleDeceleration = ENET_HOST_TO_NET_32 (deceleration); enet_peer_queue_outgoing_command (peer, & command, NULL, 0, 0); } int enet_peer_throttle (ENetPeer * peer, enet_uint32 rtt) { if (peer -> lastRoundTripTime <= peer -> lastRoundTripTimeVariance) { peer -> packetThrottle = peer -> packetThrottleLimit; } else if (rtt < peer -> lastRoundTripTime) { peer -> packetThrottle += peer -> packetThrottleAcceleration; if (peer -> packetThrottle > peer -> packetThrottleLimit) peer -> packetThrottle = peer -> packetThrottleLimit; return 1; } else if (rtt > peer -> lastRoundTripTime + 2 * peer -> lastRoundTripTimeVariance) { if (peer -> packetThrottle > peer -> packetThrottleDeceleration) peer -> packetThrottle -= peer -> packetThrottleDeceleration; else peer -> packetThrottle = 0; return -1; } return 0; } /** Queues a packet to be sent. @param peer destination for the packet @param channelID channel on which to send @param packet packet to send @retval 0 on success @retval < 0 on failure */ int enet_peer_send (ENetPeer * peer, enet_uint8 channelID, ENetPacket * packet) { ENetChannel * channel = & peer -> channels [channelID]; ENetProtocol command; size_t fragmentLength; if (peer -> state != ENET_PEER_STATE_CONNECTED || channelID >= peer -> channelCount || packet -> dataLength > ENET_PROTOCOL_MAXIMUM_PACKET_SIZE) return -1; fragmentLength = peer -> mtu - sizeof (ENetProtocolHeader) - sizeof (ENetProtocolSendFragment); if (peer -> host -> checksum != NULL) fragmentLength -= sizeof(enet_uint32); if (packet -> dataLength > fragmentLength) { enet_uint32 fragmentCount = (packet -> dataLength + fragmentLength - 1) / fragmentLength, fragmentNumber, fragmentOffset; enet_uint8 commandNumber; enet_uint16 startSequenceNumber; ENetList fragments; ENetOutgoingCommand * fragment; if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT) return -1; if ((packet -> flags & (ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT)) == ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT && channel -> outgoingUnreliableSequenceNumber < 0xFFFF) { commandNumber = ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT; startSequenceNumber = ENET_HOST_TO_NET_16 (channel -> outgoingUnreliableSequenceNumber + 1); } else { commandNumber = ENET_PROTOCOL_COMMAND_SEND_FRAGMENT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE; startSequenceNumber = ENET_HOST_TO_NET_16 (channel -> outgoingReliableSequenceNumber + 1); } enet_list_clear (& fragments); for (fragmentNumber = 0, fragmentOffset = 0; fragmentOffset < packet -> dataLength; ++ fragmentNumber, fragmentOffset += fragmentLength) { if (packet -> dataLength - fragmentOffset < fragmentLength) fragmentLength = packet -> dataLength - fragmentOffset; fragment = (ENetOutgoingCommand *) enet_malloc (sizeof (ENetOutgoingCommand)); if (fragment == NULL) { while (! enet_list_empty (& fragments)) { fragment = (ENetOutgoingCommand *) enet_list_remove (enet_list_begin (& fragments)); enet_free (fragment); } return -1; } fragment -> fragmentOffset = fragmentOffset; fragment -> fragmentLength = fragmentLength; fragment -> packet = packet; fragment -> command.header.command = commandNumber; fragment -> command.header.channelID = channelID; fragment -> command.sendFragment.startSequenceNumber = startSequenceNumber; fragment -> command.sendFragment.dataLength = ENET_HOST_TO_NET_16 (fragmentLength); fragment -> command.sendFragment.fragmentCount = ENET_HOST_TO_NET_32 (fragmentCount); fragment -> command.sendFragment.fragmentNumber = ENET_HOST_TO_NET_32 (fragmentNumber); fragment -> command.sendFragment.totalLength = ENET_HOST_TO_NET_32 (packet -> dataLength); fragment -> command.sendFragment.fragmentOffset = ENET_NET_TO_HOST_32 (fragmentOffset); enet_list_insert (enet_list_end (& fragments), fragment); } packet -> referenceCount += fragmentNumber; while (! enet_list_empty (& fragments)) { fragment = (ENetOutgoingCommand *) enet_list_remove (enet_list_begin (& fragments)); enet_peer_setup_outgoing_command (peer, fragment); } return 0; } command.header.channelID = channelID; if ((packet -> flags & (ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNSEQUENCED)) == ENET_PACKET_FLAG_UNSEQUENCED) { command.header.command = ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED | ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED; command.sendUnsequenced.dataLength = ENET_HOST_TO_NET_16 (packet -> dataLength); } else if (packet -> flags & ENET_PACKET_FLAG_RELIABLE || channel -> outgoingUnreliableSequenceNumber >= 0xFFFF) { command.header.command = ENET_PROTOCOL_COMMAND_SEND_RELIABLE | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE; command.sendReliable.dataLength = ENET_HOST_TO_NET_16 (packet -> dataLength); } else { command.header.command = ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE; command.sendUnreliable.dataLength = ENET_HOST_TO_NET_16 (packet -> dataLength); } if (enet_peer_queue_outgoing_command (peer, & command, packet, 0, packet -> dataLength) == NULL) return -1; return 0; } /** Attempts to dequeue any incoming queued packet. @param peer peer to dequeue packets from @param channelID holds the channel ID of the channel the packet was received on success @returns a pointer to the packet, or NULL if there are no available incoming queued packets */ ENetPacket * enet_peer_receive (ENetPeer * peer, enet_uint8 * channelID) { ENetIncomingCommand * incomingCommand; ENetPacket * packet; if (enet_list_empty (& peer -> dispatchedCommands)) return NULL; incomingCommand = (ENetIncomingCommand *) enet_list_remove (enet_list_begin (& peer -> dispatchedCommands)); if (channelID != NULL) * channelID = incomingCommand -> command.header.channelID; packet = incomingCommand -> packet; -- packet -> referenceCount; if (incomingCommand -> fragments != NULL) enet_free (incomingCommand -> fragments); enet_free (incomingCommand); return packet; } static void enet_peer_reset_outgoing_commands (ENetList * queue) { ENetOutgoingCommand * outgoingCommand; while (! enet_list_empty (queue)) { outgoingCommand = (ENetOutgoingCommand *) enet_list_remove (enet_list_begin (queue)); if (outgoingCommand -> packet != NULL) { -- outgoingCommand -> packet -> referenceCount; if (outgoingCommand -> packet -> referenceCount == 0) enet_packet_destroy (outgoingCommand -> packet); } enet_free (outgoingCommand); } } static void enet_peer_remove_incoming_commands (ENetList * queue, ENetListIterator startCommand, ENetListIterator endCommand) { ENetListIterator currentCommand; for (currentCommand = startCommand; currentCommand != endCommand; ) { ENetIncomingCommand * incomingCommand = (ENetIncomingCommand *) currentCommand; currentCommand = enet_list_next (currentCommand); enet_list_remove (& incomingCommand -> incomingCommandList); if (incomingCommand -> packet != NULL) { -- incomingCommand -> packet -> referenceCount; if (incomingCommand -> packet -> referenceCount == 0) enet_packet_destroy (incomingCommand -> packet); } if (incomingCommand -> fragments != NULL) enet_free (incomingCommand -> fragments); enet_free (incomingCommand); } } static void enet_peer_reset_incoming_commands (ENetList * queue) { enet_peer_remove_incoming_commands(queue, enet_list_begin (queue), enet_list_end (queue)); } void enet_peer_reset_queues (ENetPeer * peer) { ENetChannel * channel; if (peer -> needsDispatch) { enet_list_remove (& peer -> dispatchList); peer -> needsDispatch = 0; } while (! enet_list_empty (& peer -> acknowledgements)) enet_free (enet_list_remove (enet_list_begin (& peer -> acknowledgements))); enet_peer_reset_outgoing_commands (& peer -> sentReliableCommands); enet_peer_reset_outgoing_commands (& peer -> sentUnreliableCommands); enet_peer_reset_outgoing_commands (& peer -> outgoingReliableCommands); enet_peer_reset_outgoing_commands (& peer -> outgoingUnreliableCommands); enet_peer_reset_incoming_commands (& peer -> dispatchedCommands); if (peer -> channels != NULL && peer -> channelCount > 0) { for (channel = peer -> channels; channel < & peer -> channels [peer -> channelCount]; ++ channel) { enet_peer_reset_incoming_commands (& channel -> incomingReliableCommands); enet_peer_reset_incoming_commands (& channel -> incomingUnreliableCommands); } enet_free (peer -> channels); } peer -> channels = NULL; peer -> channelCount = 0; } /** Forcefully disconnects a peer. @param peer peer to forcefully disconnect @remarks The foreign host represented by the peer is not notified of the disconnection and will timeout on its connection to the local host. */ void enet_peer_reset (ENetPeer * peer) { peer -> outgoingPeerID = ENET_PROTOCOL_MAXIMUM_PEER_ID; peer -> connectID = 0; peer -> state = ENET_PEER_STATE_DISCONNECTED; peer -> incomingBandwidth = 0; peer -> outgoingBandwidth = 0; peer -> incomingBandwidthThrottleEpoch = 0; peer -> outgoingBandwidthThrottleEpoch = 0; peer -> incomingDataTotal = 0; peer -> outgoingDataTotal = 0; peer -> lastSendTime = 0; peer -> lastReceiveTime = 0; peer -> nextTimeout = 0; peer -> earliestTimeout = 0; peer -> packetLossEpoch = 0; peer -> packetsSent = 0; peer -> packetsLost = 0; peer -> packetLoss = 0; peer -> packetLossVariance = 0; peer -> packetThrottle = ENET_PEER_DEFAULT_PACKET_THROTTLE; peer -> packetThrottleLimit = ENET_PEER_PACKET_THROTTLE_SCALE; peer -> packetThrottleCounter = 0; peer -> packetThrottleEpoch = 0; peer -> packetThrottleAcceleration = ENET_PEER_PACKET_THROTTLE_ACCELERATION; peer -> packetThrottleDeceleration = ENET_PEER_PACKET_THROTTLE_DECELERATION; peer -> packetThrottleInterval = ENET_PEER_PACKET_THROTTLE_INTERVAL; peer -> pingInterval = ENET_PEER_PING_INTERVAL; peer -> timeoutLimit = ENET_PEER_TIMEOUT_LIMIT; peer -> timeoutMinimum = ENET_PEER_TIMEOUT_MINIMUM; peer -> timeoutMaximum = ENET_PEER_TIMEOUT_MAXIMUM; peer -> lastRoundTripTime = ENET_PEER_DEFAULT_ROUND_TRIP_TIME; peer -> lowestRoundTripTime = ENET_PEER_DEFAULT_ROUND_TRIP_TIME; peer -> lastRoundTripTimeVariance = 0; peer -> highestRoundTripTimeVariance = 0; peer -> roundTripTime = ENET_PEER_DEFAULT_ROUND_TRIP_TIME; peer -> roundTripTimeVariance = 0; peer -> mtu = peer -> host -> mtu; peer -> reliableDataInTransit = 0; peer -> outgoingReliableSequenceNumber = 0; peer -> windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; peer -> incomingUnsequencedGroup = 0; peer -> outgoingUnsequencedGroup = 0; peer -> eventData = 0; memset (peer -> unsequencedWindow, 0, sizeof (peer -> unsequencedWindow)); enet_peer_reset_queues (peer); } /** Sends a ping request to a peer. @param peer destination for the ping request @remarks ping requests factor into the mean round trip time as designated by the roundTripTime field in the ENetPeer structure. Enet automatically pings all connected peers at regular intervals, however, this function may be called to ensure more frequent ping requests. */ void enet_peer_ping (ENetPeer * peer) { ENetProtocol command; if (peer -> state != ENET_PEER_STATE_CONNECTED) return; command.header.command = ENET_PROTOCOL_COMMAND_PING | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE; command.header.channelID = 0xFF; enet_peer_queue_outgoing_command (peer, & command, NULL, 0, 0); } /** Sets the interval at which pings will be sent to a peer. Pings are used both to monitor the liveness of the connection and also to dynamically adjust the throttle during periods of low traffic so that the throttle has reasonable responsiveness during traffic spikes. @param peer the peer to adjust @param pingInterval the interval at which to send pings; defaults to ENET_PEER_PING_INTERVAL if 0 */ void enet_peer_ping_interval (ENetPeer * peer, enet_uint32 pingInterval) { peer -> pingInterval = pingInterval ? pingInterval : ENET_PEER_PING_INTERVAL; } /** Sets the timeout parameters for a peer. The timeout parameter control how and when a peer will timeout from a failure to acknowledge reliable traffic. Timeout values use an exponential backoff mechanism, where if a reliable packet is not acknowledge within some multiple of the average RTT plus a variance tolerance, the timeout will be doubled until it reaches a set limit. If the timeout is thus at this limit and reliable packets have been sent but not acknowledged within a certain minimum time period, the peer will be disconnected. Alternatively, if reliable packets have been sent but not acknowledged for a certain maximum time period, the peer will be disconnected regardless of the current timeout limit value. @param peer the peer to adjust @param timeoutLimit the timeout limit; defaults to ENET_PEER_TIMEOUT_LIMIT if 0 @param timeoutMinimum the timeout minimum; defaults to ENET_PEER_TIMEOUT_MINIMUM if 0 @param timeoutMaximum the timeout maximum; defaults to ENET_PEER_TIMEOUT_MAXIMUM if 0 */ void enet_peer_timeout (ENetPeer * peer, enet_uint32 timeoutLimit, enet_uint32 timeoutMinimum, enet_uint32 timeoutMaximum) { peer -> timeoutLimit = timeoutLimit ? timeoutLimit : ENET_PEER_TIMEOUT_LIMIT; peer -> timeoutMinimum = timeoutMinimum ? timeoutMinimum : ENET_PEER_TIMEOUT_MINIMUM; peer -> timeoutMaximum = timeoutMaximum ? timeoutMaximum : ENET_PEER_TIMEOUT_MAXIMUM; } /** Force an immediate disconnection from a peer. @param peer peer to disconnect @param data data describing the disconnection @remarks No ENET_EVENT_DISCONNECT event will be generated. The foreign peer is not guarenteed to receive the disconnect notification, and is reset immediately upon return from this function. */ void enet_peer_disconnect_now (ENetPeer * peer, enet_uint32 data) { ENetProtocol command; if (peer -> state == ENET_PEER_STATE_DISCONNECTED) return; if (peer -> state != ENET_PEER_STATE_ZOMBIE && peer -> state != ENET_PEER_STATE_DISCONNECTING) { enet_peer_reset_queues (peer); command.header.command = ENET_PROTOCOL_COMMAND_DISCONNECT | ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED; command.header.channelID = 0xFF; command.disconnect.data = ENET_HOST_TO_NET_32 (data); enet_peer_queue_outgoing_command (peer, & command, NULL, 0, 0); enet_host_flush (peer -> host); } enet_peer_reset (peer); } /** Request a disconnection from a peer. @param peer peer to request a disconnection @param data data describing the disconnection @remarks An ENET_EVENT_DISCONNECT event will be generated by enet_host_service() once the disconnection is complete. */ void enet_peer_disconnect (ENetPeer * peer, enet_uint32 data) { ENetProtocol command; if (peer -> state == ENET_PEER_STATE_DISCONNECTING || peer -> state == ENET_PEER_STATE_DISCONNECTED || peer -> state == ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT || peer -> state == ENET_PEER_STATE_ZOMBIE) return; enet_peer_reset_queues (peer); command.header.command = ENET_PROTOCOL_COMMAND_DISCONNECT; command.header.channelID = 0xFF; command.disconnect.data = ENET_HOST_TO_NET_32 (data); if (peer -> state == ENET_PEER_STATE_CONNECTED || peer -> state == ENET_PEER_STATE_DISCONNECT_LATER) command.header.command |= ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE; else command.header.command |= ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED; enet_peer_queue_outgoing_command (peer, & command, NULL, 0, 0); if (peer -> state == ENET_PEER_STATE_CONNECTED || peer -> state == ENET_PEER_STATE_DISCONNECT_LATER) peer -> state = ENET_PEER_STATE_DISCONNECTING; else { enet_host_flush (peer -> host); enet_peer_reset (peer); } } /** Request a disconnection from a peer, but only after all queued outgoing packets are sent. @param peer peer to request a disconnection @param data data describing the disconnection @remarks An ENET_EVENT_DISCONNECT event will be generated by enet_host_service() once the disconnection is complete. */ void enet_peer_disconnect_later (ENetPeer * peer, enet_uint32 data) { if ((peer -> state == ENET_PEER_STATE_CONNECTED || peer -> state == ENET_PEER_STATE_DISCONNECT_LATER) && ! (enet_list_empty (& peer -> outgoingReliableCommands) && enet_list_empty (& peer -> outgoingUnreliableCommands) && enet_list_empty (& peer -> sentReliableCommands))) { peer -> state = ENET_PEER_STATE_DISCONNECT_LATER; peer -> eventData = data; } else enet_peer_disconnect (peer, data); } ENetAcknowledgement * enet_peer_queue_acknowledgement (ENetPeer * peer, const ENetProtocol * command, enet_uint16 sentTime) { ENetAcknowledgement * acknowledgement; if (command -> header.channelID < peer -> channelCount) { ENetChannel * channel = & peer -> channels [command -> header.channelID]; enet_uint16 reliableWindow = command -> header.reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE, currentWindow = channel -> incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE; if (command -> header.reliableSequenceNumber < channel -> incomingReliableSequenceNumber) reliableWindow += ENET_PEER_RELIABLE_WINDOWS; if (reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1 && reliableWindow <= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS) return NULL; } acknowledgement = (ENetAcknowledgement *) enet_malloc (sizeof (ENetAcknowledgement)); if (acknowledgement == NULL) return NULL; peer -> outgoingDataTotal += sizeof (ENetProtocolAcknowledge); acknowledgement -> sentTime = sentTime; acknowledgement -> command = * command; enet_list_insert (enet_list_end (& peer -> acknowledgements), acknowledgement); return acknowledgement; } void enet_peer_setup_outgoing_command (ENetPeer * peer, ENetOutgoingCommand * outgoingCommand) { ENetChannel * channel = & peer -> channels [outgoingCommand -> command.header.channelID]; peer -> outgoingDataTotal += enet_protocol_command_size (outgoingCommand -> command.header.command) + outgoingCommand -> fragmentLength; if (outgoingCommand -> command.header.channelID == 0xFF) { ++ peer -> outgoingReliableSequenceNumber; outgoingCommand -> reliableSequenceNumber = peer -> outgoingReliableSequenceNumber; outgoingCommand -> unreliableSequenceNumber = 0; } else if (outgoingCommand -> command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) { ++ channel -> outgoingReliableSequenceNumber; channel -> outgoingUnreliableSequenceNumber = 0; outgoingCommand -> reliableSequenceNumber = channel -> outgoingReliableSequenceNumber; outgoingCommand -> unreliableSequenceNumber = 0; } else if (outgoingCommand -> command.header.command & ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED) { ++ peer -> outgoingUnsequencedGroup; outgoingCommand -> reliableSequenceNumber = 0; outgoingCommand -> unreliableSequenceNumber = 0; } else { if (outgoingCommand -> fragmentOffset == 0) ++ channel -> outgoingUnreliableSequenceNumber; outgoingCommand -> reliableSequenceNumber = channel -> outgoingReliableSequenceNumber; outgoingCommand -> unreliableSequenceNumber = channel -> outgoingUnreliableSequenceNumber; } outgoingCommand -> sendAttempts = 0; outgoingCommand -> sentTime = 0; outgoingCommand -> roundTripTimeout = 0; outgoingCommand -> roundTripTimeoutLimit = 0; outgoingCommand -> command.header.reliableSequenceNumber = ENET_HOST_TO_NET_16 (outgoingCommand -> reliableSequenceNumber); switch (outgoingCommand -> command.header.command & ENET_PROTOCOL_COMMAND_MASK) { case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE: outgoingCommand -> command.sendUnreliable.unreliableSequenceNumber = ENET_HOST_TO_NET_16 (outgoingCommand -> unreliableSequenceNumber); break; case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED: outgoingCommand -> command.sendUnsequenced.unsequencedGroup = ENET_HOST_TO_NET_16 (peer -> outgoingUnsequencedGroup); break; default: break; } if (outgoingCommand -> command.header.command & ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) enet_list_insert (enet_list_end (& peer -> outgoingReliableCommands), outgoingCommand); else enet_list_insert (enet_list_end (& peer -> outgoingUnreliableCommands), outgoingCommand); } ENetOutgoingCommand * enet_peer_queue_outgoing_command (ENetPeer * peer, const ENetProtocol * command, ENetPacket * packet, enet_uint32 offset, enet_uint16 length) { ENetOutgoingCommand * outgoingCommand = (ENetOutgoingCommand *) enet_malloc (sizeof (ENetOutgoingCommand)); if (outgoingCommand == NULL) return NULL; outgoingCommand -> command = * command; outgoingCommand -> fragmentOffset = offset; outgoingCommand -> fragmentLength = length; outgoingCommand -> packet = packet; if (packet != NULL) ++ packet -> referenceCount; enet_peer_setup_outgoing_command (peer, outgoingCommand); return outgoingCommand; } void enet_peer_dispatch_incoming_unreliable_commands (ENetPeer * peer, ENetChannel * channel) { ENetListIterator droppedCommand, startCommand, currentCommand; for (droppedCommand = startCommand = currentCommand = enet_list_begin (& channel -> incomingUnreliableCommands); currentCommand != enet_list_end (& channel -> incomingUnreliableCommands); currentCommand = enet_list_next (currentCommand)) { ENetIncomingCommand * incomingCommand = (ENetIncomingCommand *) currentCommand; if ((incomingCommand -> command.header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED) continue; if (incomingCommand -> reliableSequenceNumber == channel -> incomingReliableSequenceNumber) { if (incomingCommand -> fragmentsRemaining <= 0) { channel -> incomingUnreliableSequenceNumber = incomingCommand -> unreliableSequenceNumber; continue; } if (startCommand != currentCommand) { enet_list_move (enet_list_end (& peer -> dispatchedCommands), startCommand, enet_list_previous (currentCommand)); if (! peer -> needsDispatch) { enet_list_insert (enet_list_end (& peer -> host -> dispatchQueue), & peer -> dispatchList); peer -> needsDispatch = 1; } droppedCommand = currentCommand; } else if (droppedCommand != currentCommand) droppedCommand = enet_list_previous (currentCommand); } else { enet_uint16 reliableWindow = incomingCommand -> reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE, currentWindow = channel -> incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE; if (incomingCommand -> reliableSequenceNumber < channel -> incomingReliableSequenceNumber) reliableWindow += ENET_PEER_RELIABLE_WINDOWS; if (reliableWindow >= currentWindow && reliableWindow < currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1) break; droppedCommand = enet_list_next (currentCommand); if (startCommand != currentCommand) { enet_list_move (enet_list_end (& peer -> dispatchedCommands), startCommand, enet_list_previous (currentCommand)); if (! peer -> needsDispatch) { enet_list_insert (enet_list_end (& peer -> host -> dispatchQueue), & peer -> dispatchList); peer -> needsDispatch = 1; } } } startCommand = enet_list_next (currentCommand); } if (startCommand != currentCommand) { enet_list_move (enet_list_end (& peer -> dispatchedCommands), startCommand, enet_list_previous (currentCommand)); if (! peer -> needsDispatch) { enet_list_insert (enet_list_end (& peer -> host -> dispatchQueue), & peer -> dispatchList); peer -> needsDispatch = 1; } droppedCommand = currentCommand; } enet_peer_remove_incoming_commands (& channel -> incomingUnreliableCommands, enet_list_begin (& channel -> incomingUnreliableCommands), droppedCommand); } void enet_peer_dispatch_incoming_reliable_commands (ENetPeer * peer, ENetChannel * channel) { ENetListIterator currentCommand; for (currentCommand = enet_list_begin (& channel -> incomingReliableCommands); currentCommand != enet_list_end (& channel -> incomingReliableCommands); currentCommand = enet_list_next (currentCommand)) { ENetIncomingCommand * incomingCommand = (ENetIncomingCommand *) currentCommand; if (incomingCommand -> fragmentsRemaining > 0 || incomingCommand -> reliableSequenceNumber != (enet_uint16) (channel -> incomingReliableSequenceNumber + 1)) break; channel -> incomingReliableSequenceNumber = incomingCommand -> reliableSequenceNumber; if (incomingCommand -> fragmentCount > 0) channel -> incomingReliableSequenceNumber += incomingCommand -> fragmentCount - 1; } if (currentCommand == enet_list_begin (& channel -> incomingReliableCommands)) return; channel -> incomingUnreliableSequenceNumber = 0; enet_list_move (enet_list_end (& peer -> dispatchedCommands), enet_list_begin (& channel -> incomingReliableCommands), enet_list_previous (currentCommand)); if (! peer -> needsDispatch) { enet_list_insert (enet_list_end (& peer -> host -> dispatchQueue), & peer -> dispatchList); peer -> needsDispatch = 1; } if (! enet_list_empty (& channel -> incomingUnreliableCommands)) enet_peer_dispatch_incoming_unreliable_commands (peer, channel); } ENetIncomingCommand * enet_peer_queue_incoming_command (ENetPeer * peer, const ENetProtocol * command, ENetPacket * packet, enet_uint32 fragmentCount) { static ENetIncomingCommand dummyCommand; ENetChannel * channel = & peer -> channels [command -> header.channelID]; enet_uint32 unreliableSequenceNumber = 0, reliableSequenceNumber = 0; enet_uint16 reliableWindow, currentWindow; ENetIncomingCommand * incomingCommand; ENetListIterator currentCommand; if (peer -> state == ENET_PEER_STATE_DISCONNECT_LATER) goto freePacket; if ((command -> header.command & ENET_PROTOCOL_COMMAND_MASK) != ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED) { reliableSequenceNumber = command -> header.reliableSequenceNumber; reliableWindow = reliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE; currentWindow = channel -> incomingReliableSequenceNumber / ENET_PEER_RELIABLE_WINDOW_SIZE; if (reliableSequenceNumber < channel -> incomingReliableSequenceNumber) reliableWindow += ENET_PEER_RELIABLE_WINDOWS; if (reliableWindow < currentWindow || reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1) goto freePacket; } switch (command -> header.command & ENET_PROTOCOL_COMMAND_MASK) { case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT: case ENET_PROTOCOL_COMMAND_SEND_RELIABLE: if (reliableSequenceNumber == channel -> incomingReliableSequenceNumber) goto freePacket; for (currentCommand = enet_list_previous (enet_list_end (& channel -> incomingReliableCommands)); currentCommand != enet_list_end (& channel -> incomingReliableCommands); currentCommand = enet_list_previous (currentCommand)) { incomingCommand = (ENetIncomingCommand *) currentCommand; if (reliableSequenceNumber >= channel -> incomingReliableSequenceNumber) { if (incomingCommand -> reliableSequenceNumber < channel -> incomingReliableSequenceNumber) continue; } else if (incomingCommand -> reliableSequenceNumber >= channel -> incomingReliableSequenceNumber) break; if (incomingCommand -> reliableSequenceNumber <= reliableSequenceNumber) { if (incomingCommand -> reliableSequenceNumber < reliableSequenceNumber) break; goto freePacket; } } break; case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE: case ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT: unreliableSequenceNumber = ENET_NET_TO_HOST_16 (command -> sendUnreliable.unreliableSequenceNumber); if (reliableSequenceNumber == channel -> incomingReliableSequenceNumber && unreliableSequenceNumber <= channel -> incomingUnreliableSequenceNumber) goto freePacket; for (currentCommand = enet_list_previous (enet_list_end (& channel -> incomingUnreliableCommands)); currentCommand != enet_list_end (& channel -> incomingUnreliableCommands); currentCommand = enet_list_previous (currentCommand)) { incomingCommand = (ENetIncomingCommand *) currentCommand; if ((command -> header.command & ENET_PROTOCOL_COMMAND_MASK) == ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED) continue; if (reliableSequenceNumber >= channel -> incomingReliableSequenceNumber) { if (incomingCommand -> reliableSequenceNumber < channel -> incomingReliableSequenceNumber) continue; } else if (incomingCommand -> reliableSequenceNumber >= channel -> incomingReliableSequenceNumber) break; if (incomingCommand -> reliableSequenceNumber < reliableSequenceNumber) break; if (incomingCommand -> reliableSequenceNumber > reliableSequenceNumber) continue; if (incomingCommand -> unreliableSequenceNumber <= unreliableSequenceNumber) { if (incomingCommand -> unreliableSequenceNumber < unreliableSequenceNumber) break; goto freePacket; } } break; case ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED: currentCommand = enet_list_end (& channel -> incomingUnreliableCommands); break; default: goto freePacket; } incomingCommand = (ENetIncomingCommand *) enet_malloc (sizeof (ENetIncomingCommand)); if (incomingCommand == NULL) goto notifyError; incomingCommand -> reliableSequenceNumber = command -> header.reliableSequenceNumber; incomingCommand -> unreliableSequenceNumber = unreliableSequenceNumber & 0xFFFF; incomingCommand -> command = * command; incomingCommand -> fragmentCount = fragmentCount; incomingCommand -> fragmentsRemaining = fragmentCount; incomingCommand -> packet = packet; incomingCommand -> fragments = NULL; if (fragmentCount > 0) { if (fragmentCount <= ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT) incomingCommand -> fragments = (enet_uint32 *) enet_malloc ((fragmentCount + 31) / 32 * sizeof (enet_uint32)); if (incomingCommand -> fragments == NULL) { enet_free (incomingCommand); goto notifyError; } memset (incomingCommand -> fragments, 0, (fragmentCount + 31) / 32 * sizeof (enet_uint32)); } if (packet != NULL) ++ packet -> referenceCount; enet_list_insert (enet_list_next (currentCommand), incomingCommand); switch (command -> header.command & ENET_PROTOCOL_COMMAND_MASK) { case ENET_PROTOCOL_COMMAND_SEND_FRAGMENT: case ENET_PROTOCOL_COMMAND_SEND_RELIABLE: enet_peer_dispatch_incoming_reliable_commands (peer, channel); break; default: enet_peer_dispatch_incoming_unreliable_commands (peer, channel); break; } return incomingCommand; freePacket: if (fragmentCount > 0) goto notifyError; if (packet != NULL && packet -> referenceCount == 0) enet_packet_destroy (packet); return & dummyCommand; notifyError: if (packet != NULL && packet -> referenceCount == 0) enet_packet_destroy (packet); return NULL; } /** @} */