Committed unspeakable necromancy on the graveyard of the repository.
git-svn-id: http://svn.berlios.de/svnroot/repos/oolite-linux/trunk@2331 127b21dd-08f5-0310-b4b7-95ae10353056master
parent
999fe7e969
commit
6aaf7a1e75
|
@ -0,0 +1,277 @@
|
|||
include $(GNUSTEP_MAKEFILES)/common.make
|
||||
CP = cp
|
||||
BUILD_WITH_DEBUG_FUNCTIONALITY = yes
|
||||
DOCKING_CLEARANCE = yes
|
||||
PROCEDURAL_PLANETS = yes
|
||||
WORMHOLE_SCANNER = yes
|
||||
TARGET_INCOMING_MISSILES = yes
|
||||
vpath %.m src/SDL:src/Core:src/Core/Entities:src/Core/Materials:src/Core/Scripting:src/Core/OXPVerifier:src/Core/Debug
|
||||
vpath %.h src/SDL:src/Core:src/Core/Entities:src/Core/Materials:src/Core/Scripting:src/Core/OXPVerifier:src/Core/Debug
|
||||
vpath %.c src/SDL:src/Core:src/BSDCompat:src/Core/Debug
|
||||
GNUSTEP_INSTALLATION_DIR = $(GNUSTEP_USER_ROOT)
|
||||
GNUSTEP_OBJ_DIR_BASENAME := $(GNUSTEP_OBJ_DIR_NAME)
|
||||
ifeq ($(GNUSTEP_HOST_OS),mingw32)
|
||||
ADDITIONAL_INCLUDE_DIRS = -Ideps/Windows-x86-deps/include -Isrc/SDL -Isrc/Core -Isrc/BSDCompat -Isrc/Core/Scripting -Isrc/Core/Materials -Isrc/Core/Entities -Isrc/Core/OXPVerifier -Isrc/Core/Debug
|
||||
ADDITIONAL_OBJC_LIBS = -lglu32 -lopengl32 -lpng12.dll -lmingw32 -lSDLmain -lSDL -lSDL_mixer -lgnustep-base -ljs32 -mwindows
|
||||
ADDITIONAL_CFLAGS = -DWIN32 -DNEED_STRLCPY `sdl-config --cflags`
|
||||
# note the vpath stuff above isn't working for me, so adding src/SDL and src/Core explicitly
|
||||
ADDITIONAL_OBJCFLAGS = -DLOADSAVEGUI -DWIN32 -DXP_WIN -Wno-import `sdl-config --cflags`
|
||||
oolite_LIB_DIRS += -L/usr/local/lib -L$(GNUSTEP_LOCAL_ROOT)/lib -Ldeps/Windows-x86-deps/lib
|
||||
else
|
||||
LIBJS_SRC_DIR = deps/Cross-platform-deps/SpiderMonkey/js/src
|
||||
LIBJS_BIN_DIR = $(LIBJS_SRC_DIR)/Linux_All_OPT.OBJ
|
||||
ADDITIONAL_INCLUDE_DIRS = -I$(LIBJS_SRC_DIR) -I$(LIBJS_BIN_DIR) -Isrc/SDL -Isrc/Core -Isrc/BSDCompat -Isrc/Core/Scripting -Isrc/Core/Materials -Isrc/Core/Entities -Isrc/Core/OXPVerifier -Isrc/Core/Debug
|
||||
ADDITIONAL_OBJC_LIBS = -lpng $(LIBJS_BIN_DIR)/libjs.a -lGLU -lGL -lSDL -lSDL_mixer -lgnustep-base
|
||||
ADDITIONAL_CFLAGS = -DLINUX -DNEED_STRLCPY `sdl-config --cflags`
|
||||
ADDITIONAL_OBJCFLAGS = -std=c99 -DLOADSAVEGUI -DLINUX -DXP_UNIX -Wno-import `sdl-config --cflags`
|
||||
oolite_LIB_DIRS += -L/usr/X11R6/lib/
|
||||
endif
|
||||
ifeq ($(libespeak),yes)
|
||||
ADDITIONAL_OBJC_LIBS += -lespeak
|
||||
ADDITIONAL_OBJCFLAGS+=-DHAVE_LIBESPEAK=1
|
||||
GNUSTEP_OBJ_DIR_NAME := $(GNUSTEP_OBJ_DIR_NAME).spk
|
||||
endif
|
||||
ifeq ($(debug),yes)
|
||||
ADDITIONAL_CFLAGS += -g -O0
|
||||
ADDITIONAL_OBJCFLAGS += -g -O0
|
||||
GNUSTEP_OBJ_DIR_NAME := $(GNUSTEP_OBJ_DIR_NAME).dbg
|
||||
ADDITIONAL_CFLAGS += -DDEBUG -DOO_DEBUG -DDEBUG_GRAPHVIZ
|
||||
ADDITIONAL_OBJCFLAGS += -DDEBUG -DOO_DEBUG -DDEBUG_GRAPHVIZ
|
||||
endif
|
||||
ifeq ($(BUILD_WITH_DEBUG_FUNCTIONALITY),no)
|
||||
ADDITIONAL_CFLAGS += -DNDEBUG
|
||||
ADDITIONAL_OBJCFLAGS += -DNDEBUG
|
||||
endif
|
||||
ifeq ($(PROCEDURAL_PLANETS),yes)
|
||||
ADDITIONAL_CFLAGS += -DALLOW_PROCEDURAL_PLANETS=1
|
||||
ADDITIONAL_OBJCFLAGS += -DALLOW_PROCEDURAL_PLANETS=1
|
||||
endif
|
||||
ifeq ($(DOCKING_CLEARANCE),yes)
|
||||
ADDITIONAL_CFLAGS += -DDOCKING_CLEARANCE_ENABLED=1
|
||||
ADDITIONAL_OBJCFLAGS += -DDOCKING_CLEARANCE_ENABLED=1
|
||||
endif
|
||||
ifeq ($(WORMHOLE_SCANNER),yes)
|
||||
ADDITIONAL_CFLAGS += -DWORMHOLE_SCANNER=1
|
||||
ADDITIONAL_OBJCFLAGS += -DWORMHOLE_SCANNER=1
|
||||
endif
|
||||
ifeq ($(TARGET_INCOMING_MISSILES),yes)
|
||||
ADDITIONAL_CFLAGS += -DTARGET_INCOMING_MISSILES=1
|
||||
ADDITIONAL_OBJCFLAGS += -DTARGET_INCOMING_MISSILES=1
|
||||
endif
|
||||
|
||||
ifeq ($(SNAPSHOT_BUILD), yes)
|
||||
ADDITIONAL_CFLAGS += -DSNAPSHOT_BUILD -DOOLITE_SNAPSHOT_VERSION=\"$(VERSION_STRING)\"
|
||||
ADDITIONAL_OBJCFLAGS += -DSNAPSHOT_BUILD -DOOLITE_SNAPSHOT_VERSION=\"$(VERSION_STRING)\"
|
||||
endif
|
||||
|
||||
OBJC_PROGRAM_NAME = oolite
|
||||
|
||||
oolite_C_FILES = \
|
||||
legacy_random.c \
|
||||
strlcpy.c \
|
||||
OOTCPStreamDecoder.c
|
||||
|
||||
|
||||
OOLITE_DEBUG_FILES = \
|
||||
OODebugMonitor.m \
|
||||
OODebugSupport.m \
|
||||
OODebugTCPConsoleClient.m \
|
||||
OOJSConsole.m \
|
||||
OOTCPStreamDecoderAbstractionLayer.m
|
||||
|
||||
OOLITE_ENTITY_FILES = \
|
||||
DustEntity.m \
|
||||
Entity.m \
|
||||
OOEntityWithDrawable.m \
|
||||
OOSelfDrawingEntity.m \
|
||||
ParticleEntity.m \
|
||||
PlanetEntity.m \
|
||||
PlayerEntity.m \
|
||||
PlayerEntityContracts.m \
|
||||
PlayerEntityControls.m \
|
||||
PlayerEntityLegacyScriptEngine.m \
|
||||
PlayerEntityLoadSave.m \
|
||||
PlayerEntityScriptMethods.m \
|
||||
PlayerEntitySound.m \
|
||||
PlayerEntityStickMapper.m \
|
||||
RingEntity.m \
|
||||
ShipEntity.m \
|
||||
ShipEntityAI.m \
|
||||
ShipEntityScriptMethods.m \
|
||||
SkyEntity.m \
|
||||
StationEntity.m \
|
||||
WormholeEntity.m
|
||||
|
||||
OOLITE_GRAPHICS_DRAWABLE_FILES = \
|
||||
OODrawable.m \
|
||||
OOMesh.m
|
||||
|
||||
OOLITE_GRAPHICS_MATERIAL_FILES = \
|
||||
OOBasicMaterial.m \
|
||||
OOMaterial.m \
|
||||
OONullTexture.m \
|
||||
OOPNGTextureLoader.m \
|
||||
OOShaderMaterial.m \
|
||||
OOShaderProgram.m \
|
||||
OOShaderUniform.m \
|
||||
OOShaderUniformMethodType.m \
|
||||
OOSingleTextureMaterial.m \
|
||||
OOTexture.m \
|
||||
OOTextureLoader.m \
|
||||
OOTextureScaling.m
|
||||
|
||||
OOLITE_GRAPHICS_MISC_FILES = \
|
||||
OOCamera.m \
|
||||
OOCrosshairs.m \
|
||||
OODebugGLDrawing.m \
|
||||
OOGraphicsResetManager.m \
|
||||
OOLight.m \
|
||||
OOOpenGL.m \
|
||||
OOOpenGLExtensionManager.m \
|
||||
OOProbabilisticTextureManager.m \
|
||||
OOSkyDrawable.m \
|
||||
OpenGLSprite.m
|
||||
|
||||
OOLITE_MATHS_FILES = \
|
||||
CollisionRegion.m \
|
||||
Geometry.m \
|
||||
Octree.m \
|
||||
OOFastArithmetic.m \
|
||||
OOMatrix.m \
|
||||
OOQuaternion.m \
|
||||
OOTriangle.m \
|
||||
OOVector.m \
|
||||
OOVoxel.m
|
||||
|
||||
OOLITE_OXP_VERIFIER_FILES = \
|
||||
OOAIStateMachineVerifierStage.m \
|
||||
OOCheckDemoShipsPListVerifierStage.m \
|
||||
OOCheckEquipmentPListVerifierStage.m \
|
||||
OOCheckRequiresPListVerifierStage.m \
|
||||
OOCheckShipDataPListVerifierStage.m \
|
||||
OOFileScannerVerifierStage.m \
|
||||
OOModelVerifierStage.m \
|
||||
OOOXPVerifier.m \
|
||||
OOOXPVerifierStage.m \
|
||||
OOPListSchemaVerifier.m \
|
||||
OOTextureVerifierStage.m
|
||||
|
||||
OOLITE_RSRC_MGMT_FILES = \
|
||||
OldSchoolPropertyListWriting.m \
|
||||
OOCache.m \
|
||||
OOCacheManager.m \
|
||||
OOConvertSystemDescriptions.m \
|
||||
OOPListParsing.m \
|
||||
ResourceManager.m \
|
||||
TextureStore.m
|
||||
|
||||
OOLITE_SCRIPTING_FILES = \
|
||||
EntityOOJavaScriptExtensions.m \
|
||||
OOJavaScriptEngine.m \
|
||||
OOJSCall.m \
|
||||
OOJSClock.m \
|
||||
OOJSEntity.m \
|
||||
OOJSEquipmentInfo.m \
|
||||
OOJSFunction.m \
|
||||
OOJSGlobal.m \
|
||||
OOJSMission.m \
|
||||
OOJSMissionVariables.m \
|
||||
OOJSOolite.m \
|
||||
OOJSPlanet.m \
|
||||
OOJSPlayer.m \
|
||||
OOJSPlayerShip.m \
|
||||
OOJSQuaternion.m \
|
||||
OOJSScript.m \
|
||||
OOJSShip.m \
|
||||
OOJSShipGroup.m \
|
||||
OOJSSound.m \
|
||||
OOJSSoundSource.m \
|
||||
OOJSSpecialFunctions.m \
|
||||
OOJSStation.m \
|
||||
OOJSSun.m \
|
||||
OOJSSystem.m \
|
||||
OOJSSystemInfo.m \
|
||||
OOJSTimer.m \
|
||||
OOJSVector.m \
|
||||
OOJSWorldScripts.m \
|
||||
OOLegacyScriptWhitelist.m \
|
||||
OOPListScript.m \
|
||||
OOScript.m \
|
||||
OOScriptTimer.m
|
||||
|
||||
OOLITE_SOUND_FILES = \
|
||||
OOBasicSoundReferencePoint.m \
|
||||
OOMusicController.m \
|
||||
OOSDLConcreteSound.m \
|
||||
OOSDLSound.m \
|
||||
OOSDLSoundChannel.m \
|
||||
OOSDLSoundMixer.m \
|
||||
OOSoundSource.m \
|
||||
OOSoundSourcePool.m \
|
||||
SDLMusic.m
|
||||
|
||||
OOLITE_UI_FILES = \
|
||||
GuiDisplayGen.m \
|
||||
HeadUpDisplay.m \
|
||||
OOEncodingConverter.m
|
||||
|
||||
OO_UTILITY_FILES = \
|
||||
Comparison.m \
|
||||
NSDictionaryOOExtensions.m \
|
||||
NSFileManagerOOExtensions.m \
|
||||
NSMutableDictionaryOOExtensions.m \
|
||||
NSScannerOOExtensions.m \
|
||||
NSStringOOExtensions.m \
|
||||
NSThreadOOExtensions.m \
|
||||
OOAsyncQueue.m \
|
||||
OOCollectionExtractors.m \
|
||||
OOColor.m \
|
||||
OOConstToString.m \
|
||||
OOCPUInfo.m \
|
||||
OOEntityFilterPredicate.m \
|
||||
OOExcludeObjectEnumerator.m \
|
||||
OOFilteringEnumerator.m \
|
||||
OOIsNumberLiteral.m \
|
||||
OOLogging.m \
|
||||
OOLogHeader.m \
|
||||
OOLogOutputHandler.m \
|
||||
OOPriorityQueue.m \
|
||||
OOProbabilitySet.m \
|
||||
OOShipGroup.m \
|
||||
OOStringParsing.m \
|
||||
OOWeakReference.m \
|
||||
OOXMLExtensions.m \
|
||||
OODeepCopy.m
|
||||
|
||||
OOLITE_MISC_FILES = \
|
||||
AI.m \
|
||||
GameController.m \
|
||||
JoystickHandler.m \
|
||||
main.m \
|
||||
MyOpenGLView.m \
|
||||
OOCharacter.m \
|
||||
OOCocoa.m \
|
||||
OOEquipmentType.m \
|
||||
OORoleSet.m \
|
||||
OOShipRegistry.m \
|
||||
OOSpatialReference.m \
|
||||
OOTrumble.m \
|
||||
Universe.m
|
||||
|
||||
oolite_OBJC_FILES = \
|
||||
$(OOLITE_DEBUG_FILES) \
|
||||
$(OOLITE_ENTITY_FILES) \
|
||||
$(OOLITE_GRAPHICS_DRAWABLE_FILES) \
|
||||
$(OOLITE_GRAPHICS_MATERIAL_FILES) \
|
||||
$(OOLITE_GRAPHICS_MISC_FILES) \
|
||||
$(OOLITE_MATHS_FILES) \
|
||||
$(OOLITE_OXP_VERIFIER_FILES) \
|
||||
$(OOLITE_RSRC_MGMT_FILES) \
|
||||
$(OOLITE_SCRIPTING_FILES) \
|
||||
$(OOLITE_SOUND_FILES) \
|
||||
$(OOLITE_UI_FILES) \
|
||||
$(OO_UTILITY_FILES) \
|
||||
$(OOLITE_MISC_FILES)
|
||||
|
||||
include $(GNUSTEP_MAKEFILES)/objc.make
|
||||
include GNUmakefile.postamble
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,6 @@
|
|||
Schemata
|
||||
=======
|
||||
|
||||
This folder contains property list schemata for the various plists used in Oolite.
|
||||
|
||||
For more information, see src/Core/OXPVerifier/OOPListSchemaVerifier.h and tools/plistSchemaVerifier.
|
|
@ -0,0 +1,12 @@
|
|||
/*
|
||||
Schema for demoships.plist.
|
||||
*/
|
||||
|
||||
{
|
||||
type = array;
|
||||
valueType =
|
||||
{
|
||||
type = delegatedType;
|
||||
baseType = string;
|
||||
};
|
||||
}
|
|
@ -0,0 +1,134 @@
|
|||
/*
|
||||
Schema for hud.plist.
|
||||
*/
|
||||
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"dials" =
|
||||
{
|
||||
type = array;
|
||||
valueType =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
// Not all values apply to all types of dial.
|
||||
"alpha" = $floatZeroToTwo;
|
||||
"equipment_required" = $equipmentKey;
|
||||
"selector" = $oneParamSelector;
|
||||
"x" = integer;
|
||||
"y" = integer;
|
||||
"width" = positiveFloat;
|
||||
"height" = positiveFloat;
|
||||
"rgb_color" = $simpleRGBColor;
|
||||
"color" = $colourSpecifier; // Alternative to rgb_color as of 1.70
|
||||
"draw_surround" = boolean;
|
||||
"labelled" = boolean;
|
||||
"spacing" = positiveInteger;
|
||||
"n_bars" = positiveInteger;
|
||||
|
||||
// These are for use with the resizeGuis: selector, which isn't actually useful at this time.
|
||||
"message_gui" = $guiParameters;
|
||||
"comm_log_gui" = $guiParameters;
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "selector" );
|
||||
};
|
||||
};
|
||||
legends =
|
||||
{
|
||||
type = array;
|
||||
valueType =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"text" = string;
|
||||
"x" = integer;
|
||||
"y" = integer;
|
||||
"width" = positiveFloat;
|
||||
"height" = positiveFloat;
|
||||
"image" = $imageFileName;
|
||||
};
|
||||
allowOthers = NO;
|
||||
};
|
||||
allowOthers = NO;
|
||||
};
|
||||
};
|
||||
allowOthers = NO;
|
||||
$definitions =
|
||||
{
|
||||
$equipmentKey =
|
||||
{
|
||||
type = string;
|
||||
requiredPrefix = "EQ_";
|
||||
};
|
||||
$oneParamSelector =
|
||||
{
|
||||
type = delegatedType;
|
||||
key = oneParamSelector;
|
||||
baseType =
|
||||
{
|
||||
type = string;
|
||||
requiredSuffix = ":";
|
||||
};
|
||||
};
|
||||
$floatZeroToOne =
|
||||
{
|
||||
type = positiveFloat;
|
||||
maximum = 1;
|
||||
};
|
||||
$floatZeroToTwo =
|
||||
{
|
||||
// Alpha can reasonably be two for aegis, since it's scaled by 0.5.
|
||||
type = positiveFloat;
|
||||
maximum = 2;
|
||||
};
|
||||
$simpleRGBColor =
|
||||
{
|
||||
type = array;
|
||||
valueType = $floatZeroToOne;
|
||||
minCount = 3;
|
||||
maxCount = 3;
|
||||
};
|
||||
$colorSpecifier =
|
||||
{
|
||||
type = delegatedType;
|
||||
baseType =
|
||||
{
|
||||
type = oneOf;
|
||||
options =
|
||||
(
|
||||
array,
|
||||
dictionary,
|
||||
string
|
||||
);
|
||||
};
|
||||
key = colorSpecifier;
|
||||
};
|
||||
$imageFileName =
|
||||
{
|
||||
type = delegatedType;
|
||||
baseType = string;
|
||||
key = imageFileName;
|
||||
};
|
||||
$guiParameters =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"x" = integer;
|
||||
"y" = integer;
|
||||
"width" = positiveFloat;
|
||||
"height" = positiveFloat;
|
||||
"row_height" = positiveInteger;
|
||||
"alpha" = $floatZeroToOne;
|
||||
"background_rgba" = string;
|
||||
"title" = string;
|
||||
};
|
||||
allowOthers = NO;
|
||||
};
|
||||
};
|
||||
}
|
|
@ -0,0 +1,434 @@
|
|||
/* plistschema.plist
|
||||
|
||||
Schema for plist schemas. Oooh, meta.
|
||||
|
||||
Note: for clarity, quoted strings are used only for strings that will
|
||||
appear in the file being checked. This may cause problems under GNUstep.
|
||||
*/
|
||||
|
||||
{
|
||||
type = $rootTypeSpecifier;
|
||||
|
||||
$definitions =
|
||||
{
|
||||
$typeSpecifier =
|
||||
{
|
||||
type = oneOf;
|
||||
options =
|
||||
(
|
||||
$simpleTypeSpecifier,
|
||||
$macroInvocation,
|
||||
$stringTypeSpecifier,
|
||||
$arrayTypeSpecifier,
|
||||
$dictionaryTypeSpecifier,
|
||||
$numberTypeSpecifier,
|
||||
$positiveNumberTypeSpecifier,
|
||||
$parameterLessTypeSpecifier,
|
||||
$enumerationTypeSpecifier,
|
||||
$oneOfTypeSpecifier,
|
||||
$delegatedTypeSpecifier
|
||||
);
|
||||
};
|
||||
|
||||
$rootTypeSpecifier =
|
||||
{
|
||||
type = oneOf;
|
||||
options =
|
||||
(
|
||||
$simpleTypeSpecifier,
|
||||
$rootMacroInvocation,
|
||||
$stringTypeSpecifier,
|
||||
$numberTypeSpecifier,
|
||||
$positiveNumberTypeSpecifier,
|
||||
$parameterLessTypeSpecifier,
|
||||
$enumerationTypeSpecifier,
|
||||
$rootArrayTypeSpecifier,
|
||||
$rootDictionaryTypeSpecifier,
|
||||
$rootOneOfTypeSpecifier,
|
||||
$rootDelegatedTypeSpecifier
|
||||
);
|
||||
};
|
||||
|
||||
$simpleTypeSpecifier =
|
||||
{
|
||||
// Simple types that can be referred to by name with no parameters
|
||||
type = enumeration;
|
||||
values =
|
||||
(
|
||||
"string",
|
||||
"array",
|
||||
"dictionary",
|
||||
"integer",
|
||||
"positiveInteger",
|
||||
"float",
|
||||
"positiveFloat",
|
||||
"boolean",
|
||||
"fuzzyBoolean",
|
||||
"vector",
|
||||
"quaternion"
|
||||
// Not oneOf, enumeration or delegatedType
|
||||
);
|
||||
};
|
||||
|
||||
$macroInvocation =
|
||||
{
|
||||
type = oneOf;
|
||||
options =
|
||||
(
|
||||
$macroInvocationString,
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" = $macroInvocation;
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type" );
|
||||
}
|
||||
);
|
||||
};
|
||||
$macroInvocationString =
|
||||
{
|
||||
type = string;
|
||||
minLength = 2;
|
||||
requiredPrefix = "$";
|
||||
};
|
||||
|
||||
|
||||
$stringTypeSpecifier =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = enumeration;
|
||||
values = ( "string" );
|
||||
};
|
||||
|
||||
"filter" = $filterSpecifier;
|
||||
"requiredPrefix" = $stringOrStringArray;
|
||||
"requiredSuffix" = $stringOrStringArray;
|
||||
"requiredSubString" = $stringOrStringArray;
|
||||
"minLength" = positiveInteger;
|
||||
"maxLength" = positiveInteger;
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type" );
|
||||
};
|
||||
$arrayTypeSpecifier =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = enumeration;
|
||||
values = ( "array" );
|
||||
};
|
||||
|
||||
"minCount" = positiveInteger;
|
||||
"maxCount" = positiveInteger;
|
||||
"valueType" = $typeSpecifier;
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type" );
|
||||
};
|
||||
$dictionaryTypeSpecifier =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = enumeration;
|
||||
values = ( "dictionary" );
|
||||
};
|
||||
|
||||
"minCount" = positiveInteger;
|
||||
"maxCount" = positiveInteger;
|
||||
"valueType" = $typeSpecifier;
|
||||
"schema" =
|
||||
{
|
||||
type = dictionary;
|
||||
valueType = $typeSpecifier;
|
||||
};
|
||||
"allowOthers" = boolean;
|
||||
"requiredKeys" =
|
||||
{
|
||||
type = array;
|
||||
valueType = string;
|
||||
};
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type" );
|
||||
};
|
||||
$numberTypeSpecifier =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = enumeration;
|
||||
values =
|
||||
(
|
||||
"integer",
|
||||
"float"
|
||||
);
|
||||
};
|
||||
|
||||
"minimum" = integer;
|
||||
"maximum" = integer;
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type" );
|
||||
};
|
||||
$positiveNumberTypeSpecifier =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = enumeration;
|
||||
values =
|
||||
(
|
||||
"positiveInteger",
|
||||
"positiveFloat"
|
||||
);
|
||||
};
|
||||
|
||||
"minimum" = positiveInteger;
|
||||
"maximum" = positiveInteger;
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type" );
|
||||
};
|
||||
$parameterLessTypeSpecifier =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = enumeration;
|
||||
values =
|
||||
(
|
||||
"boolean",
|
||||
"fuzzyBoolean",
|
||||
"vector",
|
||||
"quaternion"
|
||||
);
|
||||
};
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type" );
|
||||
};
|
||||
$enumerationTypeSpecifier =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = enumeration;
|
||||
values = ( "enumeration" );
|
||||
};
|
||||
|
||||
"values" =
|
||||
{
|
||||
type = array;
|
||||
valueType = string;
|
||||
minCount = 1;
|
||||
};
|
||||
"filter" = $filterSpecifier;
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type", "values" );
|
||||
};
|
||||
$oneOfTypeSpecifier =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = enumeration;
|
||||
values = ( "oneOf" );
|
||||
};
|
||||
|
||||
"options" =
|
||||
{
|
||||
type = array;
|
||||
valueType = $typeSpecifier;
|
||||
minCount = 1;
|
||||
};
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type", "options" );
|
||||
};
|
||||
$delegatedTypeSpecifier =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = enumeration;
|
||||
values = ( "delegatedType" );
|
||||
};
|
||||
|
||||
"baseType" = $typeSpecifier;
|
||||
"key" = string;
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type", "key" );
|
||||
};
|
||||
|
||||
// "Root" variants of types which can have typeSpecifier arguments. These are the only types for which a $definitions entry is meaningful.
|
||||
$rootArrayTypeSpecifier =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = enumeration;
|
||||
values = ( "array" );
|
||||
};
|
||||
"$definitions" = $definitionsDictionary;
|
||||
|
||||
"minCount" = positiveInteger;
|
||||
"maxCount" = positiveInteger;
|
||||
"valueType" = $typeSpecifier;
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type" );
|
||||
};
|
||||
$rootDictionaryTypeSpecifier =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = enumeration;
|
||||
values = ( "dictionary") ;
|
||||
};
|
||||
"$definitions" = $definitionsDictionary;
|
||||
|
||||
"minCount" = positiveInteger;
|
||||
"maxCount" = positiveInteger;
|
||||
"valueType" = $typeSpecifier;
|
||||
"schema" =
|
||||
{
|
||||
type = dictionary;
|
||||
valueType = $typeSpecifier;
|
||||
};
|
||||
"allowOthers" = boolean;
|
||||
"requiredKeys" =
|
||||
{
|
||||
type = array;
|
||||
valueType = string;
|
||||
};
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type" );
|
||||
};
|
||||
$rootOneOfTypeSpecifier =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = enumeration;
|
||||
values = ( "oneOf" );
|
||||
};
|
||||
"$definitions" = $definitionsDictionary;
|
||||
|
||||
"options" =
|
||||
{
|
||||
type = array;
|
||||
valueType = $typeSpecifier;
|
||||
};
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type", "options" );
|
||||
};
|
||||
$rootDelegatedTypeSpecifier =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = enumeration;
|
||||
values = ( "delegatedType") ;
|
||||
};
|
||||
"$definitions" = $definitionsDictionary;
|
||||
|
||||
"baseType" = $typeSpecifier;
|
||||
"key" = string;
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type", "key" );
|
||||
};
|
||||
$rootMacroInvocation =
|
||||
{
|
||||
type = oneOf;
|
||||
options =
|
||||
(
|
||||
$macroInvocationString,
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"type" = $macroInvocation;
|
||||
"$definitions" = $definitionsDictionary;
|
||||
};
|
||||
allowOthers = NO;
|
||||
requiredKeys = ( "type" );
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
$stringOrStringArray =
|
||||
{
|
||||
type = oneOf;
|
||||
options =
|
||||
(
|
||||
string,
|
||||
{
|
||||
type = array;
|
||||
valueType = string;
|
||||
}
|
||||
);
|
||||
};
|
||||
$filterSpecifier =
|
||||
{
|
||||
type = enumeration;
|
||||
filter = subStringToInclusive::;
|
||||
values =
|
||||
(
|
||||
"lowerCase",
|
||||
"upperCase",
|
||||
"capitalized",
|
||||
"truncFront:",
|
||||
"truncBack:",
|
||||
"subStringTo:",
|
||||
"subStringFrom:",
|
||||
"subStringToInclusive:",
|
||||
"subStringFromInclusive:"
|
||||
);
|
||||
};
|
||||
$definitionsDictionary =
|
||||
{
|
||||
// NOTE: there is currently no way to apply string requirements (like requiredPrefix = "$") to dictionary keys.
|
||||
type = dictionary;
|
||||
valueType = $typeSpecifier;
|
||||
};
|
||||
};
|
||||
}
|
|
@ -0,0 +1,499 @@
|
|||
/* This is a schema for a single entry in a shipdata.plist file (not the file
|
||||
as a whole).
|
||||
*/
|
||||
|
||||
{
|
||||
type = "dictionary";
|
||||
requiredKeys = ( "model", "name", "roles" );
|
||||
schema =
|
||||
{
|
||||
is_template = "boolean";
|
||||
like_ship = "$shipRole";
|
||||
max_flight_speed = "positiveFloat";
|
||||
max_flight_roll = "positiveFloat";
|
||||
max_flight_pitch = "positiveFloat";
|
||||
max_flight_yaw = "positiveFloat";
|
||||
thrust = "positiveFloat";
|
||||
accuracy = "float";
|
||||
max_energy = "positiveFloat";
|
||||
energy_recharge_rate = "positiveFloat";
|
||||
forward_weapon_type = "$weaponType";
|
||||
aft_weapon_type = "$weaponType";
|
||||
weapon_energy = "positiveFloat";
|
||||
scanner_range = "positiveFloat";
|
||||
missiles = "positiveInteger";
|
||||
has_ecm = "fuzzyBoolean";
|
||||
has_scoop = "fuzzyBoolean";
|
||||
has_escape_pod = "positiveInteger";
|
||||
has_energy_bomb = "fuzzyBoolean";
|
||||
has_fuel_injection = "fuzzyBoolean";
|
||||
has_cloaking_device = "fuzzyBoolean";
|
||||
has_military_jammer = "fuzzyBoolean";
|
||||
has_military_scanner_filter = "fuzzyBoolean";
|
||||
fragment_chance = "fuzzyBoolean";
|
||||
has_shield_booster = "fuzzyBoolean";
|
||||
has_shield_enhancer = "fuzzyBoolean";
|
||||
fuel = "positiveInteger";
|
||||
bounty = "positiveInteger";
|
||||
ai_type = "$aiFileName";
|
||||
max_cargo = "positiveInteger";
|
||||
likely_cargo = "positiveInteger";
|
||||
extra_cargo = "positiveInteger";
|
||||
cargo_carried = "$cargoCarried";
|
||||
cargo_type = "$cargoType";
|
||||
model = "$modelName";
|
||||
materials = "$materialDict";
|
||||
shaders = "$materialDict";
|
||||
smooth = "boolean";
|
||||
density = "positiveFloat";
|
||||
name = "string";
|
||||
roles = "$roles";
|
||||
exhaust =
|
||||
{
|
||||
type = "array";
|
||||
valueType = "$exhaustSpecifier";
|
||||
};
|
||||
is_hulk = "boolean";
|
||||
subentities =
|
||||
{
|
||||
type = "array";
|
||||
valueType = "$subEntitySpecifier";
|
||||
};
|
||||
frangible = "boolean";
|
||||
laser_color = "$colorSpecifier";
|
||||
scanClass = "$scanClass";
|
||||
launch_actions = "$scriptActions";
|
||||
script_actions = "$scriptActions";
|
||||
death_actions = "$scriptActions";
|
||||
setup_actions = "$scriptActions";
|
||||
escorts = "positiveInteger";
|
||||
beacon = "string";
|
||||
rotational_velocity = "quaternion";
|
||||
track_contacts = "boolean";
|
||||
weapon_position_forward = "vector";
|
||||
weapon_position_aft = "vector";
|
||||
weapon_position_port = "vector";
|
||||
weapon_position_starboard = "vector";
|
||||
weapon_offset_x = "float"; // NOTE: ignored after 1.65
|
||||
scoop_position = "vector";
|
||||
heat_insulation = "positiveFloat";
|
||||
pilot = "$characterKey";
|
||||
unpiloted = "fuzzyBoolean";
|
||||
escort-role = "$shipRole";
|
||||
escort-ship = "$shipKey";
|
||||
missile_launch_position = "vector";
|
||||
missile_role = "$shipRole";
|
||||
escape_pod_model = "$shipRole";
|
||||
aft_eject_position = "vector";
|
||||
auto_ai = "boolean";
|
||||
rotating = "boolean";
|
||||
defense_ship = "$shipKey";
|
||||
defense_ship_role = "$shipRole";
|
||||
hasShipyard =
|
||||
{
|
||||
type = "oneOf";
|
||||
options =
|
||||
(
|
||||
"$scriptCondition",
|
||||
"boolean"
|
||||
);
|
||||
};
|
||||
conditions = "$scriptConditionList";
|
||||
port_radius = "positiveFloat";
|
||||
port_dimensions = "$portDimensions";
|
||||
equivalent_tech_level = "integer";
|
||||
max_scavengers = "positiveInteger";
|
||||
max_defense_ships = "positiveInteger";
|
||||
max_police = "positiveInteger";
|
||||
equipment_price_factor = "positiveFloat";
|
||||
extra_equipment = "$extraEquipmentDictionary";
|
||||
hud = "$hudFileName";
|
||||
view_position_forward = "vector";
|
||||
view_position_aft = "vector";
|
||||
view_position_port = "vector";
|
||||
view_position_starboard = "vector";
|
||||
custom_views =
|
||||
{
|
||||
type = "array";
|
||||
valueType = "$customViewSpec";
|
||||
};
|
||||
max_missiles = "positiveInteger";
|
||||
script = "$scriptFileName";
|
||||
has_npc_traffic = "fuzzyBoolean";
|
||||
script_info = "dictionary";
|
||||
is_submunition = "boolean";
|
||||
isCarrier = "boolean";
|
||||
no_boulders = "fuzzyBoolean";
|
||||
hyperspace_motor_spin_time = "positiveFloat";
|
||||
requires_docking_clearance = "boolean";
|
||||
};
|
||||
$definitions =
|
||||
{
|
||||
// "Special" types referred to above.
|
||||
$weaponType =
|
||||
{
|
||||
type = "enumeration";
|
||||
values =
|
||||
(
|
||||
"WEAPON_NONE",
|
||||
"WEAPON_PLASMA_CANNON",
|
||||
"WEAPON_PULSE_LASER",
|
||||
"WEAPON_BEAM_LASER",
|
||||
"WEAPON_MINING_LASER",
|
||||
"WEAPON_MILITARY_LASER",
|
||||
"WEAPON_THARGOID_LASER"
|
||||
);
|
||||
};
|
||||
$materialDict =
|
||||
{
|
||||
type = "dictionary";
|
||||
schema =
|
||||
{
|
||||
ambient = "$colorSpecifier";
|
||||
diffuse = "$colorSpecifier";
|
||||
diffuse_map = "$textureSpecifier";
|
||||
emission = "$colorSpecifier";
|
||||
shininess =
|
||||
{
|
||||
type = "positiveInteger";
|
||||
maximum = "128";
|
||||
};
|
||||
specular = "$colorSpecifier";
|
||||
fragment_shader = "$shaderFileName";
|
||||
textures =
|
||||
{
|
||||
type = "array";
|
||||
valueType = "$textureSpecifier";
|
||||
};
|
||||
uniforms =
|
||||
{
|
||||
type = "dictionary";
|
||||
valueType =
|
||||
{
|
||||
type = "oneOf";
|
||||
options =
|
||||
(
|
||||
"string",
|
||||
{
|
||||
type = "dictionary";
|
||||
schema =
|
||||
{
|
||||
asMatrix = "boolean";
|
||||
binding = "string";
|
||||
clamped = "boolean";
|
||||
normalized = "boolean";
|
||||
type =
|
||||
{
|
||||
type = "enumeration";
|
||||
values =
|
||||
(
|
||||
"binding",
|
||||
"float",
|
||||
"real",
|
||||
"int",
|
||||
"integer",
|
||||
"texture"
|
||||
);
|
||||
};
|
||||
value = "float";
|
||||
};
|
||||
}
|
||||
);
|
||||
};
|
||||
};
|
||||
vertex_shader = "$shaderFileName";
|
||||
};
|
||||
};
|
||||
$textureSpecifier =
|
||||
{
|
||||
type = "oneOf";
|
||||
options =
|
||||
(
|
||||
"string",
|
||||
{
|
||||
type = "dictionary";
|
||||
schema =
|
||||
{
|
||||
anisotropy = "positiveFloat";
|
||||
mag_filter =
|
||||
{
|
||||
type = "enumeration";
|
||||
values =
|
||||
(
|
||||
"nearest",
|
||||
"linear"
|
||||
);
|
||||
};
|
||||
min_filter =
|
||||
{
|
||||
type = "enumeration";
|
||||
values =
|
||||
(
|
||||
"nearest",
|
||||
"linear",
|
||||
"mipmap",
|
||||
"default"
|
||||
);
|
||||
};
|
||||
name = "string";
|
||||
no_shrink = "boolean";
|
||||
repeat_s = "boolean";
|
||||
repeat_t = "boolean";
|
||||
texture_LOD_bias = "float";
|
||||
};
|
||||
}
|
||||
);
|
||||
};
|
||||
$scanClass =
|
||||
{
|
||||
type = "enumeration";
|
||||
values =
|
||||
(
|
||||
"CLASS_NOT_SET",
|
||||
"CLASS_BUOY",
|
||||
"CLASS_CARGO",
|
||||
"CLASS_MILITARY",
|
||||
"CLASS_MISSILE",
|
||||
"CLASS_POLICE",
|
||||
"CLASS_ROCK",
|
||||
"CLASS_STATION",
|
||||
"CLASS_THARGOID"
|
||||
);
|
||||
};
|
||||
$cargoType =
|
||||
{
|
||||
type = "enumeration";
|
||||
values =
|
||||
(
|
||||
"CARGO_NOT_CARGO",
|
||||
"CARGO_SLAVES",
|
||||
"CARGO_ALLOY",
|
||||
"CARGO_MINERALS",
|
||||
"CARGO_THARGOID",
|
||||
"CARGO_RANDOM",
|
||||
"CARGO_CARRIED",
|
||||
"CARGO_SCRIPTED_ITEM",
|
||||
"CARGO_CHARACTER"
|
||||
);
|
||||
};
|
||||
$customViewSpec =
|
||||
{
|
||||
type = "dictionary";
|
||||
schema =
|
||||
{
|
||||
"view_description" = "string";
|
||||
"view_position" = "vector";
|
||||
"view_orientation" = "quaternion";
|
||||
"weapon_facing" =
|
||||
{
|
||||
type = "enumeration";
|
||||
filter = "lowerCase";
|
||||
values =
|
||||
(
|
||||
"forward",
|
||||
"aft",
|
||||
"port",
|
||||
"starboard"
|
||||
);
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
// Types handled in code.
|
||||
$modelName =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType =
|
||||
{
|
||||
type = "string";
|
||||
filter = "lowerCase";
|
||||
requiredSuffix = ".dat";
|
||||
};
|
||||
key = "modelName";
|
||||
};
|
||||
$colorSpecifier =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType =
|
||||
{
|
||||
type = "oneOf";
|
||||
options =
|
||||
(
|
||||
"array",
|
||||
"dictionary",
|
||||
"string"
|
||||
);
|
||||
};
|
||||
key = "colorSpecifier";
|
||||
};
|
||||
$textureFileName =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType =
|
||||
{
|
||||
type = "string";
|
||||
filter = "lowerCase";
|
||||
requiredSuffix = ".png";
|
||||
};
|
||||
key = "textureFileName";
|
||||
};
|
||||
$aiFileName =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType =
|
||||
{
|
||||
type = "string";
|
||||
filter = "lowerCase";
|
||||
requiredSuffix = ".plist";
|
||||
};
|
||||
key = "aiFileName";
|
||||
};
|
||||
$shaderFileName =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType =
|
||||
{
|
||||
type = "string";
|
||||
filter = "lowerCase";
|
||||
requiredSuffix =
|
||||
(
|
||||
".vertex",
|
||||
".vert",
|
||||
".fragment",
|
||||
".frag"
|
||||
);
|
||||
};
|
||||
key = "shaderFileName";
|
||||
};
|
||||
$exhaustSpecifier =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "string";
|
||||
key = "exhaustSpecifier";
|
||||
};
|
||||
$subEntitySpecifier =
|
||||
{
|
||||
type = "oneOf";
|
||||
options =
|
||||
(
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "string";
|
||||
key = "subEntitySpecifier";
|
||||
},
|
||||
{
|
||||
type = "dictionary";
|
||||
requiredKeys = ( "type", "subentity_key" );
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = "enumeration";
|
||||
values = ( "standard", "ball_turret" );
|
||||
};
|
||||
subentity_key = "$shipKey";
|
||||
position = "vector";
|
||||
orientation = "quaternion";
|
||||
is_dock = "boolean";
|
||||
};
|
||||
},
|
||||
{
|
||||
type = "dictionary";
|
||||
requiredKeys = ( "type" );
|
||||
schema =
|
||||
{
|
||||
"type" =
|
||||
{
|
||||
type = "enumeration";
|
||||
values = ( "flasher" );
|
||||
};
|
||||
color = "$colorSpecifier";
|
||||
colors =
|
||||
{
|
||||
type = array;
|
||||
valueType = "$colorSpecifier";
|
||||
};
|
||||
position = "vector";
|
||||
orientation = "quaternion";
|
||||
size = "positiveFloat";
|
||||
frequency = "float";
|
||||
phase = "float";
|
||||
initially_on = "boolean";
|
||||
};
|
||||
}
|
||||
);
|
||||
};
|
||||
$scriptActions =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "array";
|
||||
key = "scriptActions";
|
||||
};
|
||||
$characterKey =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "string";
|
||||
key = "characterKey";
|
||||
};
|
||||
$shipRole =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "string";
|
||||
key = "shipRole";
|
||||
};
|
||||
$shipKey =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "string";
|
||||
key = "shipKey";
|
||||
};
|
||||
$roles =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "string";
|
||||
key = "roles";
|
||||
};
|
||||
$scriptCondition =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "string";
|
||||
key = "scriptCondition";
|
||||
};
|
||||
$scriptConditionList =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "array";
|
||||
key = "scriptConditions";
|
||||
};
|
||||
$portDimensions =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "string";
|
||||
key = "portDimensions";
|
||||
};
|
||||
$extraEquipmentDictionary =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "dictionary";
|
||||
key = "extraEquipmentDictionary";
|
||||
};
|
||||
$hudFileName =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "string";
|
||||
key = "hudFileName";
|
||||
};
|
||||
$cargoCarried =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "string";
|
||||
key = "cargoCarried";
|
||||
};
|
||||
$scriptFileName =
|
||||
{
|
||||
type = "delegatedType";
|
||||
baseType = "string";
|
||||
key = "$scriptFileName";
|
||||
};
|
||||
};
|
||||
}
|
|
@ -0,0 +1,73 @@
|
|||
/*
|
||||
Schema for shipyard.plist.
|
||||
*/
|
||||
|
||||
{
|
||||
type = dictionary;
|
||||
valueType =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"chance" = float;
|
||||
"optional_equipment" = $equipmentKeyArray;
|
||||
"price" = positiveInteger;
|
||||
"standard_equipment" =
|
||||
{
|
||||
type = dictionary;
|
||||
schema =
|
||||
{
|
||||
"forward_weapon_type" = $weaponType;
|
||||
"extras" = $equipmentKeyArray;
|
||||
"missiles" = positiveInteger;
|
||||
};
|
||||
allowOthers = NO;
|
||||
};
|
||||
techLevel =
|
||||
{
|
||||
type = positiveInteger;
|
||||
maximum = 99; // Normally 0..13, but 99 is special.
|
||||
};
|
||||
weaponFacings =
|
||||
{
|
||||
type = positiveInteger;
|
||||
maximum = 15;
|
||||
};
|
||||
"conditions" = $scriptConditions;
|
||||
"max_cargo" = positiveInteger;
|
||||
};
|
||||
};
|
||||
$definitions =
|
||||
{
|
||||
$equipmentKey =
|
||||
{
|
||||
type = string;
|
||||
requiredPrefix = "EQ_";
|
||||
};
|
||||
$equipmentKeyArray =
|
||||
{
|
||||
type = array;
|
||||
valueType = $equipmentKey;
|
||||
};
|
||||
$weaponType =
|
||||
{
|
||||
type = enumeration;
|
||||
values =
|
||||
(
|
||||
"EQ_WEAPON_NONE",
|
||||
// "EQ_WEAPON_PLASMA_CANNON", // Currently not supported in code.
|
||||
"EQ_WEAPON_PULSE_LASER",
|
||||
"EQ_WEAPON_BEAM_LASER",
|
||||
"EQ_WEAPON_MINING_LASER",
|
||||
"EQ_WEAPON_MILITARY_LASER",
|
||||
"EQ_WEAPON_THARGOID_LASER"
|
||||
);
|
||||
};
|
||||
$scriptConditions =
|
||||
{
|
||||
type = delegatedType;
|
||||
baseType = array;
|
||||
key = scriptConditions;
|
||||
};
|
||||
};
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# Quick and dirty patching script.
|
||||
# Copyright (C) 2007 Chris Crowther <hikari@hikari.org.uk>
|
||||
#
|
||||
# Additional Changes: Michael Werle <micha@michaelwerle.com>
|
||||
#
|
||||
# History:
|
||||
# 2008.11.02 MKW Auto-read all patches from patch directory
|
||||
#
|
||||
# $Id$
|
||||
#
|
||||
PATCHES=`ls -1 debian/patches`
|
||||
FLAGS=""
|
||||
|
||||
while getopts ":R" option
|
||||
do
|
||||
case $option in
|
||||
R)
|
||||
if test -f patch; then
|
||||
echo "Patches have been applied: reversing."
|
||||
export FLAGS="$FLAGS -R";
|
||||
else
|
||||
echo "Patches have not been applied: not reversing."
|
||||
exit 0;
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
echo "Using patch flags: $FLAGS"
|
||||
|
||||
for PATCH in $PATCHES; do
|
||||
patch $FLAGS -p0 < debian/patches/$PATCH
|
||||
done;
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
oolite (1.73) unstable; urgency=low
|
||||
|
||||
*
|
||||
|
||||
-- Michael Werle <micha@michaelwerle.com> Fri, 07 Nov 2008 01:00:00 +0100
|
||||
|
||||
oolite (1.72.1-1) testing; urgency=low
|
||||
|
||||
* Fixed crash-bug with no sound-device.
|
||||
* Fixed some compiler warnings.
|
||||
* Tweaks to build rules.
|
||||
|
||||
-- Michael Werle <micha@michaelwerle.com> Wed, 05 Nov 2008 07:14:00 +0100
|
||||
|
||||
oolite (1.72~svn-1) testing; urgency=low
|
||||
|
||||
* Many build changes...
|
||||
* Build-depend on debhelper.
|
||||
* Build using internal libjs; oolite doesn't like libmozjs :-\
|
||||
(New patch 02_libjs_linkage: we want the static lib.)
|
||||
* Updated patch 01_oolite.desktop to point at the "correct" image.
|
||||
* Imported oolite.menu, oolite.6 & oolite-logo1.xpm into debian/ from
|
||||
1.65-6 (in Debian lenny).
|
||||
* Don't include SVN directories in the .debs.
|
||||
* Clean up properly after building.
|
||||
|
||||
-- Darren Salt <linux@youmustbejoking.demon.co.uk> Fri, 04 Jul 2008 15:00:02 +0100
|
||||
|
||||
oolite (1.69-1) testing; urgency=low
|
||||
|
||||
* Initial creation of debian build rules.
|
||||
* Fixed missing libpng and libmozjs hooks for the Linux build.
|
||||
|
||||
-- Chris Crowther <hikari@hikari.org.uk> Mon, 11 Jun 2007 10:50:06 +0100
|
||||
|
|
@ -0,0 +1 @@
|
|||
5
|
|
@ -0,0 +1,37 @@
|
|||
Source: oolite
|
||||
Section: games
|
||||
Priority: optional
|
||||
Maintainer: Chris Crowther <hikari@hikari.org.uk>
|
||||
Standards-Version: 3.7.2
|
||||
Build-Depends: debhelper (>= 5),
|
||||
libsdl1.2-dev, libsdl-mixer1.2-dev, libespeak-dev,
|
||||
libgnustep-base-dev, gnustep-core-devel,
|
||||
libpng-dev, mesa-common-dev
|
||||
Homepage: http://oolite.org/
|
||||
Vcs-Svn: svn://svn.berlios.de/oolite-linux
|
||||
Vcs-Browser: http://svn.berlios.de/wsvn/oolite-linux
|
||||
|
||||
Package: oolite
|
||||
Architecture: any
|
||||
Depends: ${shlibs:Depends}, oolite-data (>= ${source:Version})
|
||||
Description: space sim game, inspired by Elite
|
||||
Oolite is a space sim game, inspired by Elite, powered by Objective-C
|
||||
and OpenGL, and designed as a small game that is easy for users to pick
|
||||
up, modify and expand upon. Almost every aspect of the game can be changed
|
||||
by using simple, free graphics packages and text-editors.
|
||||
.
|
||||
Originally written for Mac OS X, and under continuous development for over
|
||||
three years. Oolite is available for Mac OS X (10.3.9 and higher), Windows XP
|
||||
and Linux. It requires at least a 400MHz processor, 256Mb of memory, and a
|
||||
graphics card capable of accelerating OpenGL graphics.
|
||||
|
||||
Package: oolite-data
|
||||
Architecture: all
|
||||
Recommends: oolite (>= ${source:Version})
|
||||
Description: space sim game, inspired by Elite (data files)
|
||||
Oolite is a space sim game, inspired by Elite, powered by Objective-C
|
||||
and OpenGL, and designed as a small game that is easy for users to pick
|
||||
up, modify and expand upon. Almost every aspect of the game can be changed
|
||||
by using simple, free graphics packages and text-editors.
|
||||
.
|
||||
This package contains the data files for the game.
|
|
@ -0,0 +1,6 @@
|
|||
This package was debianized by Chris Crowther <hikari@hikari.org.uk> on
|
||||
Mon, 11 Jun 2007 10:50:06 +0100
|
||||
|
||||
Copyright Holder: Giles Williams and the Oolite project.
|
||||
|
||||
License: GNU GPL v2 or later, see /usr/share/common-licenses/GPL-2
|
|
@ -0,0 +1,2 @@
|
|||
#!/bin/sh
|
||||
openapp oolite &
|
|
@ -0,0 +1 @@
|
|||
usr/lib/GNUstep/Applications/oolite.app
|
|
@ -0,0 +1,7 @@
|
|||
Doc/FAQ.TXT
|
||||
Doc/PORTING.TXT
|
||||
Doc/README_LINUX.TXT
|
||||
Doc/ReadMe.rtfd/TXT.rtf
|
||||
oolite.*/Resources/README.TXT
|
||||
deps/Linux-x86-deps/PLAYING.TXT
|
||||
installers/win32/OoliteRS.pdf
|
|
@ -0,0 +1 @@
|
|||
oolite.app/Resources usr/lib/GNUstep/Applications/oolite.app
|
|
@ -0,0 +1,219 @@
|
|||
/* XPM */
|
||||
static char *oolite-logo1[] = {
|
||||
/* columns rows colors chars-per-pixel */
|
||||
"32 32 181 2",
|
||||
" c #000000",
|
||||
". c #050609",
|
||||
"X c #030906",
|
||||
"o c #050A09",
|
||||
"O c #0A070F",
|
||||
"+ c #080E0A",
|
||||
"@ c #080A17",
|
||||
"# c #0B0A1C",
|
||||
"$ c #0A110B",
|
||||
"% c #0A1213",
|
||||
"& c #0B111A",
|
||||
"* c #0D1B13",
|
||||
"= c #0A1A1B",
|
||||
"- c #1F1F1F",
|
||||
"; c #0F0920",
|
||||
": c #0C1C20",
|
||||
"> c #121120",
|
||||
", c #181735",
|
||||
"< c #18183F",
|
||||
"1 c #0D2016",
|
||||
"2 c #112517",
|
||||
"3 c #133317",
|
||||
"4 c #15351F",
|
||||
"5 c #0E2A23",
|
||||
"6 c #0D2B29",
|
||||
"7 c #102027",
|
||||
"8 c #112B25",
|
||||
"9 c #16292B",
|
||||
"0 c #162134",
|
||||
"q c #162C35",
|
||||
"w c #1D3B28",
|
||||
"e c #153331",
|
||||
"r c #123935",
|
||||
"t c #193140",
|
||||
"y c #271B4A",
|
||||
"u c #252D5A",
|
||||
"i c #31245A",
|
||||
"p c #3E2C73",
|
||||
"a c #343F7E",
|
||||
"s c #1D4B2A",
|
||||
"d c #1F4D35",
|
||||
"f c #204C25",
|
||||
"g c #21482D",
|
||||
"h c #245B2C",
|
||||
"j c #21543A",
|
||||
"k c #28622F",
|
||||
"l c #256034",
|
||||
"z c #2B6936",
|
||||
"x c #2C6C3B",
|
||||
"c c #2F7335",
|
||||
"v c #1F4B4E",
|
||||
"b c #1F4451",
|
||||
"n c #224D4F",
|
||||
"m c #25435A",
|
||||
"M c #205446",
|
||||
"N c #255E4B",
|
||||
"B c #245557",
|
||||
"V c #245E56",
|
||||
"C c #234466",
|
||||
"Z c #284C63",
|
||||
"A c #2B4074",
|
||||
"S c #335D7F",
|
||||
"D c #286645",
|
||||
"F c #2C604A",
|
||||
"G c #2A6A47",
|
||||
"H c #2A6B4A",
|
||||
"J c #29695E",
|
||||
"K c #2D7341",
|
||||
"L c #326352",
|
||||
"P c #326B56",
|
||||
"I c #376E5B",
|
||||
"U c #307943",
|
||||
"Y c #307B54",
|
||||
"T c #39725F",
|
||||
"R c #276F68",
|
||||
"E c #2C6272",
|
||||
"W c #2D6F73",
|
||||
"Q c #3D7C67",
|
||||
"! c #347877",
|
||||
"~ c #33787C",
|
||||
"^ c #397E7E",
|
||||
"/ c #412E7B",
|
||||
"( c #3F5FAA",
|
||||
") c #37699B",
|
||||
"_ c #41488E",
|
||||
"` c #4942A6",
|
||||
"' c #4E59B1",
|
||||
"] c #467C9D",
|
||||
"[ c #4263A5",
|
||||
"{ c #4469A2",
|
||||
"} c #476CA8",
|
||||
"| c #564EC2",
|
||||
" . c #5B50C4",
|
||||
".. c #4D73C2",
|
||||
"X. c #5565D8",
|
||||
"o. c #5969E2",
|
||||
"O. c #675BDE",
|
||||
"+. c #35833B",
|
||||
"@. c #368A3D",
|
||||
"#. c #368441",
|
||||
"$. c #32844E",
|
||||
"%. c #3D9A44",
|
||||
"&. c #3D9C58",
|
||||
"*. c #36886C",
|
||||
"=. c #3F8868",
|
||||
"-. c #399060",
|
||||
";. c #3C9D6C",
|
||||
":. c #3FA05B",
|
||||
">. c #3FA860",
|
||||
",. c #438B5C",
|
||||
"<. c #409F4C",
|
||||
"1. c #47935F",
|
||||
"2. c #48945F",
|
||||
"3. c #418F74",
|
||||
"4. c #479361",
|
||||
"5. c #489460",
|
||||
"6. c #47967A",
|
||||
"7. c #48967A",
|
||||
"8. c #41A249",
|
||||
"9. c #46A85D",
|
||||
"0. c #4ABC67",
|
||||
"q. c #4ABC7E",
|
||||
"w. c #4DC165",
|
||||
"e. c #4EC268",
|
||||
"r. c #4FD077",
|
||||
"t. c #56D669",
|
||||
"y. c #56D861",
|
||||
"u. c #55D777",
|
||||
"i. c #53D27A",
|
||||
"p. c #57D975",
|
||||
"a. c #59E37E",
|
||||
"s. c #3C849A",
|
||||
"d. c #3A9586",
|
||||
"f. c #399488",
|
||||
"g. c #3C9196",
|
||||
"h. c #418F9A",
|
||||
"j. c #499E80",
|
||||
"k. c #428AA5",
|
||||
"l. c #4C84A6",
|
||||
"z. c #4B85A8",
|
||||
"x. c #41A281",
|
||||
"c. c #42A598",
|
||||
"v. c #4AB681",
|
||||
"b. c #4AB495",
|
||||
"n. c #53B291",
|
||||
"m. c #48A6AD",
|
||||
"M. c #4CADBA",
|
||||
"N. c #5598D7",
|
||||
"B. c #5A86E5",
|
||||
"V. c #599FE2",
|
||||
"C. c #4DA1C2",
|
||||
"Z. c #5BB1D6",
|
||||
"A. c #5BA1E6",
|
||||
"S. c #5BBCE5",
|
||||
"D. c #4EC98A",
|
||||
"F. c #55D891",
|
||||
"G. c #57DD98",
|
||||
"H. c #5BD899",
|
||||
"J. c #4DC1B3",
|
||||
"K. c #54CBA7",
|
||||
"L. c #53D3AD",
|
||||
"P. c #5DDEA2",
|
||||
"I. c #52DAB5",
|
||||
"U. c #5AE483",
|
||||
"Y. c #58E097",
|
||||
"T. c #5BE69C",
|
||||
"R. c #5BE5A2",
|
||||
"E. c #5AE5BC",
|
||||
"W. c #65DFB4",
|
||||
"Q. c #66E2B5",
|
||||
"!. c #68E6B9",
|
||||
"~. c #55CCD7",
|
||||
"^. c #53DACE",
|
||||
"/. c #5AD7E4",
|
||||
"(. c #5BD8E6",
|
||||
"). c #5AE5D6",
|
||||
"_. c #5AE5D8",
|
||||
"`. c #DFDFDF",
|
||||
"'. c #E3E3E3",
|
||||
"]. c gray100",
|
||||
"[. c None",
|
||||
/* pixels */
|
||||
"[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.",
|
||||
"[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.",
|
||||
"[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.",
|
||||
"- [.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[. ",
|
||||
"- p . [.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[. i ; ",
|
||||
"- .| , [.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[. # ` O.# ",
|
||||
"- . _ o.a . [.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[. u X.' & ",
|
||||
"[. A B...0 [.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[. & [ B.[ [.",
|
||||
"[.[.[.C A.A.V._ X [.[.[.[.[.[.[.[.[.[.[.[. m N.A.A.) [.[.",
|
||||
"[.[. q Z.S.S.S.M.e [.[.[. [.[.[. = k.S.S.S.S.Z [.[.",
|
||||
"[.[.[. % h.(.(.(./.~ . [.X g.m.= [. B ~.(.(.(.M.9 [.[.",
|
||||
"[.[.[.[. ^._.).).).J.e r ).).R = c._._._._._.6 [.[.[.[.",
|
||||
"[.[.[.[.[. I.E.E.E.E.E.M o b.K.5 8 L.E.E.E.E.E.5 [.[.[.[.[.",
|
||||
"[.[.[.[.[. N P.R.R.R.D.X * * X ;.R.R.R.R.=.X [.[.[.[.[.",
|
||||
"[.[.[.[.[.[. 2 ,.5.5.5.g >.r.+ 2 5.5.4.4.w [.[.[.[.[.",
|
||||
"[.[.[.[. $ $ $ $ $ $ $ $ $ 3 h $ $ $ $ $ $ $ $ $ + [.[.[.[.",
|
||||
"[.[.[. x w.w.z x t.8.z #.8.%.@.y.c k f #.h x x u.9.4 [.[.",
|
||||
"[.[.[. X $.G U.i.K G U.&.h 0.a.u.U a.x U.s &.&.U.8 X [.[.",
|
||||
"[.[.[. d H.G G.D.Y H T.&.D q.T.F.Y Y.G T.j v.v.R.v.* [.[.",
|
||||
"[.[.[.[. * 3.T Q W.n.I 7.x.N D *.6.Q.7.!.L P L P [.[.[.[.",
|
||||
"[.[.[.[.[.[. X X X V f.R f.X . X [.[.[.[.[.",
|
||||
"[.[.[.[.[.[.[.[. : n v v ^ W g.! n v v e [.[.[.[.[.[.[.[.",
|
||||
"[.[.[.[.[.[.[.[.[. . O 7 s.E b . o [.[.[.[.[.[.[.[.[.",
|
||||
"[.[.[.[.[.[.[.[.[.[.[. : ] z.Z S ] l.q [.[.[.[.[.[.[.[.[.[.",
|
||||
"[.[.[.[.[.[.[.[.[.[.[.[. } { & [.[.[.[.[.[.[.[.[.[.[.[.",
|
||||
"[.[.[.[.[.[.[.[.[.[.[.[.[. @ [.[.[.[.[.[.[.[.[.[.[.[.[.",
|
||||
"[.[.[.[.[.[.[.[.[.[.[.[.[.[. # < [.[.[.[.[.[.[.[.[.[.[.[.[.[.",
|
||||
"[.[.[.[.[.[.[.[.[.[.[.[.[.[. y / [.[.[.[.[.[.[.[.[.[.[.[.[.[.",
|
||||
"[.[.[.[.[.[.[.[.[.[.[.[.[.[. O > [.[.[.[.[.[.[.[.[.[.[.[.[.[.",
|
||||
"[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.`.`.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.",
|
||||
"[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.",
|
||||
"[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[."
|
||||
};
|
|
@ -0,0 +1,79 @@
|
|||
.\" Hey, EMACS: -*- nroff -*-
|
||||
.\" First parameter, NAME, should be all caps
|
||||
.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
|
||||
.\" other parameters are allowed: see man(7), man(1)
|
||||
.TH OOLITE 6 "April 9th, 2006"
|
||||
.\" Please adjust this date whenever revising the manpage.
|
||||
.\"
|
||||
.\" Some roff macros, for reference:
|
||||
.\" .nh disable hyphenation
|
||||
.\" .hy enable hyphenation
|
||||
.\" .ad l left justify
|
||||
.\" .ad b justify to both left and right margins
|
||||
.\" .nf disable filling
|
||||
.\" .fi enable filling
|
||||
.\" .br insert line break
|
||||
.\" .sp <n> insert n+1 empty lines
|
||||
.\" for manpage-specific macros, see man(7)
|
||||
.de URL
|
||||
\\$2 \(laURL: \\$1 \(ra\\$3
|
||||
..
|
||||
.if \n[.g] .mso www.tmac
|
||||
|
||||
.SH NAME
|
||||
Oolite \- a space-sim game
|
||||
.SH SYNOPSIS
|
||||
.B oolite
|
||||
.br
|
||||
.SH DESCRIPTION
|
||||
This manual page documents briefly the
|
||||
.B Oolite.
|
||||
.PP
|
||||
\fBOolite\fP is a port of the space-sim game Oolite to the GNUStep/OpenGL linux platform.
|
||||
.br 2
|
||||
.SH FAQ
|
||||
.PP
|
||||
.B What is the purpose of the game?
|
||||
.br
|
||||
To fly from planet to planet, buying and selling goods, shooting pirates or committing acts
|
||||
of piracy. There's no goal other than perhaps to achieve the rank of
|
||||
.B ELITE.
|
||||
.br
|
||||
.PP
|
||||
.B I'm still confused, how do I play?
|
||||
.br
|
||||
Have a look at Ian Bell's Flight Training Manual for the original BBC Elite,
|
||||
some of Oolite's control keys are different from the original, so be sure to
|
||||
read it alongside the Oolite PLAYING.TXT file.
|
||||
.PP
|
||||
.TP
|
||||
.B What do the various colors represent on the radar?
|
||||
.br
|
||||
\(bu White - unpowered items that can't mass-lock the in-system drive.
|
||||
.br
|
||||
\(bu Green/Yellow - navigation buoys.
|
||||
.br
|
||||
\(bu Yellow - powered craft.
|
||||
.br
|
||||
\(bu Red - powered craft identified as hostile.
|
||||
.br
|
||||
\(bu Green - space stations.
|
||||
.br
|
||||
\(bu Green/Red - thargoids
|
||||
.br
|
||||
\(bu Purple - police
|
||||
.br
|
||||
\(bu Blue/Red - police on intercept
|
||||
.br
|
||||
\(bu Red/Yellow - active mine (about to detonate)
|
||||
.br
|
||||
.mso www.tmac
|
||||
.SH AUTHOR
|
||||
Oolite was written by Giles Williams and other, and it was ported to the GNU/Linux operating
|
||||
system by the
|
||||
.URL "http://oolite-linux.berlios.de/" "Oolite Linux" " project."
|
||||
The original version can be found at
|
||||
.URL http://oolite.aegidian.org/ "the Oolite home page" "."
|
||||
.PP
|
||||
This manual page was written by Eddy Petrisor <eddy.petrisor@gmail.com>,
|
||||
for the Debian project (but may be used by others).
|
|
@ -0,0 +1,4 @@
|
|||
usr/games
|
||||
usr/share/icons
|
||||
usr/lib/GNUstep/Applications/oolite.app
|
||||
usr/lib/GNUstep/Library/DTDs
|
|
@ -0,0 +1,7 @@
|
|||
oolite.app/oolite usr/lib/GNUstep/Applications/oolite.app
|
||||
oolite.app/Resources/Info-gnustep.plist usr/lib/GNUstep/Applications/oolite.app/Resources
|
||||
deps/Cross-platform-deps/DTDs usr/lib/GNUstep/Library
|
||||
debian/extra/games/oolite /usr/games
|
||||
FreeDesktop/oolite.desktop usr/share/applications
|
||||
FreeDesktop/oolite-icon.png usr/share/icons
|
||||
debian/oolite-logo1.xpm usr/share/pixmaps
|
|
@ -0,0 +1,3 @@
|
|||
usr/lib/GNUstep/Applications/oolite.app/Resources/Textures/oolite-logo.png usr/share/pixmaps/oolite-logo.png
|
||||
usr/lib/GNUstep/Applications/oolite.app/Resources/Textures/oolite-logo1.png usr/share/pixmaps/oolite-logo1.png
|
||||
usr/share/doc/oolite-data usr/share/doc/oolite
|
|
@ -0,0 +1,5 @@
|
|||
?package(oolite):needs="X11" section="Games/Simulation" \
|
||||
longtitle="Oolite - space-sim game" \
|
||||
title="Oolite" command="/usr/games/oolite" \
|
||||
icon="/usr/share/pixmaps/oolite-logo1.xpm" \
|
||||
hints="Flight,GNUstep"
|
|
@ -0,0 +1,103 @@
|
|||
#!/usr/bin/make -f
|
||||
#
|
||||
# Ubuntu/Debian build rules file for OOlite
|
||||
# Copyright (c) 2007 Chris Crowther <hikari@hikari.org.uk>
|
||||
#
|
||||
# Originally based on the exemplar hello project.
|
||||
#
|
||||
# Re-written by Darren Salt
|
||||
# Tweaked by Michael Werle
|
||||
|
||||
GSMAKE = gs_make
|
||||
JS_SRC = deps/Cross-platform-deps/SpiderMonkey/js/src
|
||||
|
||||
CFLAGS += -g
|
||||
ifeq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
|
||||
CFLAGS += -O2
|
||||
GSMAKE += debug=no
|
||||
override EXT =
|
||||
else
|
||||
CFLAGS += -O0
|
||||
GSMAKE += debug=yes
|
||||
override EXT = .dbg
|
||||
endif
|
||||
export CFLAGS
|
||||
|
||||
export GNUSTEP_INSTALLATION_DOMAIN = SYSTEM
|
||||
|
||||
patch:
|
||||
debian/apply-patches
|
||||
touch patch
|
||||
|
||||
unpatch:
|
||||
debian/apply-patches -R
|
||||
rm -f patch
|
||||
|
||||
build: patch build-stamp
|
||||
build-stamp:
|
||||
dh_testdir
|
||||
$(MAKE) -C $(JS_SRC)/fdlibm -f Makefile.ref BUILD_OPT=1
|
||||
$(MAKE) -C $(JS_SRC) -f Makefile.ref BUILD_OPT=1
|
||||
$(GSMAKE) libespeak=yes
|
||||
touch $@
|
||||
|
||||
clean: clean-stamp unpatch
|
||||
clean-stamp:
|
||||
dh_testdir
|
||||
rm -f build-stamp
|
||||
$(GSMAKE) clean
|
||||
$(MAKE) -C $(JS_SRC)/fdlibm -f Makefile.ref clean
|
||||
$(MAKE) -C $(JS_SRC) -f Makefile.ref clean
|
||||
rm -rf oolite.app oolite.debug
|
||||
rm -f http+_www.apple.com_DTDs_PropertyList-1.0.dtd
|
||||
find $(JS_SRC) -name Linux_All_OPT.OBJ | xargs -r rm -rf
|
||||
dh_clean
|
||||
|
||||
install: build
|
||||
dh_testdir
|
||||
dh_testroot
|
||||
dh_clean -k
|
||||
dh_installdirs
|
||||
ifneq (,$(EXT))
|
||||
mv -f "oolite.app/oolite$(EXT)" oolite.app/oolite
|
||||
endif
|
||||
|
||||
binary-indep: build install
|
||||
dh_testdir
|
||||
dh_testroot
|
||||
dh_installchangelogs -i
|
||||
dh_installdocs -i
|
||||
dh_install -i
|
||||
cd debian/oolite-data/usr/lib/GNUstep/Applications/oolite.app && rm -f oolite Resources/Info-gnustep.plist
|
||||
find debian/oolite-data -name .svn | xargs -r rm -rf
|
||||
dh_link -i
|
||||
dh_strip -i
|
||||
dh_compress -i
|
||||
dh_fixperms -i
|
||||
dh_installdeb -i
|
||||
dh_gencontrol -i
|
||||
dh_md5sums -i
|
||||
dh_builddeb -i
|
||||
|
||||
binary-arch: build install
|
||||
dh_testdir
|
||||
dh_testroot
|
||||
dh_installman -a debian/oolite.6
|
||||
dh_installmenu -a
|
||||
dh_install -a
|
||||
dh_desktop -a FreeDesktop/oolite.desktop
|
||||
rm -rf debian/oolite/usr/share/doc/oolite
|
||||
find debian/oolite -name .svn | xargs -r rm -rf
|
||||
dh_link -a
|
||||
dh_strip -a
|
||||
dh_compress -a
|
||||
dh_fixperms -a
|
||||
dh_installdeb -a
|
||||
dh_shlibdeps -a
|
||||
dh_gencontrol -a
|
||||
dh_md5sums -a
|
||||
dh_builddeb -a
|
||||
|
||||
binary: binary-arch binary-indep
|
||||
|
||||
.PHONY: binary binary-arch binary-indep build clean install
|
Binary file not shown.
After Width: | Height: | Size: 22 KiB |
Binary file not shown.
After Width: | Height: | Size: 2.2 KiB |
|
@ -0,0 +1,192 @@
|
|||
; Include the NSIS logic library. Required for the code that handles
|
||||
; adding of the changelog file in the non-snapshot distributions
|
||||
!include "LogicLib.nsh"
|
||||
|
||||
; Need to include the versions as we can't pass them in as parameters
|
||||
; and it's too much work to try to dynamically edit this file
|
||||
!include /NONFATAL "OoliteVersions.nsh"
|
||||
|
||||
!ifndef SVNREV
|
||||
!warning "No SVN Revision supplied"
|
||||
!define SVNREV 0
|
||||
!endif
|
||||
!ifndef VERSION
|
||||
!warning "No Version information supplied"
|
||||
!define VERSION 0.0.0.0
|
||||
!endif
|
||||
; Version number must be of format X.X.X.X.
|
||||
; We use M.m.R.S: M-major, m-minor, R-revision, S-subversion
|
||||
!define VER ${VERSION}
|
||||
!ifndef DST
|
||||
!define DST ..\..\oolite.app
|
||||
!endif
|
||||
!ifndef OUTDIR
|
||||
!define OUTDIR .
|
||||
!endif
|
||||
|
||||
!ifndef SNAPSHOT
|
||||
!define EXTVER ""
|
||||
!define ADDCHANGELOG 1 ; Official distributions go with a changelog file
|
||||
!else
|
||||
!define EXTVER "-dev"
|
||||
!define ADDCHANGELOG 0 ; Snapshot distributions do not need changelog
|
||||
!endif
|
||||
|
||||
!include "MUI.nsh"
|
||||
|
||||
SetCompress auto
|
||||
SetCompressor LZMA
|
||||
SetCompressorDictSize 32
|
||||
SetDatablockOptimize on
|
||||
OutFile "${OUTDIR}\OoliteInstall-${VER}${EXTVER}.exe"
|
||||
BrandingText "(C) 2003-2009 Giles Williams and contributors"
|
||||
Name "Oolite"
|
||||
Caption "Oolite ${VER}${EXTVER} Setup"
|
||||
SubCaption 0 " "
|
||||
SubCaption 1 " "
|
||||
SubCaption 2 " "
|
||||
SubCaption 3 " "
|
||||
SubCaption 4 " "
|
||||
Icon Oolite.ico
|
||||
UninstallIcon Oolite.ico
|
||||
InstallDirRegKey HKLM Software\Oolite "Install_Dir"
|
||||
InstallDir $INSTDIR ; $INSTDIR is set in .onInit
|
||||
CRCCheck on
|
||||
InstallColors /windows
|
||||
InstProgressFlags smooth
|
||||
AutoCloseWindow false
|
||||
SetOverwrite on
|
||||
|
||||
VIAddVersionKey "ProductName" "Oolite"
|
||||
VIAddVersionKey "FileDescription" "A space combat/trading game, inspired by Elite."
|
||||
VIAddVersionKey "LegalCopyright" "© 2003-2009 Giles Williams and contributors"
|
||||
VIAddVersionKey "FileVersion" "${VER}"
|
||||
!ifdef SNAPSHOT
|
||||
VIAddVersionKey "SVN Revision" "${SVNREV}"
|
||||
!endif
|
||||
!ifdef BUILDTIME
|
||||
VIAddVersionKey "Build Time" "${BUILDTIME}"
|
||||
!endif
|
||||
VIProductVersion "${VER}"
|
||||
|
||||
!define MUI_HEADERIMAGE
|
||||
!define MUI_HEADERIMAGE_BITMAP ".\OoliteInstallerHeaderBitmap_ModernUI.bmp"
|
||||
!define MUI_HEADERIMAGE_UNBITMAP ".\OoliteInstallerHeaderBitmap_ModernUI.bmp"
|
||||
!define MUI_ICON oolite.ico
|
||||
!define MUI_UNICON oolite.ico
|
||||
|
||||
!insertmacro MUI_PAGE_DIRECTORY
|
||||
!insertmacro MUI_PAGE_INSTFILES
|
||||
!insertmacro MUI_UNPAGE_CONFIRM
|
||||
!insertmacro MUI_UNPAGE_INSTFILES
|
||||
|
||||
!insertmacro MUI_LANGUAGE "English"
|
||||
|
||||
Function .onInit
|
||||
; 1. Get the system drive
|
||||
StrCpy $R9 $WINDIR 2
|
||||
StrCpy $INSTDIR $R9\Oolite
|
||||
|
||||
; 2. Check for multiple running installers
|
||||
System::Call 'kernel32::CreateMutexA(i 0, i 0, t "OoliteInstallerMutex") i .r1 ?e'
|
||||
Pop $R0
|
||||
|
||||
StrCmp $R0 0 +3
|
||||
MessageBox MB_OK|MB_ICONEXCLAMATION "Another instance of the Oolite installer is already running."
|
||||
Abort
|
||||
|
||||
; 3. Checks for already-installed versions of Oolite and offers to uninstall
|
||||
ReadRegStr $R0 HKLM \
|
||||
"Software\Microsoft\Windows\CurrentVersion\Uninstall\Oolite" \
|
||||
"UninstallString"
|
||||
StrCmp $R0 "" done
|
||||
|
||||
MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION \
|
||||
"Oolite is already installed. $\n$\nClick `OK` to remove the \
|
||||
previous version or `Cancel` to cancel this upgrade." \
|
||||
IDOK uninst
|
||||
Abort
|
||||
|
||||
;Run the uninstaller
|
||||
uninst:
|
||||
ClearErrors
|
||||
ExecWait '$R0 _?=$INSTDIR'
|
||||
IfErrors no_remove_uninstaller
|
||||
Delete "$INSTDIR\UninstOolite.exe"
|
||||
Goto done
|
||||
no_remove_uninstaller:
|
||||
MessageBox MB_OK|MB_ICONEXCLAMATION "The Uninstaller did not complete successfully. Please ensure Oolite was correctly uninstalled then run the installer again."
|
||||
Abort
|
||||
done:
|
||||
FunctionEnd
|
||||
|
||||
Function RegSetup
|
||||
FunctionEnd
|
||||
|
||||
Function un.RegSetup
|
||||
FunctionEnd
|
||||
|
||||
;------------------------------------------------------------
|
||||
; Installation Section
|
||||
Section ""
|
||||
SetOutPath $INSTDIR
|
||||
|
||||
; Package files
|
||||
CreateDirectory "$INSTDIR\AddOns"
|
||||
|
||||
File "Oolite.ico"
|
||||
File "Oolite_Readme.txt"
|
||||
File "OoliteRS.pdf"
|
||||
File "..\..\Doc\AdviceForNewCommanders.pdf"
|
||||
File "..\..\Doc\OoliteReadMe.pdf"
|
||||
${If} ${ADDCHANGELOG} == "1"
|
||||
File "..\..\Doc\CHANGELOG.TXT"
|
||||
${EndIf}
|
||||
File /r /x .svn /x *~ "${DST}"
|
||||
|
||||
WriteUninstaller "$INSTDIR\UninstOolite.exe"
|
||||
|
||||
; Registry entries
|
||||
WriteRegStr HKLM Software\Oolite "Install_Dir" "$INSTDIR"
|
||||
WriteRegStr HKLM Software\Microsoft\Windows\CurrentVersion\Uninstall\Oolite DisplayName "Oolite ${VER}${EXTVER}"
|
||||
WriteRegStr HKLM Software\Microsoft\Windows\CurrentVersion\Uninstall\Oolite UninstallString '"$INSTDIR\UninstOolite.exe"'
|
||||
|
||||
; Start Menu shortcuts
|
||||
SetOutPath $INSTDIR\oolite.app
|
||||
CreateDirectory "$SMPROGRAMS\Oolite"
|
||||
CreateShortCut "$SMPROGRAMS\Oolite\Oolite.lnk" "$INSTDIR\oolite.app\oolite.exe" "" "$INSTDIR\Oolite.ico"
|
||||
CreateShortCut "$SMPROGRAMS\Oolite\Oolite ReadMe.lnk" "$INSTDIR\OoliteReadMe.pdf"
|
||||
CreateShortCut "$SMPROGRAMS\Oolite\Oolite Reference Sheet.lnk" "$INSTDIR\OoliteRS.pdf"
|
||||
CreateShortCut "$SMPROGRAMS\Oolite\Oolite - Advice for New Commanders.lnk" "$INSTDIR\AdviceForNewCommanders.pdf"
|
||||
CreateShortCut "$SMPROGRAMS\Oolite\Oolite Website.lnk" "http://oolite.org/"
|
||||
CreateShortCut "$SMPROGRAMS\Oolite\Oolite Uninstall.lnk" "$INSTDIR\UninstOolite.exe"
|
||||
|
||||
Call RegSetup
|
||||
|
||||
Exec "notepad.exe $INSTDIR\Oolite_Readme.txt"
|
||||
|
||||
SectionEnd
|
||||
|
||||
;------------------------------------------------------------
|
||||
; Uninstaller Section
|
||||
Section "Uninstall"
|
||||
|
||||
; Remove registry entries
|
||||
DeleteRegKey HKLM Software\Oolite
|
||||
DeleteRegKey HKLM Software\Microsoft\Windows\CurrentVersion\Uninstall\Oolite
|
||||
Call un.RegSetup
|
||||
|
||||
; Remove Start Menu entries
|
||||
RMDir /r "$SMPROGRAMS\Oolite"
|
||||
|
||||
; Remove Package files (but leave any generated content behind)
|
||||
RMDir /r "$INSTDIR\oolite.app\Contents"
|
||||
RMDir /r "$INSTDIR\oolite.app\GNUstep"
|
||||
RMDir /r "$INSTDIR\oolite.app\oolite.app"
|
||||
RMDir /r "$INSTDIR\oolite.app\Resources"
|
||||
RMDir /r "$INSTDIR\oolite.app\Logs"
|
||||
Delete "$INSTDIR\*.*"
|
||||
Delete "$INSTDIR\oolite.app\*.*"
|
||||
|
||||
SectionEnd
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
!packhdr "Oolite.dat" "upx.exe --best Oolite.dat"
|
||||
SetCompress auto
|
||||
SetCompressor LZMA
|
||||
SetCompressorDictSize 32
|
||||
SetDatablockOptimize on
|
||||
|
||||
OutFile "OoliteUpdate.exe"
|
||||
BrandingText "Oolite"
|
||||
Name "Oolite"
|
||||
Caption "Oolite"
|
||||
SubCaption 0 " "
|
||||
SubCaption 1 " "
|
||||
SubCaption 2 " "
|
||||
SubCaption 3 " "
|
||||
SubCaption 4 " "
|
||||
Icon "Install.ico"
|
||||
InstallDirRegKey HKLM Software\Oolite "Install_Dir"
|
||||
InstallDir $PROGRAMFILES\Oolite
|
||||
DirText "Choose a directory to install Oolite"
|
||||
CRCCheck on
|
||||
InstallColors /windows
|
||||
InstProgressFlags smooth
|
||||
AutoCloseWindow false
|
||||
SetOverwrite on
|
||||
|
||||
Function RegSetup
|
||||
FunctionEnd
|
||||
|
||||
Function un.RegSetup
|
||||
FunctionEnd
|
||||
|
||||
Section ""
|
||||
SetOutPath $INSTDIR
|
||||
File "C:\program files\Oolite\Oolite_Readme.txt"
|
||||
|
||||
SetOutPath "$INSTDIR\oolite.app"
|
||||
File "C:\program files\Oolite\oolite.app\Oolite.exe"
|
||||
|
||||
RMDir /r "$INSTDIR\AddOns\lasercoolant.oxp"
|
||||
|
||||
SetOutPath "$INSTDIR\oolite.app\Contents\Resources\Config"
|
||||
File "C:\Program Files\Oolite\oolite.app\Contents\Resources\Config\keyconfig.plist"
|
||||
File "C:\Program Files\Oolite\oolite.app\Contents\Resources\Config\shipdata.plist"
|
||||
File "C:\Program Files\Oolite\oolite.app\Contents\Resources\Config\equipment.plist"
|
||||
|
||||
SetOutPath "$INSTDIR\oolite.app\Contents\Resources\AIs"
|
||||
File "C:\Program Files\Oolite\oolite.app\Contents\Resources\AIs\thargletAI.plist"
|
||||
|
||||
Call RegSetup
|
||||
|
||||
MessageBox MB_OK "Oolite Update Package was installed successfully"
|
||||
SectionEnd
|
||||
|
Binary file not shown.
After Width: | Height: | Size: 82 KiB |
Binary file not shown.
After Width: | Height: | Size: 24 KiB |
Binary file not shown.
After Width: | Height: | Size: 9.5 KiB |
Binary file not shown.
|
@ -0,0 +1,300 @@
|
|||
|
||||
|
||||
How to run Oolite
|
||||
-----------------
|
||||
|
||||
A folder has been created in Start -> Program Files called Oolite. This
|
||||
folder has icons for running the game, the reference sheet, the Advice
|
||||
for New Commanders guide, the link to the official Oolite website,a more
|
||||
detailed ReadMe document in PDF format and an uninstall program.
|
||||
|
||||
To run the game, choose the Oolite icon in the Oolite folder.
|
||||
|
||||
|
||||
The user preferences defaults file .GNUstepDefaults
|
||||
-----------------------------------------------------------------------
|
||||
|
||||
The file <installation dir>/oolite.app/GNUstep/Defaults/.GNUstepDefaults
|
||||
contains the current settings for fullscreen mode and display resolutions,
|
||||
together with the user preference settings for sound volume, reduced
|
||||
detail (Yes/No), wireframe graphics display (Yes/No) and the shader
|
||||
effects level (Off, Simple, Full), in case your system supports shaders.
|
||||
All these can be changed by either running the game and navigating to the
|
||||
Game Options... menu ('F2' or '2' key, then select Game Options...), or
|
||||
by directly editing the .GNUstepDefaults file. The recommended way to
|
||||
change settings is to use the in-game menu. See below for examples of
|
||||
editing the preferences file. Note that .GNUstepDefaults will not be
|
||||
present after the game's installation. You will need to run Oolite at
|
||||
least once to have it generated.
|
||||
|
||||
|
||||
Switching between full screen and windowed mode, or changing resolution
|
||||
-----------------------------------------------------------------------
|
||||
|
||||
The long standing issues with textures being corrupted when resizing the
|
||||
game window have been resolved as of version 1.73.
|
||||
|
||||
If in doubt, delete .GNUstepDefaults and restart the game. That will start
|
||||
you in windowed mode.
|
||||
|
||||
To change the full screen mode resolution, you can use the Game Options...
|
||||
menu or alternatively edit the .GNUstepDefaults file by changing the
|
||||
display_width and display_height values, and ensuring the fullscreen
|
||||
property has a value of <*BY>.
|
||||
|
||||
|
||||
.GNUstepDefaults Editing Examples
|
||||
-----------------------------------------------------------------------
|
||||
|
||||
These settings will give a full screen display of 800x600, about one
|
||||
third sound volume, reduced detail set to No, wireframe graphics set
|
||||
to Yes and shader effects set to Simple:
|
||||
|
||||
{
|
||||
NSGlobalDomain = {
|
||||
};
|
||||
oolite.exe = {
|
||||
display_width = <*I800>;
|
||||
display_height = <*I600>;
|
||||
fullscreen = <*BY>;
|
||||
"reduced-detail-graphics" = <*BN>;
|
||||
"shader-effects-level" = <*I2>;
|
||||
volume_control = <*R0.26>;
|
||||
"wireframe-graphics" = <*BY>;
|
||||
};
|
||||
}
|
||||
|
||||
And these settings will give a full screen display of 1400x1050,
|
||||
full sound volume, reduced detail set to No, wireframe graphics
|
||||
set to No and shader effects set to Full:
|
||||
|
||||
{
|
||||
NSGlobalDomain = {
|
||||
};
|
||||
oolite.exe = {
|
||||
display_width = <*I1400>;
|
||||
display_height = <*I1050>;
|
||||
fullscreen = <*BY>;
|
||||
"reduced-detail-graphics" = <*BN>;
|
||||
"shader-effects-level" = <*I3>;
|
||||
volume_control = <*R1>;
|
||||
"wireframe-graphics" = <*BN>;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Tips
|
||||
----
|
||||
|
||||
* Read the installed "Oolite reference sheet" PDF for the controls
|
||||
|
||||
* More detailed information about the game can be found inside the Acrobat
|
||||
PDF OoliteReadMe file, already installed in your root Oolite folder
|
||||
|
||||
* Use Shift+Escape to quit the game
|
||||
|
||||
* Read the tutorial before you begin! ( http://oolite.aegidian.org/tutorial )
|
||||
|
||||
* You can read the Advice for New Commanders at the bottom of this file for
|
||||
a quick introduction to the game, with hints and tips
|
||||
|
||||
|
||||
Links
|
||||
-----
|
||||
Oolite website at: http://oolite.org
|
||||
|
||||
Oolite Message Board at: http://www.aegidian.org/bb
|
||||
|
||||
Oolite Development Project Page at: https://developer.berlios.de/projects/oolite-linux/
|
||||
|
||||
Browse the Oolite wiki at: http://wiki.alioth.net/index.php/Oolite_Main_Page
|
||||
|
||||
Get OXPs at: http://wiki.alioth.net/index.php/OXP
|
||||
http://oosat.alioth.net/
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Advice for New Commanders*
|
||||
by Disembodied, 24-Mar-2008
|
||||
---------------------------
|
||||
|
||||
It is an ancient mariner,
|
||||
and he stoppeth one of three...
|
||||
|
||||
All right there! You just got your pilot’s ticket. Can I just say that your zip-clip
|
||||
there doesn’t do you justice? You’re itching to get off and out into the big black, I
|
||||
can tell; but we just got a few final once-overs before I can stamp that thing legal.
|
||||
Shall we?
|
||||
|
||||
So. You got yourself a brand and shiny-new Cobra Mark III. Cowell and MgRath’s finest,
|
||||
yes siree: more’n sixty years since the first one rolled off the line right here on Lave,
|
||||
and it’s still one of the best. An all-round ship, you get me? It ain’t the fastest, and
|
||||
it ain’t the strongest, nor the most killing neither, and it definitely ain’t the biggest,
|
||||
by a long shot, but a sweet little number in her own right, no error.
|
||||
|
||||
Let’s take a tour around... Hoo boy, she is mint, ain’t she! I just love that new-ship
|
||||
smell. Take a sniff, go on: yeah, well, most of them long-chain monomers is carcinogenic,
|
||||
so don’t you snort too deep...
|
||||
|
||||
Hah! I’m just funnin’ ya, kid. If pulling a tick from sniffing the command console was all
|
||||
a pilot had to worry about, life would be gravy! No, there’s more’n enough out there to kill
|
||||
you plenty quick, if you don’t watch out, shiny new ship or no.
|
||||
|
||||
I see a lot of blanks on this here board... I’m guessing your ship is, whadda they call it,
|
||||
a basic model, yeah? Legal minimum? Uh-huh, I thought so. Man oh man, they shouldn’t oughta
|
||||
let kids out in a machine like this; it’s a sin, is what it is. Some bandit takes a pop at
|
||||
you, and what you got to hold your end up with? A Pulse Laser. A Pulse Laser’s one step up
|
||||
from a penlight, kiddo. Oh, it’s a better defence than just harsh language, and there’s
|
||||
always a chance you might be attacked by a really nervous pirate – but seriously: if you
|
||||
ever want to shift that “Harmless” tag you better beef up your armaments, and soon! Beam
|
||||
laser, minimum. Until then you’d best stick to the cop-end worlds: Democracies and Corporates,
|
||||
Confederacies maybe if you’re feeling lucky, you hear me? You stay sharp, and maybe you’ll
|
||||
stay alive.
|
||||
|
||||
See, right here is what I’m talking about: this is where you need to fit an ECM. Someone locks
|
||||
a missile on you, you pop that sucker fast. Oh, I know there’s Hardheads out there, shielded
|
||||
missiles proofed against countermeasures, but a good ECM can pop those too, if you’re lucky.
|
||||
You get one of those running on you, you turn tail and run from it as fast as you can. A
|
||||
warhead’s nasty, but nosense in giving it a kinetic advantage too, right? Keep slapping the ECM
|
||||
as you go, if you’ve got the energy for it: if the first burst don’t kill it, maybe the next
|
||||
one will.
|
||||
|
||||
Speaking of running... over here is where you’d control your Witchdrive Fuel Injectors, if’n
|
||||
you had ‘em... dumps fuel straight from the tanks into the drive, and shoots you off like an
|
||||
Oresquan on a hot date. Good for whatever ails ya, from pushing past a mass-lock to getting the
|
||||
hell out of town!
|
||||
|
||||
Down here, now, this is your Fuel Scoop indicator... huh, “offline”, I see. Sure, sure, you
|
||||
don’t think you’ll ever need to kiss the stars: why bother, when fuel’s cheaper than Celabiler
|
||||
poetry? Well, maybe it’s true, and maybe it ain’t, but anyways this piece of kit scoops up more
|
||||
than just sunshine. There’s scraps and salvage out there, kid, and good money to be had. Skim on
|
||||
over the top and this puppy drops ‘em straight into the cargo bay. Pays for itself in no time.
|
||||
Sweeps up Escape Pods, too: you get the chance to bring someone safe home, you take it – even if
|
||||
it means dumping some of your own payload to take them on board. Look out for the other guys and
|
||||
they’ll look out for you.
|
||||
|
||||
And... sweet Lord Giles on a gyrospider, they didn’t even fit you out with a Docking Computer!
|
||||
“Optional Extra”, my shiny blue ass... Oh, sure, manual docking’s easy enough, but there’s a
|
||||
knack to it. You gotta get that knack first, though. Practice it. Before you go anywhere,
|
||||
practice it. Fly out to the station buoy, turn around and come back in again, until you got it
|
||||
pat. And match the rotation: you put scrapes or dents or a big long greasy smear all over my bay,
|
||||
and I will NOT be pleased...
|
||||
|
||||
Oh, there’s a whole bunch of other shit you can stick on here: a Scanner Targeting Enhancement,
|
||||
for one, if you ever get yourself set up right for a firefight. Even before then, maybe: if you
|
||||
can clock pirates before they start their run on you, that’s half the battle. Well, quarter of
|
||||
the battle. Or a fifth. Some proportion, anyhow. The Advanced Space Compass, too, now that’s a
|
||||
handy doodad to have on board. And an Extra Energy Unit to boost your recharge. And Shield
|
||||
Boosters, now they’re a no-brainer. And – okay, most of this junk is too high-tech for Lave: you
|
||||
can get most everything at Zaonce, though, just a wormhole away. Dull kinda burg, Zaonce, but
|
||||
they know their quarks from their quaternions. Shouldn’t set you back more’n ten, twenty thou.
|
||||
|
||||
You got how much? One hundred creds. One ... hundred ... creds. Ayoha. All right then. Let’s
|
||||
break it down. Your problem here is financial, not technical. Maybe at bottom it’s psychological,
|
||||
but I’ll give you the benefit.
|
||||
|
||||
There’s two types of money, kid: fast, and slow. Fast money comes easy, and slow money comes hard.
|
||||
The slow is sure and steady, though, and the fast, well, it might make you wish you had waited.
|
||||
I’ll run you through them both, though, and you can make up your own mind.
|
||||
|
||||
First of all, for the fast money, there’s this sweet and cherry Cobra III: you sell it, right now,
|
||||
you’ll net yourself enough to buy a second-hand ship with enough scratch left over for some half-
|
||||
decent kit. ‘Course, some of these second-hand numbers are pretty, well, used, if you know what I
|
||||
mean, and come with problems of their own. I mean, you ever try to take a dump in a head designed
|
||||
for some other guy’s anatomy? And the resale sucks, if’n you ever want to move on up. But it’s an
|
||||
option.
|
||||
|
||||
Second, now, there’s the... ah, let me just check that we’re alone here... okay: there’s the Black
|
||||
Monks. Great guys, I’d like to make that clear, absolutely: most fine and upstanding! They’ll be
|
||||
happy to loan you what you need to get you started. They’re a not-for-profit organisation, a charity,
|
||||
really, but what with overheads and all they do have to charge a wee bit of interest on any loans
|
||||
they make: and they are keen – eager, even – to see that they get paid back. You take a loan from
|
||||
them, you make every gram of cargo pay, every time. Work hard though and it can be done: in all my
|
||||
years I’ve never met anyone who defaulted on a loan from the Bank of St Herod. Not one. Ever.
|
||||
|
||||
Slow money, now, that’s less chancy. You buy up what’s cheap, you take it to where it’s expensive,
|
||||
and you sell it at a profit. Rinse and repeat. What’s cheap where, and what’s expensive? Supply and
|
||||
demand, kid. Like the philosopher said, “it’s the economy, stupid”. Agricultural worlds produce raw
|
||||
materials like minerals, metals and radioactives, and the bio-products like food, textiles, booze
|
||||
and furs, too. Industrial planets make finished goods, like luxuries, computers and machinery. So
|
||||
you take the produce of one and you sell it on the other, and chances are you’re making money on
|
||||
the deal. Politics don’t matter squat: farmers need harvesters and factories need feedstock!
|
||||
|
||||
O’course, money matters: rich Industrials are rich because they’ve got the most efficient processes,
|
||||
so not only do they make the cheapest products, their factories are the hungriest and they’ll pay
|
||||
the best prices for raw materials. Poor Agriculturals, on the other hand, they’re most desperate for
|
||||
fine articles and will scrape together whatever they can to pay for ‘em: meanwhile, they’ll offer
|
||||
you the cheapest deals anywhere for what they make themselves. Which puts a vicious lock on the
|
||||
poverty trap, but hey: nobody said life was fair. Folks like you who’ve climbed up the gravity well,
|
||||
you’re just filling a need. Buy and sell between rich Industrials and poor Agriculturals, that’s my
|
||||
advice! There’s money to be made elsewhere, no error, but those are the sweetest runs you’re likely
|
||||
to hit on. Bulk is the key, kid: the more you carry, the more you make. This Cobra III here can take
|
||||
twenty tons, right now: for just 400 creds more you can get a Cargo Bay Expansion to take you up to
|
||||
thirty-five.That extra fifteen tons of space will pay for itself and more in one good run, if you
|
||||
can fill it up.
|
||||
|
||||
It ain’t all bulk, though. Watch the board for cheap deals on precious metals and gemstones: they
|
||||
might not offer the greatest profits, but they don’t take up any cargo space at all. See this safe
|
||||
over here, behind this bulkhead? You take on platinum, or gold, or a sack of IOUN gemstones when
|
||||
you’re docked, they go right in here. You can keep ‘em here as long as you like, until you find
|
||||
somewhere to offload ‘em. Co-op rules stop you dropping too much of ‘em, or too much of anything,
|
||||
come to that, in one station – so much for free trade! – but as a slow-burn money-maker there’s not
|
||||
much to beat it. You can mine for ‘em yourself, if’n you get a Mining Laser and an Ore Processor to
|
||||
go with your Fuel Scoop, and you don’t mind scraping carbon scoring off the scoop every few jumps.
|
||||
Only don’t, for any sake, put the Mining Laser on the nose! It’s a tool, not a weapon. Or you can
|
||||
just buy the shinies cheap off the miners direct, if you run across a Rock Hermit. Powerful fond of
|
||||
liquor, Rock Hermits are, too.
|
||||
|
||||
What “other” products? What you winking for, kid? You mean slaves, narcotics and firearms? Why don’t
|
||||
you just damn well say so? They ain’t illegal. They’s what we call controlled merchandise. Bring as
|
||||
much of ‘em in as you want... what will get you into trouble with the Blues is shipping them out of
|
||||
a main system station. But there’s plenty of other places to buy ‘em up, all nice and legal, along
|
||||
with reg’lar trade goods, too. Some of the Commie worlds have Slap-Yous and Cee-Zed-Gee-Effs, whatever
|
||||
the hell they all are, and Astro-Gulags too, which are just plain depressing. Some industrial
|
||||
Dictatorship systems, they got Imperial AstroFactories, although some of ‘em seem to sell stuff they
|
||||
don’t ever make... go figure. And some spots, if they got the population size to make it worthwhile,
|
||||
there’s Convenience Stores way out by the Witchpoint. You want to give these guys a try, you sail on
|
||||
in. Check the system prices first, note down what you got yourself, see what’s on offer, and do the
|
||||
sums.
|
||||
|
||||
There’s long-range shipping contracts on offer, too, in some stations: F8-F8 will bring ‘em up, if
|
||||
there’s any there. You buy the deal and then get paid a bonus if you make the delivery on time.
|
||||
They’ll be out your price-range just now, and anyway most of ‘em call for a bigger cargo-hold than
|
||||
a Cobra can carry. Keep an eye out for any you might be able to do, though; if you build a rep as a
|
||||
reliable carrier then the jobs can get real juicy.
|
||||
|
||||
That’s slow money, kid: work, save, invest, and work again, that’s what it’s all about! It ain’t pretty
|
||||
but it gets you there in the end.
|
||||
|
||||
One final tip, kid: I’ll say this ‘cos I like ya. It won’t save you work but it will save you time,
|
||||
and it might just save your life, too: if you want to get from the Witchpoint to the station fast,
|
||||
without getting your jumpdrive mass-locked by anyone, friendly or otherwise, here’s what you do. Line
|
||||
up on the planet; angle up away from it by near enough ninety degrees; then hit the Torus jumpdrive
|
||||
and scoot on out of the main spacelane for a few hundred klicks or so. Then, when you’ve given yourself
|
||||
enough sky, pull the nose back round and come on down to the station. Chances are you won’t meet a soul,
|
||||
whether you’re cruising into Ensoreus or creeping into Qudira. The spacelanes is where the action is,
|
||||
where there’s help and hostility both; you get nervous, you go off-beam. Most times, you’ll come through
|
||||
safe.
|
||||
|
||||
Huh. Anyhow. I’m a busy frog, I can’t stay here all day filling in every Jameson on what they should have
|
||||
learned in the spawning pond. Gimme your ticket, kid, and I’ll stamp it flight-ready, though Giles knows I
|
||||
prob’ly shouldn’t... there ya go. That’s you ready to take on the Witch. Jens help us all... don’t know
|
||||
enough to keep a level bearing through a wormhole... what they send up here for us to deal with... pick up
|
||||
the pieces more like...
|
||||
|
||||
|
||||
---------------------------
|
||||
*Disclaimer:
|
||||
The above text makes reference to certain Oolite eXpansion Packs (OXPs), that are not part of the core
|
||||
Oolite game. The fact that certain elements from OXPs are mentioned does not necessarily mean that
|
||||
these OXPs are recommended by the Oolite Team, as OXP selection and usage is subject to user personal
|
||||
preferences. The OXPs mentioned in Advice for New Commanders are Rusties, Bank of the Black Monks,
|
||||
Ore Processor, Communist flavour pack, Dictatorship flavour pack, Your Ad Here. All Oolite OXPs are
|
||||
available for download from either http://wiki.alioth.net/index.php/OXP or http://oosat.alioth.net/
|
|
@ -0,0 +1,9 @@
|
|||
@echo off
|
||||
set BASE=%~dp0
|
||||
set GNUSTEP_PATH_HANDLING=windows
|
||||
set GNUSTEP_SYSTEM_ROOT=%BASE%\oolite.app
|
||||
set GNUSTEP_LOCAL_ROOT=%BASE%\oolite.app
|
||||
set GNUSTEP_NETWORK_ROOT=%BASE%\oolite.app
|
||||
set GNUSTEP_USERS_ROOT=%BASE%\oolite.app
|
||||
set HOMEPATH=%BASE%\oolite.app
|
||||
"%BASE%\oolite.app\oolite.exe" %1 %2 %3 %4
|
Binary file not shown.
After Width: | Height: | Size: 22 KiB |
|
@ -0,0 +1,7 @@
|
|||
#ifndef BSD_STRING_H
|
||||
#define BSD_STRING_H
|
||||
#ifdef NEED_STRLCPY
|
||||
size_t strlcpy(char *dst, const char *src, size_t siz);
|
||||
#endif
|
||||
#endif
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
/* $OpenBSD: strlcpy.c,v 1.10 2005/08/08 08:05:37 espie Exp $ */
|
||||
|
||||
/*
|
||||
* Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifdef NEED_STRLCPY
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <string.h>
|
||||
#include "bsd_string.h" /* DJS for Oolite on Linux/win32 */
|
||||
|
||||
/*
|
||||
* Copy src to string dst of size siz. At most siz-1 characters
|
||||
* will be copied. Always NUL terminates (unless siz == 0).
|
||||
* Returns strlen(src); if retval >= siz, truncation occurred.
|
||||
*/
|
||||
size_t
|
||||
strlcpy(char *dst, const char *src, size_t siz)
|
||||
{
|
||||
char *d = dst;
|
||||
const char *s = src;
|
||||
size_t n = siz;
|
||||
|
||||
/* Copy as many bytes as will fit */
|
||||
if (n != 0 && --n != 0) {
|
||||
do {
|
||||
if ((*d++ = *s++) == 0)
|
||||
break;
|
||||
} while (--n != 0);
|
||||
}
|
||||
|
||||
/* Not enough room in dst, add NUL and traverse rest of src */
|
||||
if (n == 0) {
|
||||
if (siz != 0)
|
||||
*d = '\0'; /* NUL-terminate dst */
|
||||
while (*s++)
|
||||
;
|
||||
}
|
||||
|
||||
return(s - src - 1); /* count does not include NUL */
|
||||
}
|
||||
#endif
|
||||
|
|
@ -0,0 +1 @@
|
|||
// Empty for OS X, compatibility stuff for GNUstep.
|
|
@ -0,0 +1,60 @@
|
|||
/*
|
||||
|
||||
Groolite.h
|
||||
|
||||
Growl integration class. The singleton Groolite object listens for Growl
|
||||
notifications and reports them by printing to the game communication log. For
|
||||
more about Growl, see <http://growl.info>.
|
||||
|
||||
To do: reimplement using delegate pattern, remove dependency on Growl
|
||||
framework headers (the framework is not needed at run time).
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
*/
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import <Growl/Growl.h>
|
||||
|
||||
@class GameController;
|
||||
|
||||
|
||||
enum
|
||||
{
|
||||
kGrooliteAllMessages = -2,
|
||||
kGrooliteLowPriority,
|
||||
kGrooliteMediumPriority,
|
||||
kGrooliteHighPriority,
|
||||
kGrooliteHighestPriority,
|
||||
kGrooliteOff,
|
||||
|
||||
kGroolitePriorityMinimum = kGrooliteAllMessages,
|
||||
kGroolitePriorityMaximum = kGrooliteOff
|
||||
};
|
||||
|
||||
|
||||
@interface Groolite: NSObject
|
||||
{
|
||||
NSConnection *connection;
|
||||
IBOutlet GameController *gameController;
|
||||
}
|
||||
|
||||
+ (NSString*) priorityDescription: (int) min_priority;
|
||||
|
||||
@end
|
|
@ -0,0 +1,254 @@
|
|||
/*
|
||||
|
||||
Groolite.m
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
*/
|
||||
|
||||
#import "Groolite.h"
|
||||
#import <Growl/Growl.h>
|
||||
#import "GameController.h"
|
||||
#import "GuiDisplayGen.h"
|
||||
#import "Universe.h"
|
||||
#import "PlayerEntityLegacyScriptEngine.h"
|
||||
|
||||
static NSString * const kOOLogGrooliteError = @"growl.error";
|
||||
static NSString * const kOOLogGrooliteDebug = @"growl.debug";
|
||||
|
||||
// #define GROOLITE_DEBUG
|
||||
|
||||
|
||||
@protocol GrowlNotificationObserver
|
||||
- (oneway void) notifyWithDictionary:(bycopy NSDictionary *)dict;
|
||||
@end
|
||||
|
||||
|
||||
@protocol GrowlNotificationCenterProtocol
|
||||
|
||||
- (oneway void) addObserver:(byref id<GrowlNotificationObserver>)observer;
|
||||
- (oneway void) removeObserver:(byref id<GrowlNotificationObserver>)observer;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@interface Groolite (Private) <GrowlNotificationObserver>
|
||||
|
||||
- (void)connectToGrowl:unused;
|
||||
- (void)disconnectFromGrowl:unused;
|
||||
- (void)connectionDied:unused;
|
||||
- (void)displayGrowlNotificiationWithTitle:(NSString *)inTitle andMessage:(NSString *)inMessage fromApp:(NSString *) inAppname;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation Groolite
|
||||
|
||||
- (void)displayGrowlNotificiationWithTitle:(NSString *)inTitle andMessage:(NSString *)inMessage fromApp:(NSString *) inAppname
|
||||
{
|
||||
PlayerEntity *player;
|
||||
NSString *notificationString;
|
||||
NSString *displayString;
|
||||
|
||||
player = [PlayerEntity sharedPlayer];
|
||||
|
||||
if (!inTitle)
|
||||
return; // catch blank messages
|
||||
|
||||
if (!inAppname)
|
||||
{
|
||||
// standard response
|
||||
notificationString = @"Growl";
|
||||
}
|
||||
else
|
||||
{
|
||||
// response if we're told which application is sending the message
|
||||
notificationString = inAppname;
|
||||
}
|
||||
|
||||
if (nil == inMessage)
|
||||
{
|
||||
// Terse mode
|
||||
displayString = [NSString stringWithFormat:@"%@: %@", notificationString, inTitle];
|
||||
}
|
||||
else
|
||||
{
|
||||
// Standard 'verbose' mode
|
||||
displayString = [NSString stringWithFormat:@"%@: %@\n%@", notificationString, inTitle, inMessage];
|
||||
}
|
||||
|
||||
[player commsMessage: displayString];
|
||||
|
||||
if ([player isSpeechOn])
|
||||
{
|
||||
[UNIVERSE stopSpeaking];
|
||||
[UNIVERSE startSpeakingString:[NSString stringWithFormat:@"%@ message: %@", notificationString, inTitle]];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (id)init
|
||||
{
|
||||
NSDistributedNotificationCenter *dnc;
|
||||
|
||||
self = [super init];
|
||||
if (nil != self)
|
||||
{
|
||||
/*
|
||||
Subscribe to GROWL_IS_READY notifications.
|
||||
This is necessary in case GrowlHelperApp currently isn't running, and in case
|
||||
it is restarted.
|
||||
*/
|
||||
dnc = [NSDistributedNotificationCenter defaultCenter];
|
||||
[dnc addObserver:self selector:@selector(connectToGrowl:) name:GROWL_IS_READY object:nil];
|
||||
|
||||
// Also, try to connect on the off chance it’s running now.
|
||||
[self connectToGrowl:nil];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
[self disconnectFromGrowl:nil];
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
- (void)connectToGrowl:unused
|
||||
{
|
||||
NSConnection *theConnection;
|
||||
NSNotificationCenter *nc;
|
||||
id<GrowlNotificationCenterProtocol> growlNC;
|
||||
|
||||
NS_DURING
|
||||
theConnection = [NSConnection connectionWithRegisteredName:@"GrowlNotificationCenter" host:nil];
|
||||
if (nil != theConnection)
|
||||
{
|
||||
growlNC = (id<GrowlNotificationCenterProtocol>)[theConnection rootProxy];
|
||||
[growlNC addObserver:self];
|
||||
|
||||
// Subscribe to connection-died and application-quit notifications, so we can unregister appropriately.
|
||||
nc = [NSNotificationCenter defaultCenter];
|
||||
[nc addObserver:self selector:@selector(connectionDied:) name:NSConnectionDidDieNotification object:theConnection];
|
||||
[nc addObserver:self selector:@selector(disconnectFromGrowl:) name:NSApplicationWillTerminateNotification object:nil];
|
||||
|
||||
connection = [theConnection retain];
|
||||
}
|
||||
NS_HANDLER
|
||||
OOLog(kOOLogGrooliteError, @"DEBUG GROOLITE exception : %@ : %@", [localException name], [localException reason]);
|
||||
NS_ENDHANDLER
|
||||
}
|
||||
|
||||
|
||||
- (void)disconnectFromGrowl:unused
|
||||
{
|
||||
NSNotificationCenter *nc;
|
||||
id<GrowlNotificationCenterProtocol> growlNC;
|
||||
|
||||
if (nil != connection)
|
||||
{
|
||||
NS_DURING
|
||||
growlNC = (id<GrowlNotificationCenterProtocol>)[connection rootProxy];
|
||||
[growlNC removeObserver:self];
|
||||
[connection release];
|
||||
connection = nil;
|
||||
|
||||
nc = [NSNotificationCenter defaultCenter];
|
||||
[nc removeObserver:self];
|
||||
NS_HANDLER
|
||||
OOLog(kOOLogGrooliteError, @"DEBUG GROOLITE exception : %@ : %@", [localException name], [localException reason]);
|
||||
NS_ENDHANDLER
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void)connectionDied:unused
|
||||
{
|
||||
NSNotificationCenter *nc;
|
||||
|
||||
if (nil != connection)
|
||||
{
|
||||
NS_DURING
|
||||
[connection release];
|
||||
connection = nil;
|
||||
|
||||
nc = [NSNotificationCenter defaultCenter];
|
||||
[nc removeObserver:self];
|
||||
NS_HANDLER
|
||||
OOLog(kOOLogGrooliteError, @"DEBUG GROOLITE exception : %@ : %@", [localException name], [localException reason]);
|
||||
NS_ENDHANDLER
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (oneway void) notifyWithDictionary:(bycopy NSDictionary *)inDict
|
||||
{
|
||||
NSUserDefaults *prefs;
|
||||
int priority;
|
||||
NSString *title;
|
||||
NSString *message;
|
||||
NSString *appname;
|
||||
|
||||
prefs = [NSUserDefaults standardUserDefaults];
|
||||
|
||||
// Ignore if we're in a window
|
||||
#ifndef GROOLITE_DEBUG
|
||||
if (![gameController inFullScreenMode])
|
||||
return;
|
||||
#endif
|
||||
|
||||
// Ignore if we're paused
|
||||
if ([gameController gameIsPaused])
|
||||
return;
|
||||
|
||||
// Check that priority is not below our threshold
|
||||
priority = [[inDict objectForKey:GROWL_NOTIFICATION_PRIORITY] intValue];
|
||||
#ifndef GROOLITE_DEBUG
|
||||
if (priority < [prefs integerForKey:@"groolite-min-priority"])
|
||||
return;
|
||||
#endif
|
||||
|
||||
// If we get here, we need to handle the message
|
||||
title = [inDict objectForKey:GROWL_NOTIFICATION_TITLE];
|
||||
message = [inDict objectForKey:GROWL_NOTIFICATION_DESCRIPTION];
|
||||
appname = [inDict objectForKey:GROWL_APP_NAME];
|
||||
|
||||
OOLog(kOOLogGrooliteDebug, @"Received Growl notification: inDict\n%@\n\n", inDict);
|
||||
OOLog(kOOLogGrooliteDebug, @"Groolite: priority = %d appname = \"%@\" title = \"%@\", message = \"%@\"", priority, appname, title, message);
|
||||
|
||||
if (nil == title || [@"" isEqual:title])
|
||||
{
|
||||
title = message;
|
||||
message = nil;
|
||||
}
|
||||
|
||||
[self displayGrowlNotificiationWithTitle:title andMessage:message fromApp:appname];
|
||||
}
|
||||
|
||||
|
||||
+ (NSString*) priorityDescription: (int) min_priority
|
||||
{
|
||||
if (min_priority < kGroolitePriorityMinimum || min_priority > kGroolitePriorityMaximum) return @"?";
|
||||
return [UNIVERSE descriptionForArrayKey:@"growl-priority-levels" index:min_priority - kGroolitePriorityMinimum];
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,114 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>English</string>
|
||||
<key>CFBundleDocumentTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleTypeExtensions</key>
|
||||
<array>
|
||||
<string>oolite-save</string>
|
||||
</array>
|
||||
<key>CFBundleTypeIconFile</key>
|
||||
<string>oolite-document</string>
|
||||
<key>CFBundleTypeName</key>
|
||||
<string>Oolite Saved Game</string>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>Editor</string>
|
||||
<key>LSHandlerRank</key>
|
||||
<string>Owner</string>
|
||||
<key>LSItemContentTypes</key>
|
||||
<array>
|
||||
<string>org.aegidian.oolite.save</string>
|
||||
</array>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>CFBundleTypeExtensions</key>
|
||||
<array>
|
||||
<string>oxp</string>
|
||||
</array>
|
||||
<key>CFBundleTypeIconFile</key>
|
||||
<string>oolite-expansion-document</string>
|
||||
<key>CFBundleTypeName</key>
|
||||
<string>Oolite Expansion Pack</string>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>Viewer</string>
|
||||
<key>LSHandlerRank</key>
|
||||
<string>Alternate</string>
|
||||
<key>LSTypeIsPackage</key>
|
||||
<true/>
|
||||
<key>LSItemContentTypes</key>
|
||||
<array>
|
||||
<string>org.aegidian.oolite.oxp</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>Oolite</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>oolite-icon</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>org.aegidian.oolite</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>Oolite</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>Ool8</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1.73</string>
|
||||
<key>NSMainNibFile</key>
|
||||
<string>MainMenu</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>OoliteApp</string>
|
||||
<key>UTExportedTypeDeclarations</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>UTTypeIdentifier</key>
|
||||
<string>org.aegidian.oolite.save</string>
|
||||
<key>UTTypeDescription</key>
|
||||
<string>Oolite Saved Game</string>
|
||||
<key>UTTypeConformsTo</key>
|
||||
<array>
|
||||
<string>public.text</string>
|
||||
<string>com.apple.property-list</string>
|
||||
</array>
|
||||
<key>UTTypeTagSpecification</key>
|
||||
<dict>
|
||||
<key>public.filename-extension</key>
|
||||
<array>
|
||||
<string>oolite-save</string>
|
||||
</array>
|
||||
</dict>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>UTTypeIdentifier</key>
|
||||
<string>org.aegidian.oolite.oxp</string>
|
||||
<key>UTTypeDescription</key>
|
||||
<string>Oolite Expansion Pack</string>
|
||||
<key>UTTypeConformsTo</key>
|
||||
<array>
|
||||
<string>public.item</string>
|
||||
<string>com.apple.package</string>
|
||||
</array>
|
||||
<key>UTTypeTagSpecification</key>
|
||||
<dict>
|
||||
<key>public.filename-extension</key>
|
||||
<array>
|
||||
<string>oxp</string>
|
||||
</array>
|
||||
</dict>
|
||||
</dict>
|
||||
</array>
|
||||
<key>SmartCrashReports_CompanyName</key>
|
||||
<string>the Oolite team</string>
|
||||
<key>SmartCrashReports_EmailTicket</key>
|
||||
<string>SCR-A36F37AFFD</string>
|
||||
<key>SmartCrashReports_CommentsTemplate</key>
|
||||
<string>Please paste the last few lines of the run log here (in your home folder, open Library, then Logs, then Oolite, then Latest.log). If a large portion of the log appears relevant, consider sending a bug report by e-mail to bugs@oolite.org instead; please include the crash log if you do (Library, Logs, CrashReporter, Oolite.crash.log).</string>
|
||||
</dict>
|
||||
</plist>
|
|
@ -0,0 +1,113 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>English</string>
|
||||
<key>CFBundleDocumentTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleTypeExtensions</key>
|
||||
<array>
|
||||
<string>oolite-save</string>
|
||||
</array>
|
||||
<key>CFBundleTypeIconFile</key>
|
||||
<string>oolite-document</string>
|
||||
<key>CFBundleTypeName</key>
|
||||
<string>Oolite Saved Game</string>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>Editor</string>
|
||||
<key>LSHandlerRank</key>
|
||||
<string>Owner</string>
|
||||
<key>LSItemContentTypes</key>
|
||||
<array>
|
||||
<string>org.aegidian.oolite.save</string>
|
||||
</array>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>CFBundleTypeExtensions</key>
|
||||
<array>
|
||||
<string>oxp</string>
|
||||
</array>
|
||||
<key>CFBundleTypeIconFile</key>
|
||||
<string>oolite-expansion-document</string>
|
||||
<key>CFBundleTypeName</key>
|
||||
<string>Oolite Expansion Pack</string>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>Viewer</string>
|
||||
<key>LSHandlerRank</key>
|
||||
<string>Alternate</string>
|
||||
<key>LSTypeIsPackage</key>
|
||||
<true/>
|
||||
<key>LSItemContentTypes</key>
|
||||
<array>
|
||||
<string>org.aegidian.oolite.oxp</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>OoliteDev</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>oolite-icon</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>org.aegidian.oolite</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>OoliteDev</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>Ool8</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$OOLITE_VERSION</string>
|
||||
<key>NSMainNibFile</key>
|
||||
<string>MainMenu</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>OoliteApp</string>
|
||||
<key>UTExportedTypeDeclarations</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>UTTypeIdentifier</key>
|
||||
<string>org.aegidian.oolite.save</string>
|
||||
<key>UTTypeDescription</key>
|
||||
<string>Oolite Saved Game</string>
|
||||
<key>UTTypeConformsTo</key>
|
||||
<array>
|
||||
<string>public.text</string>
|
||||
<string>com.apple.property-list</string>
|
||||
</array>
|
||||
<key>UTTypeTagSpecification</key>
|
||||
<dict>
|
||||
<key>public.filename-extension</key>
|
||||
<array>
|
||||
<string>oolite-save</string>
|
||||
</array>
|
||||
</dict>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>UTTypeIdentifier</key>
|
||||
<string>org.aegidian.oolite.oxp</string>
|
||||
<key>UTTypeDescription</key>
|
||||
<string>Oolite Expansion Pack</string>
|
||||
<key>UTTypeConformsTo</key>
|
||||
<array>
|
||||
<string>com.apple.package</string>
|
||||
</array>
|
||||
<key>UTTypeTagSpecification</key>
|
||||
<dict>
|
||||
<key>public.filename-extension</key>
|
||||
<array>
|
||||
<string>oxp</string>
|
||||
</array>
|
||||
</dict>
|
||||
</dict>
|
||||
</array>
|
||||
<key>SmartCrashReports_CompanyName</key>
|
||||
<string>the Oolite team</string>
|
||||
<key>SmartCrashReports_EmailTicket</key>
|
||||
<string>SCR-A36F37AFFD</string>
|
||||
<key>SmartCrashReports_CommentsTemplate</key>
|
||||
<string>Please paste the last few lines of the run log here (in your home folder, open Library, then Logs, then Oolite, then Latest.log). If a large portion of the log appears relevant, consider sending a bug report by e-mail to bugs@oolite.org instead; please include the crash log if you do (Library, Logs, CrashReporter, Oolite.crash.log).</string>
|
||||
</dict>
|
||||
</plist>
|
|
@ -0,0 +1,152 @@
|
|||
/*
|
||||
|
||||
JoystickHandler.h
|
||||
|
||||
Non-functional JoystickHandler.
|
||||
This exists to reduce the amount of #ifdefs and duplicated code.
|
||||
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#define STICK_AXISUNASSIGNED -10.0
|
||||
|
||||
// Enums are used here rather than a more complex ObjC object because
|
||||
// these are required very frequently (once per frame) so must be light
|
||||
// on CPU cycles (try and avoid too many objc sendmsgs).
|
||||
// Controls that can be an axis
|
||||
enum {
|
||||
AXIS_ROLL,
|
||||
AXIS_PITCH,
|
||||
AXIS_YAW,
|
||||
AXIS_PRECISION,
|
||||
AXIS_THRUST,
|
||||
AXIS_VIEWX,
|
||||
AXIS_VIEWY,
|
||||
AXIS_end
|
||||
} axfn;
|
||||
|
||||
// Controls that can be a button
|
||||
enum {
|
||||
BUTTON_INCTHRUST,
|
||||
BUTTON_DECTHRUST,
|
||||
BUTTON_SCANNERZOOM,
|
||||
BUTTON_JETTISON,
|
||||
BUTTON_COMPASSMODE,
|
||||
BUTTON_COMMSLOG,
|
||||
BUTTON_DOCKCPU,
|
||||
BUTTON_DOCKCPUFAST,
|
||||
BUTTON_DOCKCPUTARGET,
|
||||
BUTTON_FUELINJECT,
|
||||
BUTTON_HYPERSPEED,
|
||||
BUTTON_HYPERDRIVE,
|
||||
BUTTON_GALACTICDRIVE,
|
||||
BUTTON_FIRE,
|
||||
BUTTON_ARMMISSILE,
|
||||
BUTTON_LAUNCHMISSILE,
|
||||
BUTTON_UNARM,
|
||||
#if TARGET_INCOMING_MISSILES
|
||||
BUTTON_TARGETINCOMINGMISSILE,
|
||||
#endif
|
||||
BUTTON_CYCLEMISSILE,
|
||||
BUTTON_ENERGYBOMB,
|
||||
BUTTON_ID,
|
||||
BUTTON_ECM,
|
||||
BUTTON_ESCAPE,
|
||||
BUTTON_CLOAK,
|
||||
BUTTON_PRECISION,
|
||||
BUTTON_VIEWFORWARD,
|
||||
BUTTON_VIEWAFT,
|
||||
BUTTON_VIEWPORT,
|
||||
BUTTON_VIEWSTARBOARD,
|
||||
BUTTON_end
|
||||
} butfn;
|
||||
|
||||
// Stick constants
|
||||
#define MAX_STICKS 4
|
||||
#define MAX_AXES 16
|
||||
#define MAX_REAL_BUTTONS 64
|
||||
#define MAX_HATS 0
|
||||
#define MAX_BUTTONS (MAX_REAL_BUTTONS + 4 * MAX_HATS)
|
||||
#define STICK_NOFUNCTION -1
|
||||
#define STICK_AXISUNASSIGNED -10.0
|
||||
#define STICK_PRECISIONDIV 98304 // 3 times more precise
|
||||
#define STICK_NORMALDIV 32768
|
||||
#define STICK_PRECISIONFAC (STICK_PRECISIONDIV/STICK_NORMALDIV)
|
||||
#define STICK_DEADZONE 0.05
|
||||
|
||||
// Kind of stick device (these are bits - if any more are added,
|
||||
// the next one is 4 and so on).
|
||||
#define HW_AXIS 1
|
||||
#define HW_BUTTON 2
|
||||
|
||||
// The threshold at which an axis can trigger a call back.
|
||||
// The max of abs(axis) is 32767.
|
||||
#define AXCBTHRESH 20000
|
||||
|
||||
// Dictionary keys - used in the defaults file
|
||||
#define AXIS_SETTINGS @"JoystickAxes" // NSUserDefaults
|
||||
#define BUTTON_SETTINGS @"JoystickButs" // NSUserDefaults
|
||||
#define STICK_ISAXIS @"isAxis" // YES=axis NO=button
|
||||
#define STICK_NUMBER @"stickNum" // Stick number 0 to 4
|
||||
#define STICK_AXBUT @"stickAxBt" // Axis or button number
|
||||
#define STICK_FUNCTION @"stickFunc" // Function of axis/button
|
||||
|
||||
|
||||
@interface JoystickHandler: NSObject
|
||||
{
|
||||
BOOL butstate[BUTTON_end];
|
||||
}
|
||||
|
||||
+ (id) sharedStickHandler;
|
||||
|
||||
- (int) getNumSticks;
|
||||
- (NSPoint) getRollPitchAxis;
|
||||
- (NSPoint) getViewAxis;
|
||||
- (double) getAxisState:(int)function;
|
||||
- (double) getSensitivity;
|
||||
- (const BOOL *) getAllButtonStates;
|
||||
|
||||
@end
|
|
@ -0,0 +1,98 @@
|
|||
/*
|
||||
|
||||
JoystickHandler.m
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import "JoystickHandler.h"
|
||||
|
||||
|
||||
JoystickHandler *sSharedStickHandler = nil;
|
||||
|
||||
|
||||
@implementation JoystickHandler
|
||||
|
||||
+ (id) sharedStickHandler
|
||||
{
|
||||
if (sSharedStickHandler == nil) sSharedStickHandler = [[JoystickHandler alloc] init];
|
||||
return sSharedStickHandler;
|
||||
}
|
||||
|
||||
|
||||
- (int) getNumSticks
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
- (NSPoint) getRollPitchAxis
|
||||
{
|
||||
return NSZeroPoint;
|
||||
}
|
||||
|
||||
|
||||
- (NSPoint) getViewAxis
|
||||
{
|
||||
return NSZeroPoint;
|
||||
}
|
||||
|
||||
|
||||
- (double) getAxisState:(int)function
|
||||
{
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
|
||||
- (double) getSensitivity
|
||||
{
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
|
||||
- (const BOOL *) getAllButtonStates
|
||||
{
|
||||
return butstate;
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,200 @@
|
|||
/*
|
||||
|
||||
MyOpenGLView.h
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOCocoa.h"
|
||||
#import "OOOpenGL.h"
|
||||
|
||||
#ifdef GNUSTEP
|
||||
#include <SDL/SDL.h>
|
||||
#endif
|
||||
|
||||
#define MAX_CLEAR_DEPTH 100000000.0
|
||||
#define MAX_CLEAR_DEPTH2 10000000000000000.0
|
||||
// 100 000 km.
|
||||
|
||||
#define NUM_KEYS 320
|
||||
|
||||
#define MOUSE_DOUBLE_CLICK_INTERVAL 0.40
|
||||
|
||||
@class Entity, GameController;
|
||||
@class JoystickHandler;
|
||||
|
||||
#ifdef GNUSTEP
|
||||
#define OpenGLViewSuperClass NSObject
|
||||
#else
|
||||
#define OpenGLViewSuperClass NSOpenGLView
|
||||
#endif
|
||||
|
||||
enum GameViewKeys
|
||||
{
|
||||
gvArrowKeyUp = 255,
|
||||
gvArrowKeyDown = 254,
|
||||
gvArrowKeyLeft = 253,
|
||||
gvArrowKeyRight = 252,
|
||||
gvFunctionKey1 = 241,
|
||||
gvFunctionKey2 = 242,
|
||||
gvFunctionKey3 = 243,
|
||||
gvFunctionKey4 = 244,
|
||||
gvFunctionKey5 = 245,
|
||||
gvFunctionKey6 = 246,
|
||||
gvFunctionKey7 = 247,
|
||||
gvFunctionKey8 = 248,
|
||||
gvFunctionKey9 = 249,
|
||||
gvFunctionKey10 = 250,
|
||||
gvFunctionKey11 = 251,
|
||||
gvMouseLeftButton = 301,
|
||||
gvMouseDoubleClick = 303,
|
||||
gvHomeKey = 302,
|
||||
gvNumberKey0 = 48,
|
||||
gvNumberKey1 = 49,
|
||||
gvNumberKey2 = 50,
|
||||
gvNumberKey3 = 51,
|
||||
gvNumberKey4 = 52,
|
||||
gvNumberKey5 = 53,
|
||||
gvNumberKey6 = 54,
|
||||
gvNumberKey7 = 55,
|
||||
gvNumberKey8 = 56,
|
||||
gvNumberKey9 = 57
|
||||
};
|
||||
|
||||
enum StringInput
|
||||
{
|
||||
gvStringInputNo = 0,
|
||||
gvStringInputAlpha = 1,
|
||||
gvStringInputAll = 2
|
||||
};
|
||||
|
||||
extern int debug;
|
||||
|
||||
@interface MyOpenGLView : OpenGLViewSuperClass
|
||||
{
|
||||
GameController *gameController;
|
||||
|
||||
BOOL keys[NUM_KEYS];
|
||||
BOOL supressKeys; // DJS
|
||||
|
||||
BOOL opt, ctrl, command, shift;
|
||||
BOOL allowingStringInput;
|
||||
BOOL isAlphabetKeyDown;
|
||||
|
||||
int keycodetrans[255];
|
||||
|
||||
BOOL m_glContextInitialized;
|
||||
NSPoint mouseDragStartPoint;
|
||||
|
||||
NSTimeInterval timeIntervalAtLastClick;
|
||||
BOOL doubleClick;
|
||||
|
||||
NSMutableString *typedString;
|
||||
|
||||
NSPoint virtualJoystickPosition;
|
||||
|
||||
NSSize viewSize;
|
||||
GLfloat display_z;
|
||||
|
||||
#ifdef GNUSTEP
|
||||
double squareX,squareY;
|
||||
NSRect bounds;
|
||||
|
||||
// Full screen sizes
|
||||
NSMutableArray *screenSizes;
|
||||
int currentSize;
|
||||
BOOL fullScreen;
|
||||
|
||||
// Windowed mode
|
||||
NSSize currentWindowSize;
|
||||
SDL_Surface* surface;
|
||||
#endif
|
||||
JoystickHandler *stickHandler;
|
||||
}
|
||||
|
||||
|
||||
- (void) setStringInput: (enum StringInput) value;
|
||||
- (void) allowStringInput: (BOOL) value;
|
||||
- (enum StringInput) allowingStringInput;
|
||||
- (NSString *) typedString;
|
||||
- (void) resetTypedString;
|
||||
- (void) setTypedString:(NSString*) value;
|
||||
|
||||
- (NSSize) viewSize;
|
||||
- (GLfloat) display_z;
|
||||
|
||||
- (GameController *) gameController;
|
||||
- (void) setGameController:(GameController *) controller;
|
||||
|
||||
- (void) initialiseGLWithSize:(NSSize) v_size;
|
||||
|
||||
- (void) drawRect:(NSRect)rect;
|
||||
- (void) updateScreen;
|
||||
|
||||
- (void) snapShot;
|
||||
|
||||
#ifndef GNUSTEP
|
||||
- (void)mouseDown:(NSEvent *)theEvent;
|
||||
- (void)mouseUp:(NSEvent *)theEvent;
|
||||
#else
|
||||
- (NSRect) bounds;
|
||||
- (void) display;
|
||||
+ (NSMutableDictionary *) getNativeSize;
|
||||
|
||||
- (void) setFullScreenMode:(BOOL)fsm;
|
||||
- (BOOL) inFullScreenMode;
|
||||
- (void) toggleScreenMode;
|
||||
- (void) setDisplayMode:(int)mode fullScreen:(BOOL)fsm;
|
||||
|
||||
- (int) indexOfCurrentSize;
|
||||
- (void) setScreenSize: (int)sizeIndex;
|
||||
- (NSMutableArray *)getScreenSizeArray;
|
||||
- (void) populateFullScreenModelist;
|
||||
- (NSSize) modeAsSize: (int)sizeIndex;
|
||||
- (void) saveWindowSize: (NSSize) windowSize;
|
||||
- (NSSize) loadWindowSize;
|
||||
- (int) loadFullscreenSettings;
|
||||
- (int) findDisplayModeForWidth: (unsigned int) d_width Height:(unsigned int) d_height
|
||||
Refresh: (unsigned int)d_refresh;
|
||||
- (NSSize) currentScreenSize;
|
||||
|
||||
- (void) pollControls: (id)sender;
|
||||
- (void) handleStringInput: (SDL_KeyboardEvent *) kbd_event; // DJS
|
||||
#endif
|
||||
- (JoystickHandler *)getStickHandler; // DJS
|
||||
|
||||
- (void) setVirtualJoystick:(double) vmx :(double) vmy;
|
||||
- (NSPoint) virtualJoystickPosition;
|
||||
|
||||
- (void) clearKeys;
|
||||
- (void) clearMouse;
|
||||
- (BOOL) isAlphabetKeyDown;
|
||||
- (void) supressKeysUntilKeyUp; // DJS
|
||||
- (BOOL) isDown: (int) key;
|
||||
- (BOOL) isOptDown;
|
||||
- (BOOL) isCtrlDown;
|
||||
- (BOOL) isCommandDown;
|
||||
- (BOOL) isShiftDown;
|
||||
- (int) numKeys;
|
||||
|
||||
// Check current state of shift key rather than relying on last event.
|
||||
- (BOOL)pollShiftKey;
|
||||
|
||||
@end
|
|
@ -0,0 +1,709 @@
|
|||
/*
|
||||
|
||||
MyOpenGLView.m
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
*/
|
||||
|
||||
#import "MyOpenGLView.h"
|
||||
|
||||
#import "GameController.h"
|
||||
#import "Universe.h"
|
||||
#import "Entity.h"
|
||||
#import "PlanetEntity.h"
|
||||
#import "ResourceManager.h"
|
||||
#import "GuiDisplayGen.h"
|
||||
#import <Carbon/Carbon.h>
|
||||
#import "JoystickHandler.h"
|
||||
|
||||
|
||||
static NSString * kOOLogKeyCodeOutOfRange = @"input.keyMapping.codeOutOfRange";
|
||||
static NSString * kOOLogKeyUp = @"input.keyMapping.keyPress.keyUp";
|
||||
static NSString * kOOLogKeyDown = @"input.keyMapping.keyPress.keyDown";
|
||||
|
||||
|
||||
@interface MyOpenGLView(Internal)
|
||||
|
||||
- (int) translateKeyCode: (int) input;
|
||||
- (void)performLateSetup;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation MyOpenGLView
|
||||
|
||||
- (id) initWithFrame:(NSRect)frameRect
|
||||
{
|
||||
// Pixel Format Attributes for the View-based (non-FullScreen) NSOpenGLContext
|
||||
NSOpenGLPixelFormatAttribute attrs[] =
|
||||
{
|
||||
// // Specify that we want a full-screen OpenGL context.
|
||||
// NSOpenGLPFAFullScreen,
|
||||
// and that we want a windowed OpenGL context.
|
||||
NSOpenGLPFAWindow,
|
||||
|
||||
// We may be on a multi-display system (and each screen may be driven by a different renderer), so we need to specify which screen we want to take over.
|
||||
// For this demo, we'll specify the main screen.
|
||||
NSOpenGLPFAScreenMask, CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay),
|
||||
|
||||
// Specifying "NoRecovery" gives us a context that cannot fall back to the software renderer.
|
||||
//This makes the View-based context a compatible with the fullscreen context, enabling us to use the "shareContext"
|
||||
// feature to share textures, display lists, and other OpenGL objects between the two.
|
||||
NSOpenGLPFANoRecovery,
|
||||
|
||||
// Attributes Common to FullScreen and non-FullScreen
|
||||
NSOpenGLPFACompliant,
|
||||
|
||||
NSOpenGLPFAColorSize, 32,
|
||||
NSOpenGLPFADepthSize, 32,
|
||||
NSOpenGLPFADoubleBuffer,
|
||||
NSOpenGLPFAAccelerated,
|
||||
0
|
||||
};
|
||||
|
||||
// Create our non-FullScreen pixel format.
|
||||
NSOpenGLPixelFormat* pixelFormat = [[[NSOpenGLPixelFormat alloc] initWithAttributes:attrs] autorelease];
|
||||
|
||||
self = [super initWithFrame:frameRect pixelFormat:pixelFormat];
|
||||
|
||||
virtualJoystickPosition = NSMakePoint(0.0,0.0);
|
||||
|
||||
typedString = [[NSMutableString alloc] initWithString:@""];
|
||||
allowingStringInput = gvStringInputNo;
|
||||
isAlphabetKeyDown = NO;
|
||||
|
||||
timeIntervalAtLastClick = [NSDate timeIntervalSinceReferenceDate];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (void) dealloc
|
||||
{
|
||||
if (typedString)
|
||||
[typedString release];
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
- (void) setStringInput: (enum StringInput) value
|
||||
{
|
||||
allowingStringInput = value;
|
||||
}
|
||||
|
||||
|
||||
- (void) allowStringInput: (BOOL) value
|
||||
{
|
||||
if (value)
|
||||
allowingStringInput = gvStringInputAlpha;
|
||||
else
|
||||
allowingStringInput = gvStringInputNo;
|
||||
}
|
||||
|
||||
-(enum StringInput) allowingStringInput
|
||||
{
|
||||
return allowingStringInput;
|
||||
}
|
||||
|
||||
|
||||
- (NSString *) typedString
|
||||
{
|
||||
return typedString;
|
||||
}
|
||||
|
||||
|
||||
- (void) resetTypedString
|
||||
{
|
||||
[typedString setString:@""];
|
||||
}
|
||||
|
||||
|
||||
- (void) setTypedString:(NSString*) value
|
||||
{
|
||||
[typedString setString:value];
|
||||
}
|
||||
|
||||
|
||||
- (NSSize) viewSize
|
||||
{
|
||||
return viewSize;
|
||||
}
|
||||
|
||||
|
||||
- (GLfloat) display_z
|
||||
{
|
||||
return display_z;
|
||||
}
|
||||
|
||||
|
||||
- (GameController *)gameController
|
||||
{
|
||||
return gameController;
|
||||
}
|
||||
|
||||
|
||||
- (void) setGameController:(GameController *) controller
|
||||
{
|
||||
gameController = controller;
|
||||
}
|
||||
|
||||
|
||||
- (void) updateScreen
|
||||
{
|
||||
[self drawRect:NSMakeRect(0, 0, viewSize.width, viewSize.height)];
|
||||
}
|
||||
|
||||
|
||||
- (void) drawRect:(NSRect)rect
|
||||
{
|
||||
if ((viewSize.width != [self frame].size.width)||(viewSize.height != [self frame].size.height)) // resized
|
||||
{
|
||||
m_glContextInitialized = NO;
|
||||
viewSize = [self frame].size;
|
||||
}
|
||||
|
||||
if (!m_glContextInitialized) [self initialiseGLWithSize:viewSize];
|
||||
|
||||
// do all the drawing!
|
||||
if (UNIVERSE != nil) [UNIVERSE drawUniverse];
|
||||
else
|
||||
{
|
||||
// not set up yet, draw a black screen
|
||||
glClearColor(0.0, 0.0, 0.0, 0.0);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
}
|
||||
|
||||
[[self openGLContext] flushBuffer];
|
||||
}
|
||||
|
||||
|
||||
- (void) initialiseGLWithSize:(NSSize) v_size
|
||||
{
|
||||
GLfloat sun_ambient[] = {0.0, 0.0, 0.0, 1.0};
|
||||
GLfloat sun_diffuse[] = {1.0, 1.0, 1.0, 1.0};
|
||||
GLfloat sun_specular[] = {1.0, 1.0, 1.0, 1.0};
|
||||
GLfloat sun_center_position[] = {4000000.0, 0.0, 0.0, 1.0};
|
||||
GLfloat stars_ambient[] = {0.25, 0.2, 0.25, 1.0};
|
||||
|
||||
viewSize = v_size;
|
||||
if (viewSize.width/viewSize.height > 4.0/3.0)
|
||||
display_z = 480.0 * viewSize.width/viewSize.height;
|
||||
else
|
||||
display_z = 640.0;
|
||||
|
||||
float ratio = 0.5;
|
||||
float aspect = viewSize.height/viewSize.width;
|
||||
|
||||
glShadeModel(GL_FLAT);
|
||||
glClearColor(0.0, 0.0, 0.0, 0.0);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
[[self openGLContext] flushBuffer];
|
||||
|
||||
glClearDepth(MAX_CLEAR_DEPTH);
|
||||
glViewport( 0, 0, viewSize.width, viewSize.height);
|
||||
|
||||
glMatrixMode(GL_PROJECTION);
|
||||
glLoadIdentity(); // reset matrix
|
||||
glFrustum( -ratio, ratio, -aspect*ratio, aspect*ratio, 1.0, MAX_CLEAR_DEPTH); // set projection matrix
|
||||
|
||||
glMatrixMode( GL_MODELVIEW);
|
||||
|
||||
glEnable( GL_DEPTH_TEST); // depth buffer
|
||||
glDepthFunc( GL_LESS); // depth buffer
|
||||
|
||||
glFrontFace( GL_CCW); // face culling - front faces are AntiClockwise!
|
||||
glCullFace( GL_BACK); // face culling
|
||||
glEnable( GL_CULL_FACE); // face culling
|
||||
|
||||
glEnable( GL_BLEND); // alpha blending
|
||||
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // alpha blending
|
||||
|
||||
if (UNIVERSE)
|
||||
{
|
||||
[UNIVERSE setLighting];
|
||||
}
|
||||
else
|
||||
{
|
||||
glLightfv(GL_LIGHT1, GL_AMBIENT, sun_ambient);
|
||||
glLightfv(GL_LIGHT1, GL_SPECULAR, sun_specular);
|
||||
glLightfv(GL_LIGHT1, GL_DIFFUSE, sun_diffuse);
|
||||
glLightfv(GL_LIGHT1, GL_POSITION, sun_center_position);
|
||||
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, stars_ambient);
|
||||
|
||||
glEnable(GL_LIGHT1); // lighting
|
||||
|
||||
}
|
||||
glEnable(GL_LIGHTING); // lighting
|
||||
|
||||
|
||||
// world's simplest OpenGL optimisations...
|
||||
#if GL_APPLE_transform_hint
|
||||
glHint(GL_TRANSFORM_HINT_APPLE, GL_FASTEST);
|
||||
#endif
|
||||
|
||||
glDisable(GL_NORMALIZE);
|
||||
glDisable(GL_RESCALE_NORMAL);
|
||||
|
||||
m_glContextInitialized = YES;
|
||||
}
|
||||
|
||||
|
||||
- (void) snapShot
|
||||
{
|
||||
int w = viewSize.width;
|
||||
int h = viewSize.height;
|
||||
|
||||
if (w & 3)
|
||||
w = w + 4 - (w & 3);
|
||||
|
||||
long nPixels = w * h + 1;
|
||||
|
||||
unsigned char *red = (unsigned char *) malloc( nPixels);
|
||||
unsigned char *green = (unsigned char *) malloc( nPixels);
|
||||
unsigned char *blue = (unsigned char *) malloc( nPixels);
|
||||
|
||||
NSString *filepath = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
|
||||
int imageNo = 0;
|
||||
NSString *pathToPic = nil;
|
||||
|
||||
do
|
||||
{
|
||||
imageNo++;
|
||||
pathToPic = [filepath stringByAppendingPathComponent:[NSString stringWithFormat:@"oolite-%03d.png",imageNo]];
|
||||
} while ([[NSFileManager defaultManager] fileExistsAtPath:pathToPic]);
|
||||
|
||||
OOLog(@"snapshot", @">>>>> Snapshot %d x %d file path chosen = %@", w, h, pathToPic);
|
||||
|
||||
NSBitmapImageRep* bitmapRep =
|
||||
[[NSBitmapImageRep alloc]
|
||||
initWithBitmapDataPlanes:NULL // --> let the class allocate it
|
||||
pixelsWide: w
|
||||
pixelsHigh: h
|
||||
bitsPerSample: 8 // each component is 8 bits (1 byte)
|
||||
samplesPerPixel: 3 // number of components (R, G, B)
|
||||
hasAlpha: NO // no transparency
|
||||
isPlanar: NO // data integrated into single plane
|
||||
colorSpaceName: NSDeviceRGBColorSpace
|
||||
bytesPerRow: 3*w // can no longer let the class figure it out
|
||||
bitsPerPixel: 24 // can no longer let the class figure it out
|
||||
];
|
||||
|
||||
unsigned char *pixels = [bitmapRep bitmapData];
|
||||
|
||||
glReadPixels(0,0, w,h, GL_RED, GL_UNSIGNED_BYTE, red);
|
||||
glReadPixels(0,0, w,h, GL_GREEN, GL_UNSIGNED_BYTE, green);
|
||||
glReadPixels(0,0, w,h, GL_BLUE, GL_UNSIGNED_BYTE, blue);
|
||||
|
||||
int x,y;
|
||||
for (y = 0; y < h; y++)
|
||||
{
|
||||
long index = (h - y - 1)*w;
|
||||
for (x = 0; x < w; x++) // set bitmap pixels
|
||||
{
|
||||
*pixels++ = red[index];
|
||||
*pixels++ = green[index];
|
||||
*pixels++ = blue[index++];
|
||||
}
|
||||
}
|
||||
|
||||
[[bitmapRep representationUsingType:NSPNGFileType properties:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSImageInterlaced, NULL]]
|
||||
writeToFile:pathToPic atomically:YES]; // save PNG representation of image
|
||||
|
||||
// free allocated objects and memory
|
||||
[bitmapRep release];
|
||||
free(red);
|
||||
free(green);
|
||||
free(blue);
|
||||
|
||||
}
|
||||
|
||||
|
||||
- (BOOL) acceptsFirstResponder
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
- (void) keyUp:(NSEvent *)theEvent
|
||||
{
|
||||
NSString *stringValue = nil;
|
||||
int key;
|
||||
int keycode;
|
||||
|
||||
stringValue = [theEvent charactersIgnoringModifiers];
|
||||
|
||||
/* Bug: exception when releasing accent key.
|
||||
Analysis: Dead keys (accents and similar) return an empty string.
|
||||
Fix: reject zero-length strings. This is the Wrong Thing - we should
|
||||
really be using KeyTranslate()/UCKeyTranslate() to find out what the
|
||||
string would be if you pressed the key and then space.
|
||||
-- Ahruman 20070714
|
||||
*/
|
||||
if ([stringValue length] < 1) return;
|
||||
|
||||
key = [stringValue characterAtIndex:0];
|
||||
keycode = [theEvent keyCode] & 255;
|
||||
|
||||
supressKeys = NO;
|
||||
|
||||
key = keycodetrans[keycode]; // retrieve the character we got for pressing the hardware at key location 'keycode'
|
||||
|
||||
OOLog(kOOLogKeyUp, @"Key up: stringValue = \"%@\", keyCode = %d, key = %u", stringValue, keycode, key);
|
||||
|
||||
isAlphabetKeyDown = NO;
|
||||
if ((key >= 0)&&(key < [self numKeys])&&(keys[key]))
|
||||
{
|
||||
keys[key] = NO;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (key > [self numKeys])
|
||||
OOLog(kOOLogKeyCodeOutOfRange, @"Translated key: %d out of range", key);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void) keyDown:(NSEvent *)theEvent
|
||||
{
|
||||
NSString *stringValue = nil;
|
||||
int key;
|
||||
int keycode;
|
||||
|
||||
stringValue = [theEvent charactersIgnoringModifiers];
|
||||
|
||||
/* Bug: exception when pressing accent key.
|
||||
Analysis: Dead keys (accents and similar) return an empty string.
|
||||
Fix: reject zero-length strings. This is the Wrong Thing - we should
|
||||
really be using KeyTranslate()/UCKeyTranslate() to find out what the
|
||||
string would be if you pressed the key and then space.
|
||||
-- Ahruman 20070714
|
||||
*/
|
||||
if ([stringValue length] < 1) return;
|
||||
|
||||
key = [stringValue characterAtIndex:0];
|
||||
keycode = [theEvent keyCode] & 255;
|
||||
|
||||
key = [self translateKeyCode:key];
|
||||
|
||||
OOLog(kOOLogKeyDown, @"Key down: stringValue = \"%@\", keyCode = %d, key = %u", stringValue, keycode, key);
|
||||
|
||||
keycodetrans[keycode] = key; // record the chracter we got for pressing the hardware at key location 'keycode'
|
||||
|
||||
if ((key >= 0)&&(key < [self numKeys])&&(!keys[key]))
|
||||
{
|
||||
keys[key] = YES;
|
||||
|
||||
if (allowingStringInput)
|
||||
{
|
||||
// limited input for planet find screen
|
||||
if (allowingStringInput == gvStringInputAlpha)
|
||||
{
|
||||
if (((key > 64)&&(key < 91))||((key > 96)&&(key < 123)))
|
||||
{
|
||||
// alphanumeric
|
||||
isAlphabetKeyDown = YES;
|
||||
// convert to lowercase
|
||||
[typedString appendFormat:@"%c", (key | 64)];
|
||||
}
|
||||
else
|
||||
isAlphabetKeyDown = NO;
|
||||
if (key == NSDeleteCharacter)
|
||||
{
|
||||
//delete
|
||||
[typedString setString:@""];
|
||||
}
|
||||
}
|
||||
|
||||
// full input for load-save screen
|
||||
if (allowingStringInput == gvStringInputAll)
|
||||
{
|
||||
if ((key > 31)&&(key < 123))
|
||||
{
|
||||
// alphanumeric
|
||||
isAlphabetKeyDown = YES;
|
||||
// convert to lowercase
|
||||
[typedString appendFormat:@"%c", key];
|
||||
}
|
||||
else
|
||||
isAlphabetKeyDown = NO;
|
||||
if ((key == NSDeleteCharacter) && [typedString length])
|
||||
{
|
||||
//delete
|
||||
[typedString deleteCharactersInRange:NSMakeRange([typedString length] - 1, 1)];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (key > [self numKeys])
|
||||
OOLog(kOOLogKeyCodeOutOfRange, @"Translated key: %d out of range", key);
|
||||
}
|
||||
}
|
||||
|
||||
/* Capture shift, ctrl, opt and command press & release */
|
||||
- (void)flagsChanged:(NSEvent *)theEvent
|
||||
{
|
||||
int flags = [theEvent modifierFlags];
|
||||
opt = (flags & NSAlternateKeyMask) ? YES : NO;
|
||||
ctrl = (flags & NSControlKeyMask) ? YES : NO;
|
||||
command = (flags & NSCommandKeyMask) ? YES : NO;
|
||||
shift = ( flags & NSShiftKeyMask ) ? YES : NO;
|
||||
|
||||
}
|
||||
|
||||
|
||||
- (void)mouseDown:(NSEvent *)theEvent
|
||||
{
|
||||
if (doubleClick)
|
||||
{
|
||||
doubleClick = NO;
|
||||
keys[gvMouseDoubleClick] = NO;
|
||||
}
|
||||
keys[gvMouseLeftButton] = YES; // 'a' down
|
||||
}
|
||||
|
||||
|
||||
- (void)mouseUp:(NSEvent *)theEvent
|
||||
{
|
||||
NSTimeInterval timeBetweenClicks = [NSDate timeIntervalSinceReferenceDate] - timeIntervalAtLastClick;
|
||||
timeIntervalAtLastClick += timeBetweenClicks;
|
||||
|
||||
if (!doubleClick)
|
||||
{
|
||||
doubleClick = (timeBetweenClicks < MOUSE_DOUBLE_CLICK_INTERVAL); // One fifth of a second
|
||||
keys[gvMouseDoubleClick] = doubleClick;
|
||||
}
|
||||
|
||||
keys[gvMouseLeftButton] = NO; // 'a' up
|
||||
}
|
||||
|
||||
|
||||
- (void)mouseMoved:(NSEvent *)theEvent
|
||||
{
|
||||
double mx = [theEvent locationInWindow].x - viewSize.width/2.0;
|
||||
double my = [theEvent locationInWindow].y - viewSize.height/2.0;
|
||||
|
||||
if (display_z > 640.0)
|
||||
{
|
||||
mx /= viewSize.width * MAIN_GUI_PIXEL_WIDTH / display_z;
|
||||
my /= viewSize.height;
|
||||
}
|
||||
else
|
||||
{
|
||||
mx /= MAIN_GUI_PIXEL_WIDTH * viewSize.width / 640.0;
|
||||
my /= MAIN_GUI_PIXEL_HEIGHT * viewSize.width / 640.0;
|
||||
}
|
||||
|
||||
[self setVirtualJoystick:mx :-my];
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////
|
||||
/* Turn the Cocoa ArrowKeys into our arrow key constants. */
|
||||
- (int) translateKeyCode: (int) input
|
||||
{
|
||||
int key = input;
|
||||
switch ( input )
|
||||
{
|
||||
case NSUpArrowFunctionKey:
|
||||
key = gvArrowKeyUp;
|
||||
break;
|
||||
|
||||
case NSDownArrowFunctionKey:
|
||||
key = gvArrowKeyDown;
|
||||
break;
|
||||
|
||||
case NSLeftArrowFunctionKey:
|
||||
key = gvArrowKeyLeft;
|
||||
break;
|
||||
|
||||
case NSRightArrowFunctionKey:
|
||||
key = gvArrowKeyRight;
|
||||
break;
|
||||
|
||||
case NSF1FunctionKey:
|
||||
key = gvFunctionKey1;
|
||||
break;
|
||||
|
||||
case NSF2FunctionKey:
|
||||
key = gvFunctionKey2;
|
||||
break;
|
||||
|
||||
case NSF3FunctionKey:
|
||||
key = gvFunctionKey3;
|
||||
break;
|
||||
|
||||
case NSF4FunctionKey:
|
||||
key = gvFunctionKey4;
|
||||
break;
|
||||
|
||||
case NSF5FunctionKey:
|
||||
key = gvFunctionKey5;
|
||||
break;
|
||||
|
||||
case NSF6FunctionKey:
|
||||
key = gvFunctionKey6;
|
||||
break;
|
||||
|
||||
case NSF7FunctionKey:
|
||||
key = gvFunctionKey7;
|
||||
break;
|
||||
|
||||
case NSF8FunctionKey:
|
||||
key = gvFunctionKey8;
|
||||
break;
|
||||
|
||||
case NSF9FunctionKey:
|
||||
key = gvFunctionKey9;
|
||||
break;
|
||||
|
||||
case NSF10FunctionKey:
|
||||
key = gvFunctionKey10;
|
||||
break;
|
||||
|
||||
case NSF11FunctionKey:
|
||||
key = gvFunctionKey11;
|
||||
break;
|
||||
|
||||
case NSHomeFunctionKey:
|
||||
key = gvHomeKey;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
|
||||
- (JoystickHandler *)getStickHandler
|
||||
{
|
||||
return [JoystickHandler sharedStickHandler];
|
||||
}
|
||||
|
||||
|
||||
- (void) setVirtualJoystick:(double) vmx :(double) vmy
|
||||
{
|
||||
virtualJoystickPosition.x = vmx;
|
||||
virtualJoystickPosition.y = vmy;
|
||||
}
|
||||
|
||||
|
||||
- (NSPoint) virtualJoystickPosition
|
||||
{
|
||||
return virtualJoystickPosition;
|
||||
}
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////
|
||||
|
||||
- (void) clearKeys
|
||||
{
|
||||
int i;
|
||||
for (i = 0; i < [self numKeys]; i++)
|
||||
keys[i] = NO;
|
||||
}
|
||||
|
||||
|
||||
- (void) clearMouse
|
||||
{
|
||||
keys[gvMouseDoubleClick] = NO;
|
||||
keys[gvMouseLeftButton] = NO;
|
||||
doubleClick = NO;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL) isAlphabetKeyDown
|
||||
{
|
||||
return isAlphabetKeyDown = NO;;
|
||||
}
|
||||
|
||||
// DJS: When entering submenus in the gui, it is not helpful if the
|
||||
// key down that brought you into the submenu is still registered
|
||||
// as down when we're in. This makes isDown return NO until a key up
|
||||
// event has been received from SDL.
|
||||
- (void) supressKeysUntilKeyUp
|
||||
{
|
||||
if (keys[gvMouseDoubleClick] == NO)
|
||||
{
|
||||
supressKeys = YES;
|
||||
[self clearKeys];
|
||||
}
|
||||
else
|
||||
{
|
||||
[self clearMouse];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (BOOL) isDown: (int) key
|
||||
{
|
||||
if( supressKeys )
|
||||
return NO;
|
||||
if ( key < 0 )
|
||||
return NO;
|
||||
if ( key >= [self numKeys] )
|
||||
return NO;
|
||||
return keys[key];
|
||||
}
|
||||
|
||||
|
||||
- (BOOL) isOptDown
|
||||
{
|
||||
return opt;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL) isCtrlDown
|
||||
{
|
||||
return ctrl;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL) isCommandDown
|
||||
{
|
||||
return command;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL) isShiftDown
|
||||
{
|
||||
return shift;
|
||||
}
|
||||
|
||||
|
||||
- (int) numKeys
|
||||
{
|
||||
return NUM_KEYS;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)pollShiftKey
|
||||
{
|
||||
#define KEYMAP_GET(m, index) ((((uint8_t*)(m))[(index) >> 3] & (1L << ((index) & 7))) ? 1 : 0)
|
||||
|
||||
KeyMap map;
|
||||
|
||||
GetKeys(map);
|
||||
return KEYMAP_GET(map, 56) || KEYMAP_GET(map, 60); // Left shift or right shift -- although 60 shouldn't occur.
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,70 @@
|
|||
/*
|
||||
|
||||
OOCABufferedSound.h
|
||||
|
||||
Subclass of OOSound playing from an in-memory buffer.
|
||||
|
||||
This class is an implementation detail. Do not use it directly; use OOSound.
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "OOCASound.h"
|
||||
|
||||
@class OOCASoundDecoder;
|
||||
|
||||
|
||||
@interface OOCABufferedSound: OOSound
|
||||
{
|
||||
float *_bufferL,
|
||||
*_bufferR;
|
||||
size_t _size;
|
||||
Float64 _sampleRate;
|
||||
NSString *_name;
|
||||
BOOL _stereo;
|
||||
}
|
||||
|
||||
- (id)initWithDecoder:(OOCASoundDecoder *)inDecoder;
|
||||
|
||||
@end
|
|
@ -0,0 +1,217 @@
|
|||
/*
|
||||
|
||||
OOCABufferedSound.m
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOCASoundInternal.h"
|
||||
#import "OOCASoundDecoder.h"
|
||||
|
||||
|
||||
@interface OOCABufferedSound (Private)
|
||||
|
||||
- (BOOL)bufferSound:(NSString *)inPath;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation OOCABufferedSound
|
||||
|
||||
#pragma mark NSObject
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
if (_bufferL) free(_bufferL);
|
||||
if (_stereo) _bufferR = NULL;
|
||||
else if (_bufferR) free(_bufferR);
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
- (NSString *)description
|
||||
{
|
||||
return [NSString stringWithFormat:@"<%@ %p>{\"%@\", %s, %g Hz, %u bytes}", [self className], self, [self name], _stereo ? "stereo" : "mono", _sampleRate, _size * sizeof (float) * (_stereo ? 2 : 1)];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark OOSound
|
||||
|
||||
- (NSString *)name
|
||||
{
|
||||
return _name;
|
||||
}
|
||||
|
||||
|
||||
- (void)play
|
||||
{
|
||||
[[OOSoundMixer sharedMixer] playSound:self];
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)getAudioStreamBasicDescription:(AudioStreamBasicDescription *)outFormat
|
||||
{
|
||||
assert(NULL != outFormat);
|
||||
|
||||
outFormat->mSampleRate = _sampleRate;
|
||||
outFormat->mFormatID = kAudioFormatLinearPCM;
|
||||
outFormat->mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
|
||||
outFormat->mBytesPerPacket = sizeof (float);
|
||||
outFormat->mFramesPerPacket = 1;
|
||||
outFormat->mBytesPerFrame = sizeof (float);
|
||||
outFormat->mChannelsPerFrame = 2;
|
||||
outFormat->mBitsPerChannel = sizeof (float) * 8;
|
||||
outFormat->mReserved = 0;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
// Context is (offset << 1) | loop. Offset is initially 0.
|
||||
- (BOOL)prepareToPlayWithContext:(OOCASoundRenderContext *)outContext looped:(BOOL)inLoop
|
||||
{
|
||||
*outContext = inLoop ? 1 : 0;
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
- (OSStatus)renderWithFlags:(AudioUnitRenderActionFlags *)ioFlags frames:(UInt32)inNumFrames context:(OOCASoundRenderContext *)ioContext data:(AudioBufferList *)ioData
|
||||
{
|
||||
size_t toCopy, remaining, underflow, offset;
|
||||
BOOL loop, done = NO;
|
||||
|
||||
loop = (*ioContext) & 1;
|
||||
offset = (*ioContext) >> 1;
|
||||
assert (ioData->mNumberBuffers == 2);
|
||||
|
||||
if (offset < _size)
|
||||
{
|
||||
remaining = _size - offset;
|
||||
if (remaining < inNumFrames)
|
||||
{
|
||||
toCopy = remaining;
|
||||
underflow = inNumFrames - remaining;
|
||||
}
|
||||
else
|
||||
{
|
||||
toCopy = inNumFrames;
|
||||
underflow = 0;
|
||||
}
|
||||
|
||||
bcopy(_bufferL + offset, ioData->mBuffers[0].mData, toCopy * sizeof (float));
|
||||
bcopy(_bufferR + offset, ioData->mBuffers[1].mData, toCopy * sizeof (float));
|
||||
|
||||
if (underflow && loop)
|
||||
{
|
||||
offset = toCopy;
|
||||
toCopy = inNumFrames - toCopy;
|
||||
if (_size < toCopy) toCopy = _size;
|
||||
|
||||
bcopy(_bufferL, ((float *)ioData->mBuffers[0].mData) + offset, toCopy * sizeof (float));
|
||||
bcopy(_bufferR, ((float *)ioData->mBuffers[1].mData) + offset, toCopy * sizeof (float));
|
||||
|
||||
underflow -= toCopy;
|
||||
offset = 0;
|
||||
}
|
||||
|
||||
*ioContext = ((offset + toCopy) << 1) | loop;
|
||||
}
|
||||
else
|
||||
{
|
||||
toCopy = 0;
|
||||
underflow = inNumFrames;
|
||||
*ioFlags |= kAudioUnitRenderAction_OutputIsSilence;
|
||||
done = YES;
|
||||
}
|
||||
|
||||
if (underflow)
|
||||
{
|
||||
bzero(ioData->mBuffers[0].mData + toCopy, underflow * sizeof (float));
|
||||
bzero(ioData->mBuffers[1].mData + toCopy, underflow * sizeof (float));
|
||||
}
|
||||
|
||||
return done ? endOfDataReached : noErr;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark OOCABufferedSound
|
||||
|
||||
- (id)initWithDecoder:(OOCASoundDecoder *)inDecoder
|
||||
{
|
||||
BOOL OK = YES;
|
||||
|
||||
assert(gOOSoundSetUp);
|
||||
if (gOOSoundBroken || nil == inDecoder) OK = NO;
|
||||
|
||||
if (OK)
|
||||
{
|
||||
self = [super init];
|
||||
if (nil == self) OK = NO;
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
_name = [[inDecoder name] copy];
|
||||
_sampleRate = [inDecoder sampleRate];
|
||||
if ([inDecoder isStereo])
|
||||
{
|
||||
OK = [inDecoder readStereoCreatingLeftBuffer:&_bufferL rightBuffer:&_bufferR withFrameCount:&_size];
|
||||
_stereo = YES;
|
||||
}
|
||||
else
|
||||
{
|
||||
OK = [inDecoder readMonoCreatingBuffer:&_bufferL withFrameCount:&_size];
|
||||
_bufferR = _bufferL;
|
||||
}
|
||||
}
|
||||
|
||||
if (!OK)
|
||||
{
|
||||
[self release];
|
||||
self = nil;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,64 @@
|
|||
/*
|
||||
|
||||
OOCAMusic.h
|
||||
|
||||
Subclass of OOSound with additional controls specific to music playback. Only
|
||||
one instance of OOMusic may be playing at a time.
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "OOCASound.h"
|
||||
|
||||
|
||||
@interface OOMusic: OOSound
|
||||
{
|
||||
OOSound *sound;
|
||||
}
|
||||
|
||||
- (void) playLooped:(BOOL)looped;
|
||||
- (void) stop;
|
||||
- (BOOL) isPlaying;
|
||||
|
||||
@end
|
|
@ -0,0 +1,132 @@
|
|||
/*
|
||||
|
||||
OOCAMusic.m
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOCASoundInternal.h"
|
||||
|
||||
static OOMusic *sPlayingMusic = nil;
|
||||
static OOSoundSource *sMusicSource = nil;
|
||||
|
||||
|
||||
@implementation OOMusic
|
||||
|
||||
#pragma mark NSObject
|
||||
|
||||
+ (id)allocWithZone:(NSZone *)inZone
|
||||
{
|
||||
return NSAllocateObject([OOMusic class], 0, inZone);
|
||||
}
|
||||
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
if (sPlayingMusic == self) [self stop];
|
||||
[sound release];
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
#pragma mark OOSound
|
||||
|
||||
- (id)initWithContentsOfFile:(NSString *)inPath
|
||||
{
|
||||
self = [super init];
|
||||
if (nil != self)
|
||||
{
|
||||
sound = [[OOSound alloc] initWithContentsOfFile:inPath];
|
||||
if (nil == sound)
|
||||
{
|
||||
[self release];
|
||||
self = nil;
|
||||
}
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (NSString *)name
|
||||
{
|
||||
return [sound name];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark OOMusic
|
||||
|
||||
- (void)playLooped:(BOOL)inLoop
|
||||
{
|
||||
if (sPlayingMusic != self)
|
||||
{
|
||||
if (nil == sMusicSource)
|
||||
{
|
||||
sMusicSource = [[OOSoundSource alloc] init];
|
||||
}
|
||||
[sMusicSource stop];
|
||||
[sMusicSource setLoop:inLoop];
|
||||
[sMusicSource setSound:sound];
|
||||
[sMusicSource play];
|
||||
|
||||
sPlayingMusic = self;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)isPlaying
|
||||
{
|
||||
return sPlayingMusic == self && [sMusicSource isPlaying];
|
||||
}
|
||||
|
||||
|
||||
- (void)stop
|
||||
{
|
||||
if (sPlayingMusic == self)
|
||||
{
|
||||
sPlayingMusic = nil;
|
||||
[sMusicSource stop];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,68 @@
|
|||
/*
|
||||
|
||||
OOCASound.h
|
||||
|
||||
Abstract base class for sounds, and primary sound loading interface.
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
|
||||
@interface OOSound: NSObject
|
||||
{
|
||||
uint32_t _playingCount;
|
||||
}
|
||||
|
||||
+ (void) setUp;
|
||||
+ (void) update;
|
||||
|
||||
+ (void) setMasterVolume:(float) fraction;
|
||||
+ (float) masterVolume;
|
||||
|
||||
- (id) initWithContentsOfFile:(NSString *)path;
|
||||
|
||||
- (NSString *)name;
|
||||
|
||||
@end
|
|
@ -0,0 +1,305 @@
|
|||
/*
|
||||
|
||||
OOCASound.m
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
|
||||
/* OOSound is a class cluster. A single OOSound object exists, which
|
||||
represents a sound that has been alloced but not inited. The designated
|
||||
initialiser returns a concrete subclass, either OOCABufferedSound or
|
||||
OOCAStreamingSound, depending on the size of the sound data.
|
||||
*/
|
||||
|
||||
#import "OOCASoundInternal.h"
|
||||
#import "OOCASoundDecoder.h"
|
||||
#import <CoreAudio/CoreAudio.h>
|
||||
#import <AudioToolbox/AudioToolbox.h>
|
||||
#import "NSThreadOOExtensions.h"
|
||||
|
||||
#define KEY_VOLUME_CONTROL @"volume_control"
|
||||
#define KEY_MAX_BUFFERED_SOUND @"max_buffered_sound"
|
||||
|
||||
|
||||
NSString * const kOOLogDeprecatedMethodOOCASound = @"general.error.deprecatedMethod.oocasound";
|
||||
NSString * const kOOLogSoundInitError = @"sound.initialization.error";
|
||||
static NSString * const kOOLogSoundLoadingSuccess = @"sound.load.success";
|
||||
static NSString * const kOOLogSoundLoadingError = @"sound.load.error";
|
||||
|
||||
|
||||
static float sNominalVolume = 1.0f;
|
||||
BOOL gOOSoundSetUp = NO;
|
||||
BOOL gOOSoundBroken = NO;
|
||||
NSRecursiveLock *gOOCASoundSyncLock = nil; // Used to ensure thread-safety of play and stop, specifically because stop may be called from the CoreAudio thread.
|
||||
|
||||
static OOSound *sSingletonOOSound = nil;
|
||||
static size_t sMaxBufferedSoundSize = 1 << 20; // 1 MB
|
||||
|
||||
|
||||
@implementation OOSound
|
||||
|
||||
#pragma mark NSObject
|
||||
|
||||
+ (id)allocWithZone:(NSZone *)inZone
|
||||
{
|
||||
if (self != [OOSound class]) return [super allocWithZone:inZone];
|
||||
|
||||
if (nil == sSingletonOOSound)
|
||||
{
|
||||
sSingletonOOSound = [super allocWithZone:inZone];
|
||||
}
|
||||
|
||||
return sSingletonOOSound;
|
||||
}
|
||||
|
||||
|
||||
- (id)init
|
||||
{
|
||||
if ([self isMemberOfClass:[OOSound class]])
|
||||
{
|
||||
[self release];
|
||||
return nil;
|
||||
}
|
||||
else
|
||||
{
|
||||
return [super init];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
if (self == sSingletonOOSound) sSingletonOOSound = nil;
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
- (NSString *)description
|
||||
{
|
||||
if ([self isMemberOfClass:[OOSound class]])
|
||||
{
|
||||
return [NSString stringWithFormat:@"<%@ %p>(singleton placeholder)", [self className], self];
|
||||
}
|
||||
else
|
||||
{
|
||||
return [NSString stringWithFormat:@"<%@ %p>{\"%@\"}", [self className], self, [self name]];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#pragma mark OOSound
|
||||
|
||||
+ (void) setUp
|
||||
{
|
||||
NSUserDefaults *prefs = nil;
|
||||
|
||||
if (!gOOSoundSetUp)
|
||||
{
|
||||
gOOCASoundSyncLock = [[NSRecursiveLock alloc] init];
|
||||
[gOOCASoundSyncLock ooSetName:@"OOCASound synchronization lock"];
|
||||
if (nil == gOOCASoundSyncLock)
|
||||
{
|
||||
OOLog(kOOLogSoundInitError, @"Failed to set up sound (lock allocation failed). No sound will be played.");
|
||||
gOOSoundBroken = YES;
|
||||
}
|
||||
if (!gOOSoundBroken)
|
||||
{
|
||||
if (![OOSoundChannel setUp]) gOOSoundBroken = YES;
|
||||
}
|
||||
|
||||
gOOSoundSetUp = YES; // Must be before [OOSoundMixer sharedMixer] below.
|
||||
|
||||
prefs = [NSUserDefaults standardUserDefaults];
|
||||
|
||||
if ([prefs objectForKey:KEY_VOLUME_CONTROL]) sNominalVolume = [prefs floatForKey:KEY_VOLUME_CONTROL];
|
||||
else sNominalVolume = 0.75; // default setting at 75% system volume
|
||||
[[OOSoundMixer sharedMixer] setMasterVolume:sNominalVolume];
|
||||
|
||||
if ([prefs objectForKey:KEY_MAX_BUFFERED_SOUND])
|
||||
{
|
||||
int maxSize = [prefs integerForKey:KEY_MAX_BUFFERED_SOUND];
|
||||
if (0 <= maxSize) sMaxBufferedSoundSize = maxSize;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+ (void) update
|
||||
{
|
||||
[[OOSoundMixer sharedMixer] update];
|
||||
}
|
||||
|
||||
|
||||
+ (void) setMasterVolume:(float)fraction
|
||||
{
|
||||
if (fraction != sNominalVolume)
|
||||
{
|
||||
[[OOSoundMixer sharedMixer] setMasterVolume:fraction];
|
||||
|
||||
sNominalVolume = fraction;
|
||||
[[NSUserDefaults standardUserDefaults] setFloat:fraction forKey:KEY_VOLUME_CONTROL];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+ (float) masterVolume
|
||||
{
|
||||
return sNominalVolume;
|
||||
}
|
||||
|
||||
|
||||
/* Designated initialiser for OOSound.
|
||||
Note: OOSound is a class cluster. This will always return a subclass of OOSound.
|
||||
*/
|
||||
- (id) initWithContentsOfFile:(NSString *)inPath
|
||||
{
|
||||
OOCASoundDecoder *decoder;
|
||||
|
||||
if (!gOOSoundSetUp) [OOSound setUp];
|
||||
|
||||
decoder = [[OOCASoundDecoder alloc] initWithPath:inPath];
|
||||
if (nil == decoder) return nil;
|
||||
|
||||
if ([decoder sizeAsBuffer] <= sMaxBufferedSoundSize)
|
||||
{
|
||||
self = [[OOCABufferedSound alloc] initWithDecoder:decoder];
|
||||
}
|
||||
else
|
||||
{
|
||||
self = [[OOCAStreamingSound alloc] initWithDecoder:decoder];
|
||||
}
|
||||
[decoder release];
|
||||
|
||||
if (nil != self)
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
OOLog(kOOLogSoundLoadingSuccess, @"Loaded sound %@", self);
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
OOLog(kOOLogSoundLoadingError, @"Failed to load sound \"%@\"", inPath);
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (id)initWithDecoder:(OOCASoundDecoder *)inDecoder
|
||||
{
|
||||
[self release];
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
- (OSStatus)renderWithFlags:(AudioUnitRenderActionFlags *)ioFlags frames:(UInt32)inNumFrames context:(OOCASoundRenderContext *)ioContext data:(AudioBufferList *)ioData
|
||||
{
|
||||
OOLog(@"general.error.subclassResponsibility.OOCASound-renderWithFlags", @"%s shouldn't be called - subclass responsibility.", __PRETTY_FUNCTION__);
|
||||
return unimpErr;
|
||||
}
|
||||
|
||||
|
||||
- (void)incrementPlayingCount
|
||||
{
|
||||
++_playingCount;
|
||||
}
|
||||
|
||||
|
||||
- (void)decrementPlayingCount
|
||||
{
|
||||
//assert(0 != _playingCount);
|
||||
if (EXPECT(_playingCount != 0)) --_playingCount;
|
||||
else OOLog(@"sound.playUnderflow", @"Playing count for %@ dropped below 0!", self);
|
||||
}
|
||||
|
||||
|
||||
- (BOOL) isPlaying
|
||||
{
|
||||
return 0 != _playingCount;
|
||||
}
|
||||
|
||||
|
||||
- (uint32_t)playingCount
|
||||
{
|
||||
return _playingCount;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)prepareToPlayWithContext:(OOCASoundRenderContext *)outContext looped:(BOOL)inLoop
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
- (void)finishStoppingWithContext:(OOCASoundRenderContext)inContext
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)doPlay
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)doStop
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
- (NSString *)name
|
||||
{
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)getAudioStreamBasicDescription:(AudioStreamBasicDescription *)outFormat
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,110 @@
|
|||
/*
|
||||
|
||||
OOCASoundChannel.h
|
||||
|
||||
A channel for audio playback.
|
||||
|
||||
This class is an implementation detail. Do not use it directly; use an
|
||||
OOSoundSource to play an OOSound.
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <AudioToolbox/AudioToolbox.h>
|
||||
|
||||
@class OOSound;
|
||||
|
||||
|
||||
typedef uintptr_t OOCASoundRenderContext;
|
||||
typedef OSStatus (*OOSoundChannel_RenderIMP)(id inSelf, SEL inSelector, AudioUnitRenderActionFlags *ioFlags, UInt32 inNumFrames, OOCASoundRenderContext *ioContext, AudioBufferList *ioData);
|
||||
|
||||
|
||||
@interface OOSoundChannel: NSObject
|
||||
{
|
||||
OOSoundChannel *_next;
|
||||
id _delegate;
|
||||
AUNode _subGraphNode;
|
||||
AUGraph _subGraph;
|
||||
AUNode _node;
|
||||
AudioUnit _au;
|
||||
OOSound *_sound;
|
||||
OOCASoundRenderContext _context;
|
||||
OOSoundChannel_RenderIMP Render;
|
||||
uint8_t _state,
|
||||
_id,
|
||||
_stopReq;
|
||||
OSStatus _error;
|
||||
}
|
||||
|
||||
+ (BOOL)setUp;
|
||||
+ (void)tearDown;
|
||||
|
||||
- (id)initWithID:(uint32_t)inID auGraph:(AUGraph)inGraph;
|
||||
|
||||
- (void)setDelegate:(id)inDelegate;
|
||||
|
||||
- (uint32_t)ID;
|
||||
|
||||
- (AUNode)auSubGraphNode;
|
||||
|
||||
// Unretained pointer used to maintain simple stack
|
||||
- (OOSoundChannel *)next;
|
||||
- (void)setNext:(OOSoundChannel *)inNext;
|
||||
|
||||
- (BOOL)playSound:(OOSound *)inSound looped:(BOOL)inLoop;
|
||||
- (void)stop;
|
||||
|
||||
- (OOSound *)sound;
|
||||
|
||||
- (BOOL)isOK;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@interface NSObject(OOSoundChannelDelegate)
|
||||
|
||||
// Note: this will be called in a separate thread.
|
||||
- (void)channel:(OOSoundChannel *)inChannel didFinishPlayingSound:(OOSound *)inSound;
|
||||
|
||||
@end
|
|
@ -0,0 +1,723 @@
|
|||
/*
|
||||
|
||||
OOCASoundChannel.m
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOCASoundChannel.h"
|
||||
#import "OOCASoundInternal.h"
|
||||
#import <mach/mach.h>
|
||||
#import <pthread.h>
|
||||
#import </usr/include/libkern/OSAtomic.h>
|
||||
#import "NSThreadOOExtensions.h"
|
||||
|
||||
|
||||
static NSString * const kOOLogSoundNULLError = @"sound.render.undexpectedNull";
|
||||
static NSString * const kOOLogSoundPlaySuccess = @"sound.play.success";
|
||||
static NSString * const kOOLogSoundBadReuse = @"sound.play.failed.badReuse";
|
||||
static NSString * const kOOLogSoundSetupFailed = @"sound.play.failed.setupFailed";
|
||||
static NSString * const kOOLogSoundPlayAUError = @"sound.play.failed.auError";
|
||||
static NSString * const kOOLogSoundPlayUnknownError = @"sound.play.failed";
|
||||
static NSString * const kOOLogSoundCleanUpSuccess = @"sound.channel.cleanup.success";
|
||||
static NSString * const kOOLogSoundCleanUpBroken = @"sound.channel.cleanup.failed.broken";
|
||||
static NSString * const kOOLogSoundCleanUpBadState = @"sound.channel.cleanup.failed.badState";
|
||||
static NSString * const kOOLogSoundMachPortError = @"sound.channel.machPortError";
|
||||
|
||||
|
||||
// Tracks a kind of error that isn’t happening any more.
|
||||
#define COUNT_NULLS 0
|
||||
|
||||
|
||||
static mach_port_t sReapPort = MACH_PORT_NULL;
|
||||
static mach_port_t sStatusPort = MACH_PORT_NULL;
|
||||
static BOOL sReaperRunning = NO;
|
||||
static OOSoundChannel_RenderIMP SoundChannelRender = NULL;
|
||||
|
||||
#if COUNT_NULLS
|
||||
static int32_t sDebugUnexpectedNullCount = 0;
|
||||
#endif
|
||||
|
||||
/*
|
||||
When a channel finishes playing, it is put in the “play thread dead list.” At the end of each
|
||||
sound callback, if the play thread dead list is not empty and the reap queue mutex can be
|
||||
acquired, the play thread dead list is copied to the reap queue under the mutex. This allows us
|
||||
to use a mutex-protected list to communicate with the reap queue without having to wait on the
|
||||
mutex in the real-time thread.
|
||||
*/
|
||||
static OOSoundChannel *sPlayThreadDeadList = NULL;
|
||||
static OOSoundChannel *sReapQueue = NULL;
|
||||
static pthread_mutex_t sReapQueueMutex = { 0 };
|
||||
|
||||
enum
|
||||
{
|
||||
kState_Stopped,
|
||||
kState_Playing,
|
||||
kState_Ended,
|
||||
kState_Reap,
|
||||
|
||||
kState_Broken
|
||||
};
|
||||
|
||||
|
||||
#define kAURenderSelector @selector(renderWithFlags:frames:context:data:)
|
||||
|
||||
|
||||
@interface OOSoundChannel(Private)
|
||||
|
||||
+ (void)reaperThread:junk;
|
||||
|
||||
- (void)reap;
|
||||
- (void)cleanUp;
|
||||
|
||||
- (OSStatus)renderWithFlags:(AudioUnitRenderActionFlags *)ioFlags frames:(UInt32)inNumFrames context:(OOCASoundRenderContext *)ioContext data:(AudioBufferList *)ioData;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
enum
|
||||
{
|
||||
// Port messages
|
||||
kMsgThreadUp = 1UL,
|
||||
kMsgDie,
|
||||
kMsgThreadDied,
|
||||
kMsgWakeUp
|
||||
};
|
||||
|
||||
|
||||
typedef struct
|
||||
{
|
||||
uintptr_t tag;
|
||||
void *value;
|
||||
} PortMessage;
|
||||
|
||||
|
||||
typedef struct
|
||||
{
|
||||
mach_msg_header_t header;
|
||||
mach_msg_size_t descCount;
|
||||
mach_msg_descriptor_t descriptor;
|
||||
PortMessage message;
|
||||
} PortSendMsgBody;
|
||||
|
||||
|
||||
typedef struct
|
||||
{
|
||||
mach_msg_header_t header;
|
||||
mach_msg_size_t descCount;
|
||||
mach_msg_descriptor_t descriptor;
|
||||
PortMessage message;
|
||||
mach_msg_trailer_t trailer;
|
||||
} PortWaitMsgBody;
|
||||
|
||||
|
||||
static OSStatus ChannelRenderProc(void *inRefCon, AudioUnitRenderActionFlags *ioFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumFrames, AudioBufferList *ioData);
|
||||
|
||||
static mach_port_t CreatePort(void);
|
||||
static void PortSend(mach_port_t inPort, PortMessage inMessage);
|
||||
static BOOL PortWait(mach_port_t inPort, PortMessage *outMessage);
|
||||
|
||||
|
||||
@implementation OOSoundChannel
|
||||
|
||||
+ (BOOL)setUp
|
||||
{
|
||||
BOOL OK = YES;
|
||||
PortMessage message;
|
||||
|
||||
if (sReaperRunning) return YES;
|
||||
|
||||
SoundChannelRender = (OOSoundChannel_RenderIMP)[OOSoundChannel instanceMethodForSelector:kAURenderSelector];
|
||||
if (NULL == SoundChannelRender) OK = NO;
|
||||
|
||||
if (OK)
|
||||
{
|
||||
sReapPort = CreatePort();
|
||||
if (MACH_PORT_NULL == sReapPort) OK = NO;
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
sStatusPort = CreatePort();
|
||||
if (MACH_PORT_NULL == sStatusPort) OK = NO;
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
if (0 != pthread_mutex_init(&sReapQueueMutex, NULL)) OK = NO;
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
[NSThread detachNewThreadSelector:@selector(reaperThread:) toTarget:self withObject:nil];
|
||||
OK = PortWait(sStatusPort, &message);
|
||||
if (OK)
|
||||
{
|
||||
if (kMsgThreadUp != message.tag) OK = NO;
|
||||
}
|
||||
}
|
||||
|
||||
if (!OK)
|
||||
{
|
||||
OOLog(kOOLogSoundInitError, @"Failed to set up sound (channel queue allocation failed). No sound will be played.");
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
|
||||
+ (void)tearDown
|
||||
{
|
||||
ipc_space_t task;
|
||||
PortMessage message = { kMsgDie, NULL };
|
||||
|
||||
if (sReaperRunning)
|
||||
{
|
||||
PortSend(sReapPort, message);
|
||||
PortWait(sStatusPort, &message);
|
||||
}
|
||||
|
||||
task = mach_task_self();
|
||||
if (MACH_PORT_NULL != sReapPort) mach_port_destroy(task, sReapPort);
|
||||
if (MACH_PORT_NULL != sStatusPort) mach_port_destroy(task, sStatusPort);
|
||||
}
|
||||
|
||||
|
||||
+ (void)reaperThread:junk
|
||||
{
|
||||
PortMessage message = { kMsgThreadUp, NULL };
|
||||
OOSoundChannel *chan;
|
||||
NSAutoreleasePool *pool = nil;
|
||||
|
||||
[NSThread ooSetCurrentThreadName:@"OOSoundChannel reaper thread"];
|
||||
sReaperRunning = YES;
|
||||
PortSend(sStatusPort, message);
|
||||
|
||||
[NSThread setThreadPriority:0.5];
|
||||
|
||||
for (;;)
|
||||
{
|
||||
if (PortWait(sReapPort, &message))
|
||||
{
|
||||
pool = [[NSAutoreleasePool alloc] init];
|
||||
|
||||
if (kMsgWakeUp == message.tag)
|
||||
{
|
||||
assert (!pthread_mutex_lock(&sReapQueueMutex));
|
||||
|
||||
while (sReapQueue)
|
||||
{
|
||||
chan = sReapQueue;
|
||||
sReapQueue = chan->_next;
|
||||
if (kState_Reap == chan->_state) [chan reap];
|
||||
[chan cleanUp];
|
||||
}
|
||||
|
||||
pthread_mutex_unlock(&sReapQueueMutex);
|
||||
}
|
||||
else if (kMsgDie == message.tag)
|
||||
{
|
||||
[pool release];
|
||||
break;
|
||||
}
|
||||
|
||||
[pool release];
|
||||
}
|
||||
}
|
||||
|
||||
message.tag = kMsgThreadDied;
|
||||
message.value = NULL;
|
||||
sReaperRunning = NO;
|
||||
PortSend(sStatusPort, message);
|
||||
}
|
||||
|
||||
|
||||
- (id)init
|
||||
{
|
||||
[self release];
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
- (id)initWithID:(uint32_t)inID auGraph:(AUGraph)inGraph
|
||||
{
|
||||
OSStatus err = noErr;
|
||||
ComponentDescription desc;
|
||||
AURenderCallbackStruct input;
|
||||
|
||||
assert(sReaperRunning);
|
||||
|
||||
self = [super init];
|
||||
if (nil != self)
|
||||
{
|
||||
_id = inID;
|
||||
|
||||
// Create a subgraph (since we can’t have multiple output units otherwise)
|
||||
err = AUGraphNewNodeSubGraph(inGraph, &_subGraphNode);
|
||||
if (!err) err = AUGraphGetNodeInfoSubGraph(inGraph, _subGraphNode, &_subGraph);
|
||||
|
||||
// Create an output unit
|
||||
desc.componentType = kAudioUnitType_Output;
|
||||
desc.componentSubType = kAudioUnitSubType_GenericOutput;
|
||||
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
|
||||
desc.componentFlags = 0;
|
||||
desc.componentFlagsMask = 0;
|
||||
if (!err) err = OOAUGraphAddNode(_subGraph, &desc, &_node);
|
||||
if (!err) err = OOAUGraphNodeInfo(_subGraph, _node, NULL, &_au);
|
||||
|
||||
// Set render callback
|
||||
input.inputProc = ChannelRenderProc;
|
||||
input.inputProcRefCon = self;
|
||||
if (!err) err = AudioUnitSetProperty(_au, kAudioUnitProperty_SetRenderCallback,
|
||||
kAudioUnitScope_Input, 0, &input, sizeof input);
|
||||
|
||||
// Init & check errors
|
||||
if (!err) err = AudioUnitInitialize(_au);
|
||||
|
||||
if (err)
|
||||
{
|
||||
OOLog(kOOLogSoundInitError, @"AudioUnit setup error %@ preparing channel ID %u.", AudioErrorNSString(err), inID);
|
||||
|
||||
[self release];
|
||||
self = nil;
|
||||
}
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
[self stop];
|
||||
if (NULL != _au) CloseComponent(_au);
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
- (void)setDelegate:(id)inDelegate
|
||||
{
|
||||
_delegate = inDelegate;
|
||||
}
|
||||
|
||||
|
||||
- (uint32_t)ID
|
||||
{
|
||||
return _id;
|
||||
}
|
||||
|
||||
|
||||
- (AUNode)auSubGraphNode
|
||||
{
|
||||
return _subGraphNode;
|
||||
}
|
||||
|
||||
|
||||
- (OOSoundChannel *)next
|
||||
{
|
||||
return _next;
|
||||
}
|
||||
|
||||
|
||||
- (void)setNext:(OOSoundChannel *)inNext
|
||||
{
|
||||
_next = inNext;
|
||||
}
|
||||
|
||||
|
||||
- (OOSound *)sound
|
||||
{
|
||||
return _sound;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)playSound:(OOSound *)inSound looped:(BOOL)inLooped
|
||||
{
|
||||
BOOL OK = YES;
|
||||
OSStatus err = noErr;
|
||||
AudioStreamBasicDescription format;
|
||||
OOSound *temp;
|
||||
|
||||
#if COUNT_NULLS
|
||||
SInt32 unexpectedNulls;
|
||||
|
||||
unexpectedNulls = sDebugUnexpectedNullCount;
|
||||
if (0 != unexpectedNulls)
|
||||
{
|
||||
OOSoundAtomicAdd(-unexpectedNulls, &sDebugUnexpectedNullCount);
|
||||
if (1 == unexpectedNulls)
|
||||
{
|
||||
OOLog(kOOLogSoundNULLError, @"A NULL Render() or nil _sound error has occured.");
|
||||
}
|
||||
else
|
||||
{
|
||||
OOLog(kOOLogSoundNULLError, @"%i NULL Render() or nil _sound errors have occured.", (int)unexpectedNulls);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if (nil != inSound)
|
||||
{
|
||||
[gOOCASoundSyncLock lock];
|
||||
if (kState_Stopped != _state)
|
||||
{
|
||||
OOLog(kOOLogSoundBadReuse, @"Channel %@ reused while playing.", self);
|
||||
|
||||
[[OOSoundMixer sharedMixer] disconnectChannel:self];
|
||||
if (_sound)
|
||||
{
|
||||
Render = NULL;
|
||||
temp = _sound;
|
||||
_sound = nil;
|
||||
[temp finishStoppingWithContext:_context];
|
||||
_context = 0;
|
||||
[temp release];
|
||||
}
|
||||
_stopReq = NO;
|
||||
_state = kState_Stopped;
|
||||
}
|
||||
|
||||
Render = (OOSoundChannel_RenderIMP)[inSound methodForSelector:kAURenderSelector];
|
||||
OK = (NULL != Render);
|
||||
|
||||
if (OK) OK = [inSound getAudioStreamBasicDescription:&format];
|
||||
if (OK) OK = [inSound prepareToPlayWithContext:&_context looped:inLooped];
|
||||
|
||||
if (!OK)
|
||||
{
|
||||
OOLog(kOOLogSoundSetupFailed, @"Failed to play sound %@ - set-up failed.", inSound);
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
_sound = inSound;
|
||||
|
||||
err = AudioUnitSetProperty(_au, kAudioUnitProperty_StreamFormat,
|
||||
kAudioUnitScope_Input, 0, &format, sizeof format);
|
||||
|
||||
if (err) OOLog(kOOLogSoundPlayAUError, @"Failed to play %@ (error %@)", inSound, AudioErrorNSString(err));
|
||||
OK = !err;
|
||||
}
|
||||
|
||||
if (OK) OK = [[OOSoundMixer sharedMixer] connectChannel:self];
|
||||
|
||||
if (OK)
|
||||
{
|
||||
[_sound retain];
|
||||
_state = kState_Playing;
|
||||
OOLog(kOOLogSoundPlaySuccess, @"Playing sound %@", _sound);
|
||||
}
|
||||
else
|
||||
{
|
||||
_sound = nil;
|
||||
if (!err) OOLog(kOOLogSoundPlayUnknownError, @"Failed to play %@", inSound);
|
||||
}
|
||||
[gOOCASoundSyncLock unlock];
|
||||
}
|
||||
|
||||
return OK;
|
||||
}
|
||||
|
||||
|
||||
- (void)stop
|
||||
{
|
||||
if (kState_Playing == _state)
|
||||
{
|
||||
_stopReq = YES;
|
||||
}
|
||||
|
||||
if (kState_Ended == _state) [self cleanUp];
|
||||
}
|
||||
|
||||
|
||||
- (void)reap
|
||||
{
|
||||
OSStatus err;
|
||||
|
||||
err = [[OOSoundMixer sharedMixer] disconnectChannel:self];
|
||||
|
||||
if (noErr == err)
|
||||
{
|
||||
_state = kState_Ended;
|
||||
}
|
||||
else
|
||||
{
|
||||
_state = kState_Broken;
|
||||
_error = err;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void)cleanUp
|
||||
{
|
||||
OOSound *sound;
|
||||
|
||||
[gOOCASoundSyncLock lock];
|
||||
|
||||
if (kState_Broken == _state)
|
||||
{
|
||||
OOLog(kOOLogSoundCleanUpBroken, @"Sound channel %@ broke with error %@.", self, AudioErrorNSString(_error));
|
||||
}
|
||||
|
||||
if (kState_Ended == _state || kState_Broken == _state)
|
||||
{
|
||||
Render = NULL;
|
||||
sound = _sound;
|
||||
_sound = nil;
|
||||
[sound finishStoppingWithContext:_context];
|
||||
_context = 0;
|
||||
|
||||
_state = kState_Stopped;
|
||||
_stopReq = NO;
|
||||
|
||||
if (nil != _delegate && [_delegate respondsToSelector:@selector(channel:didFinishPlayingSound:)])
|
||||
{
|
||||
[_delegate channel:self didFinishPlayingSound:sound];
|
||||
}
|
||||
[sound release];
|
||||
|
||||
OOLog(kOOLogSoundCleanUpSuccess, @"Sound channel id %u cleaned up successfully.", _id);
|
||||
}
|
||||
else
|
||||
{
|
||||
OOLog(kOOLogSoundCleanUpBadState, @"Sound channel %@ cleaned up in invalid state %u.", self, _state);
|
||||
}
|
||||
|
||||
[gOOCASoundSyncLock unlock];
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)isOK
|
||||
{
|
||||
return kState_Broken != _state;
|
||||
}
|
||||
|
||||
|
||||
- (NSString *)description
|
||||
{
|
||||
NSString *result, *stateString;
|
||||
|
||||
[gOOCASoundSyncLock lock];
|
||||
switch (_state)
|
||||
{
|
||||
case kState_Stopped:
|
||||
stateString = @"stopped";
|
||||
break;
|
||||
|
||||
case kState_Playing:
|
||||
stateString = @"playing";
|
||||
break;
|
||||
|
||||
case kState_Ended:
|
||||
stateString = @"ended";
|
||||
break;
|
||||
|
||||
case kState_Broken:
|
||||
stateString = [NSString stringWithFormat:@"broken (%@)", AudioErrorShortNSString(_error)];
|
||||
break;
|
||||
|
||||
default:
|
||||
stateString = [NSString stringWithFormat:@"unknown (%u)", _state];
|
||||
}
|
||||
|
||||
result = [NSString stringWithFormat:@"<%@ %p>{ID=%u, state=%@, sound=%@}", [self className], self, _id, stateString, _sound];
|
||||
[gOOCASoundSyncLock unlock];
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
- (OSStatus)renderWithFlags:(AudioUnitRenderActionFlags *)ioFlags frames:(UInt32)inNumFrames context:(OOCASoundRenderContext *)ioContext data:(AudioBufferList *)ioData
|
||||
{
|
||||
OSStatus err = noErr;
|
||||
PortMessage message;
|
||||
|
||||
if (__builtin_expect(_stopReq, 0)) err = endOfDataReached;
|
||||
else if (__builtin_expect(kState_Playing == _state, 1))
|
||||
{
|
||||
if (NULL != Render && nil != _sound)
|
||||
{
|
||||
err = Render(_sound, kAURenderSelector, ioFlags, inNumFrames, &_context, ioData);
|
||||
}
|
||||
else
|
||||
{
|
||||
unsigned i, count;
|
||||
|
||||
err = endOfDataReached;
|
||||
count = ioData->mNumberBuffers;
|
||||
|
||||
for (i = 0; i != count; ++count)
|
||||
{
|
||||
bzero(ioData->mBuffers[i].mData, ioData->mBuffers[i].mDataByteSize);
|
||||
}
|
||||
*ioFlags |= kAudioUnitRenderAction_OutputIsSilence;
|
||||
|
||||
#if COUNT_NULLS
|
||||
// Logging in real-time thread _baaaaaad_.
|
||||
if (NULL == Render || nil == _sound)
|
||||
{
|
||||
OOSoundAtomicAdd(1, &sDebugUnexpectedNullCount);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
if (__builtin_expect(endOfDataReached == err, 0))
|
||||
{
|
||||
err = noErr;
|
||||
if (__builtin_expect(kState_Playing == _state, 1))
|
||||
{
|
||||
_state = kState_Reap;
|
||||
|
||||
_next = sPlayThreadDeadList;
|
||||
sPlayThreadDeadList = self;
|
||||
}
|
||||
}
|
||||
|
||||
if (__builtin_expect(nil != sPlayThreadDeadList && !pthread_mutex_trylock(&sReapQueueMutex), 0))
|
||||
{
|
||||
// Put sPlayThreadDeadList at front of sReapQueue
|
||||
OOSoundChannel *curr;
|
||||
|
||||
curr = sPlayThreadDeadList;
|
||||
while (nil != curr->_next) curr = curr->_next;
|
||||
|
||||
curr->_next = sReapQueue;
|
||||
sReapQueue = sPlayThreadDeadList;
|
||||
sPlayThreadDeadList = nil;
|
||||
|
||||
pthread_mutex_unlock(&sReapQueueMutex);
|
||||
|
||||
// Wake up reaper thread
|
||||
message.tag = kMsgWakeUp;
|
||||
message.value = NULL;
|
||||
PortSend(sReapPort, message);
|
||||
}
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
static OSStatus ChannelRenderProc(void *inRefCon, AudioUnitRenderActionFlags *ioFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumFrames, AudioBufferList *ioData)
|
||||
{
|
||||
return SoundChannelRender((id)inRefCon, kAURenderSelector, ioFlags, inNumFrames, 0, ioData);
|
||||
}
|
||||
|
||||
|
||||
static mach_port_t CreatePort(void)
|
||||
{
|
||||
kern_return_t err;
|
||||
mach_port_t result;
|
||||
ipc_space_t task;
|
||||
mach_msg_type_name_t type;
|
||||
mach_port_t sendRight;
|
||||
|
||||
task = mach_task_self();
|
||||
err = mach_port_allocate(task, MACH_PORT_RIGHT_RECEIVE, &result);
|
||||
if (KERN_SUCCESS == err) err = mach_port_insert_right(task, result, result, MACH_MSG_TYPE_MAKE_SEND);
|
||||
if (KERN_SUCCESS == err) err = mach_port_extract_right(task, result, MACH_MSG_TYPE_MAKE_SEND, &sendRight, &type);
|
||||
|
||||
if (KERN_SUCCESS != err)
|
||||
{
|
||||
OOLog(kOOLogSoundInitError, @"Mach port creation failure: %@", KernelResultNSString(err));
|
||||
result = MACH_PORT_NULL;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
static void PortSend(mach_port_t inPort, PortMessage inMessage)
|
||||
{
|
||||
PortSendMsgBody message;
|
||||
mach_msg_return_t result;
|
||||
|
||||
bzero(&message, sizeof message);
|
||||
|
||||
message.header.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_MAKE_SEND);
|
||||
message.header.msgh_size = sizeof message;
|
||||
message.header.msgh_remote_port = inPort;
|
||||
message.header.msgh_local_port = MACH_PORT_NULL;
|
||||
|
||||
message.descCount = 1;
|
||||
|
||||
message.message = inMessage;
|
||||
|
||||
result = mach_msg(&message.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof message, 0, MACH_PORT_NULL, 0, MACH_PORT_NULL);
|
||||
if (MACH_MSG_SUCCESS != result)
|
||||
{
|
||||
OOLog(kOOLogSoundMachPortError, @"Mach port transient send failure: %@", KernelResultNSString(result));
|
||||
result = mach_msg(&message.header, MACH_SEND_MSG, sizeof message, 0, MACH_PORT_NULL, 0, MACH_PORT_NULL);
|
||||
if (MACH_MSG_SUCCESS != result)
|
||||
{
|
||||
OOLog(kOOLogSoundMachPortError, @"Mach port send failure: %@", KernelResultNSString(result));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static BOOL PortWait(mach_port_t inPort, PortMessage *outMessage)
|
||||
{
|
||||
PortWaitMsgBody message;
|
||||
mach_msg_return_t result;
|
||||
|
||||
bzero(&message, sizeof message);
|
||||
|
||||
message.header.msgh_bits = MACH_MSGH_BITS_LOCAL(MACH_MSG_TYPE_COPY_RECEIVE);
|
||||
message.header.msgh_size = sizeof message;
|
||||
message.header.msgh_local_port = inPort;
|
||||
|
||||
result = mach_msg_receive(&message.header);
|
||||
if (MACH_MSG_SUCCESS == result)
|
||||
{
|
||||
if (NULL != outMessage) *outMessage = message.message;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (MACH_RCV_TIMED_OUT != result) OOLog(kOOLogSoundMachPortError, @"Mach port receive failure: %@", KernelResultNSString(result));
|
||||
}
|
||||
|
||||
return MACH_MSG_SUCCESS == result;
|
||||
}
|
|
@ -0,0 +1,81 @@
|
|||
/*
|
||||
|
||||
OOCASoundDecoder.h
|
||||
|
||||
Class responsible for converting a sound to a PCM buffer for playback. This
|
||||
class is an implementation detail. Do not use it directly; use OOSound to
|
||||
load sounds.
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
|
||||
@interface OOCASoundDecoder: NSObject
|
||||
|
||||
- (id)initWithPath:(NSString *)inPath;
|
||||
+ (OOCASoundDecoder *)codecWithPath:(NSString *)inPath;
|
||||
|
||||
// Full-buffer reading.
|
||||
- (BOOL)readMonoCreatingBuffer:(float **)outBuffer withFrameCount:(size_t *)outSize;
|
||||
- (BOOL)readStereoCreatingLeftBuffer:(float **)outLeftBuffer rightBuffer:(float **)outRightBuffer withFrameCount:(size_t *)outSize;
|
||||
|
||||
// Stream reading. This will always provide two channels (as non-interleaved PCM), discarding extra channels or doubling mono as necessary.
|
||||
- (size_t)streamStereoToBufferL:(float *)ioBufferL bufferR:(float *)ioBufferR maxFrames:(size_t)inMax;
|
||||
|
||||
// Returns the size of the data -readMonoCreatingBuffer:withFrameCount: will create.
|
||||
- (size_t)sizeAsBuffer;
|
||||
|
||||
- (BOOL)isStereo;
|
||||
|
||||
- (Float64)sampleRate;
|
||||
|
||||
// For streaming
|
||||
- (BOOL)atEnd;
|
||||
- (BOOL)scanToOffset:(uint64_t)inOffset;
|
||||
- (void)rewindToBeginning;
|
||||
|
||||
- (NSString *)name;
|
||||
|
||||
@end
|
|
@ -0,0 +1,524 @@
|
|||
/*
|
||||
|
||||
OOCASoundDecoder.m
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOCASoundDecoder.h"
|
||||
#import <stdio.h>
|
||||
#import <vorbis/vorbisfile.h>
|
||||
#import "OOLogging.h"
|
||||
|
||||
|
||||
enum
|
||||
{
|
||||
kMaxDecodeSize = 1 << 20 // 2^20 frames = 4 MB
|
||||
};
|
||||
|
||||
|
||||
static void MixDown(float *inChan1, float *inChan2, float *outMix, size_t inCount);
|
||||
|
||||
|
||||
@interface OOCASoundVorbisCodec: OOCASoundDecoder
|
||||
{
|
||||
OggVorbis_File _vf;
|
||||
NSString *_name;
|
||||
BOOL _atEnd;
|
||||
}
|
||||
|
||||
- (NSDictionary *)comments;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation OOCASoundDecoder
|
||||
|
||||
#ifndef NDEBUG
|
||||
- (id)init
|
||||
{
|
||||
OOLog(kOOLogDeprecatedMethod, @"Invalid call of %s; designated initializer is -initWithPath:", __PRETTY_FUNCTION__);
|
||||
[self release];
|
||||
return nil;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
- (id)initWithPath:(NSString *)inPath
|
||||
{
|
||||
[self release];
|
||||
self = nil;
|
||||
|
||||
if ([[inPath pathExtension] isEqual:@"ogg"])
|
||||
{
|
||||
self = [[OOCASoundVorbisCodec alloc] initWithPath:inPath];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
+ (OOCASoundDecoder *)codecWithPath:(NSString *)inPath
|
||||
{
|
||||
if ([[inPath pathExtension] isEqual:@"ogg"])
|
||||
{
|
||||
return [[[OOCASoundVorbisCodec alloc] initWithPath:inPath] autorelease];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
- (size_t)streamStereoToBufferL:(float *)ioBufferL bufferR:(float *)ioBufferR maxFrames:(size_t)inMax
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)readMonoCreatingBuffer:(float **)outBuffer withFrameCount:(size_t *)outSize
|
||||
{
|
||||
if (NULL != outBuffer) *outBuffer = NULL;
|
||||
if (NULL != outSize) *outSize = 0;
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)readStereoCreatingLeftBuffer:(float **)outLeftBuffer rightBuffer:(float **)outRightBuffer withFrameCount:(size_t *)outSize
|
||||
{
|
||||
if (NULL != outLeftBuffer) *outLeftBuffer = NULL;
|
||||
if (NULL != outRightBuffer) *outRightBuffer = NULL;
|
||||
if (NULL != outSize) *outSize = 0;
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
- (size_t)sizeAsBuffer
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)isStereo
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
- (double)sampleRate
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)atEnd
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
- (void)rewindToBeginning
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)scanToOffset:(uint64_t)inOffset
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
- (NSString *)name
|
||||
{
|
||||
return @"";
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation OOCASoundVorbisCodec
|
||||
|
||||
- (id)initWithPath:(NSString *)inPath
|
||||
{
|
||||
BOOL OK = NO;
|
||||
int err;
|
||||
FILE *file;
|
||||
|
||||
_name = [[inPath lastPathComponent] retain];
|
||||
|
||||
if (nil != inPath)
|
||||
{
|
||||
file = fopen([inPath UTF8String], "rb");
|
||||
if (NULL != file)
|
||||
{
|
||||
err = ov_open(file, &_vf, NULL, 0);
|
||||
if (0 == err)
|
||||
{
|
||||
OK = YES;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!OK)
|
||||
{
|
||||
[self release];
|
||||
self = nil;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
[_name release];
|
||||
ov_clear(&_vf);
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
- (NSDictionary *)comments
|
||||
{
|
||||
vorbis_comment *comments;
|
||||
unsigned i, count;
|
||||
NSMutableDictionary *result = nil;
|
||||
NSString *comment, *key, *value;
|
||||
NSRange range;
|
||||
|
||||
comments = ov_comment(&_vf, -1);
|
||||
if (NULL != comments)
|
||||
{
|
||||
count = comments->comments;
|
||||
if (0 != count)
|
||||
{
|
||||
result = [NSMutableDictionary dictionaryWithCapacity:count];
|
||||
for (i = 0; i != count; ++i)
|
||||
{
|
||||
comment = [[NSString alloc] initWithBytesNoCopy:comments->user_comments[i] length:comments->comment_lengths[i] encoding:NSUTF8StringEncoding freeWhenDone:NO];
|
||||
range = [comment rangeOfString:@"="];
|
||||
if (0 != range.length)
|
||||
{
|
||||
key = [comment substringToIndex:range.location];
|
||||
value = [comment substringFromIndex:range.location + 1];
|
||||
}
|
||||
else
|
||||
{
|
||||
key = comment;
|
||||
value = @"";
|
||||
}
|
||||
[result setObject:value forKey:key];
|
||||
|
||||
[comment release];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)readMonoCreatingBuffer:(float **)outBuffer withFrameCount:(size_t *)outSize
|
||||
{
|
||||
float *buffer = NULL, *dst, **src;
|
||||
size_t sizeInFrames = 0, remaining;
|
||||
unsigned chanCount;
|
||||
long framesRead;
|
||||
ogg_int64_t totalSizeInFrames;
|
||||
BOOL OK = YES;
|
||||
|
||||
if (NULL != outBuffer) *outBuffer = NULL;
|
||||
if (NULL != outSize) *outSize = 0;
|
||||
if (NULL == outBuffer || NULL == outSize) OK = NO;
|
||||
|
||||
if (OK)
|
||||
{
|
||||
totalSizeInFrames = ov_pcm_total(&_vf, -1);
|
||||
assert (kMaxDecodeSize < SIZE_T_MAX); // Should have been checked by caller
|
||||
sizeInFrames = totalSizeInFrames;
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
buffer = malloc(sizeof (float) * sizeInFrames);
|
||||
if (!buffer) OK = NO;
|
||||
}
|
||||
|
||||
if (OK && sizeInFrames)
|
||||
{
|
||||
remaining = sizeInFrames;
|
||||
dst = buffer;
|
||||
|
||||
do
|
||||
{
|
||||
chanCount = ov_info(&_vf, -1)->channels;
|
||||
framesRead = ov_read_float(&_vf, &src, remaining, NULL);
|
||||
if (framesRead <= 0)
|
||||
{
|
||||
if (OV_HOLE == framesRead) continue;
|
||||
//else:
|
||||
break;
|
||||
}
|
||||
|
||||
if (1 == chanCount) bcopy(src[0], dst, sizeof (float) * framesRead);
|
||||
else MixDown(src[0], src[1], dst, framesRead);
|
||||
|
||||
remaining -= framesRead;
|
||||
dst += framesRead;
|
||||
} while (0 != remaining);
|
||||
|
||||
sizeInFrames -= remaining; // In case we stopped at an error
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
*outBuffer = buffer;
|
||||
*outSize = sizeInFrames;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (buffer) free(buffer);
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)readStereoCreatingLeftBuffer:(float **)outLeftBuffer rightBuffer:(float **)outRightBuffer withFrameCount:(size_t *)outSize;
|
||||
{
|
||||
float *bufferL = NULL, *bufferR = NULL, *dstL, *dstR, **src;
|
||||
size_t sizeInFrames = 0, remaining;
|
||||
unsigned chanCount;
|
||||
long framesRead;
|
||||
ogg_int64_t totalSizeInFrames;
|
||||
BOOL OK = YES;
|
||||
|
||||
if (NULL != outLeftBuffer) *outLeftBuffer = NULL;
|
||||
if (NULL != outRightBuffer) *outRightBuffer = NULL;
|
||||
if (NULL != outSize) *outSize = 0;
|
||||
if (NULL == outLeftBuffer || NULL == outRightBuffer || NULL == outSize) OK = NO;
|
||||
|
||||
if (OK)
|
||||
{
|
||||
totalSizeInFrames = ov_pcm_total(&_vf, -1);
|
||||
assert (kMaxDecodeSize < SIZE_T_MAX); // Should have been checked by caller
|
||||
sizeInFrames = totalSizeInFrames;
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
bufferL = malloc(sizeof (float) * sizeInFrames);
|
||||
if (!bufferL) OK = NO;
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
bufferR = malloc(sizeof (float) * sizeInFrames);
|
||||
if (!bufferR) OK = NO;
|
||||
}
|
||||
|
||||
if (OK && sizeInFrames)
|
||||
{
|
||||
remaining = sizeInFrames;
|
||||
dstL = bufferL;
|
||||
dstR = bufferR;
|
||||
|
||||
do
|
||||
{
|
||||
chanCount = ov_info(&_vf, -1)->channels;
|
||||
framesRead = ov_read_float(&_vf, &src, remaining, NULL);
|
||||
if (framesRead <= 0)
|
||||
{
|
||||
if (OV_HOLE == framesRead) continue;
|
||||
//else:
|
||||
break;
|
||||
}
|
||||
|
||||
bcopy(src[0], dstL, sizeof (float) * framesRead);
|
||||
if (1 == chanCount) bcopy(src[0], dstR, sizeof (float) * framesRead);
|
||||
else bcopy(src[1], dstR, sizeof (float) * framesRead);
|
||||
|
||||
remaining -= framesRead;
|
||||
dstL += framesRead;
|
||||
dstR += framesRead;
|
||||
} while (0 != remaining);
|
||||
|
||||
sizeInFrames -= remaining; // In case we stopped at an error
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
*outLeftBuffer = bufferL;
|
||||
*outRightBuffer = bufferR;
|
||||
*outSize = sizeInFrames;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (bufferL) free(bufferL);
|
||||
if (bufferR) free(bufferR);
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
|
||||
- (size_t)streamStereoToBufferL:(float *)ioBufferL bufferR:(float *)ioBufferR maxFrames:(size_t)inMax
|
||||
{
|
||||
float **src;
|
||||
unsigned chanCount;
|
||||
long framesRead;
|
||||
size_t size, remaining;
|
||||
unsigned rightChan;
|
||||
|
||||
// Note: for our purposes, a frame is a set of one sample for each channel.
|
||||
if (NULL == ioBufferL || NULL == ioBufferR || 0 == inMax) return 0;
|
||||
if (_atEnd) return inMax;
|
||||
|
||||
remaining = inMax;
|
||||
do
|
||||
{
|
||||
chanCount = ov_info(&_vf, -1)->channels;
|
||||
framesRead = ov_read_float(&_vf, &src, remaining, NULL);
|
||||
if (framesRead <= 0)
|
||||
{
|
||||
if (OV_HOLE == framesRead) continue;
|
||||
//else:
|
||||
_atEnd = YES;
|
||||
break;
|
||||
}
|
||||
|
||||
size = sizeof (float) * framesRead;
|
||||
|
||||
rightChan = (1 == chanCount) ? 0 : 1;
|
||||
bcopy(src[0], ioBufferL, size);
|
||||
bcopy(src[rightChan], ioBufferR, size);
|
||||
|
||||
remaining -= framesRead;
|
||||
ioBufferL += framesRead;
|
||||
ioBufferR += framesRead;
|
||||
} while (0 != remaining);
|
||||
|
||||
return inMax - remaining;
|
||||
}
|
||||
|
||||
|
||||
- (size_t)sizeAsBuffer
|
||||
{
|
||||
ogg_int64_t size;
|
||||
|
||||
size = ov_pcm_total(&_vf, -1);
|
||||
size *= sizeof(float) * ([self isStereo] ? 2 : 1);
|
||||
if ((ogg_int64_t)SIZE_T_MAX < size) size = (ogg_int64_t)SIZE_T_MAX;
|
||||
return size;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)isStereo
|
||||
{
|
||||
return 1 < ov_info(&_vf, -1)->channels;
|
||||
}
|
||||
|
||||
|
||||
- (NSString *)description
|
||||
{
|
||||
return [NSString stringWithFormat:@"<%@ %p>{\"%@\", comments=%@}", [self className], self, _name, [self comments]];
|
||||
}
|
||||
|
||||
|
||||
- (Float64)sampleRate
|
||||
{
|
||||
return ov_info(&_vf, -1)->rate;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)atEnd
|
||||
{
|
||||
return _atEnd;
|
||||
}
|
||||
|
||||
|
||||
- (void)rewindToBeginning
|
||||
{
|
||||
if (!ov_pcm_seek(&_vf, 0)) _atEnd = NO;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)scanToOffset:(uint64_t)inOffset
|
||||
{
|
||||
if (!ov_pcm_seek(&_vf, inOffset))
|
||||
{
|
||||
_atEnd = NO;
|
||||
return YES;
|
||||
}
|
||||
else return NO;
|
||||
}
|
||||
|
||||
|
||||
- (NSString *)name
|
||||
{
|
||||
NSDictionary *comments;
|
||||
NSString *result = nil;
|
||||
|
||||
comments = [self comments];
|
||||
if (nil != comments)
|
||||
{
|
||||
result = [comments objectForKey:@"TITLE"];
|
||||
if (nil == result) result = [comments objectForKey:@"NAME"];
|
||||
}
|
||||
|
||||
if (nil == result) result = [[_name retain] autorelease];
|
||||
if (nil == result) result = [super name];
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
// TODO: optimise, vectorise
|
||||
static void MixDown(float *inChan1, float *inChan2, float *outMix, size_t inCount)
|
||||
{
|
||||
while (inCount--)
|
||||
{
|
||||
*outMix++ = (*inChan1++ + *inChan2++) * 0.5f;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,137 @@
|
|||
/*
|
||||
|
||||
OOCASoundInternal.h
|
||||
|
||||
Declarations used within OOCASound. This file should not be used by client
|
||||
code.
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOSoundInternal.h"
|
||||
#import "OOCASoundChannel.h"
|
||||
#import "OOCABufferedSound.h"
|
||||
#import "OOCAStreamingSound.h"
|
||||
#import <CoreAudio/CoreAudio.h>
|
||||
#import <AudioToolbox/AudioToolbox.h>
|
||||
#import "OOErrorDescription.h"
|
||||
#import "OOLogging.h"
|
||||
|
||||
|
||||
@interface OOSound (Internal)
|
||||
|
||||
- (OSStatus)renderWithFlags:(AudioUnitRenderActionFlags *)ioFlags frames:(UInt32)inNumFrames context:(OOCASoundRenderContext *)ioContext data:(AudioBufferList *)ioData;
|
||||
|
||||
// Called by -play and -stop only if in appropriate state
|
||||
- (BOOL)prepareToPlayWithContext:(OOCASoundRenderContext *)outContext looped:(BOOL)inLoop;
|
||||
- (void)finishStoppingWithContext:(OOCASoundRenderContext)inContext;
|
||||
|
||||
- (BOOL)getAudioStreamBasicDescription:(AudioStreamBasicDescription *)outFormat;
|
||||
|
||||
- (void)incrementPlayingCount;
|
||||
- (void)decrementPlayingCount;
|
||||
|
||||
- (BOOL) isPlaying;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@interface OOSoundMixer (Internal)
|
||||
|
||||
- (BOOL)connectChannel:(OOSoundChannel *)inChannel;
|
||||
- (OSStatus)disconnectChannel:(OOSoundChannel *)inChannel;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
extern BOOL gOOSoundSetUp, gOOSoundBroken;
|
||||
|
||||
extern NSString * const kOOLogDeprecatedMethodOOCASound;
|
||||
extern NSString * const kOOLogSoundInitError;
|
||||
|
||||
#define kOOLogUnconvertedNSLog @"unclassified.OOCASound"
|
||||
|
||||
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4
|
||||
#import </usr/include/libkern/OSAtomic.h>
|
||||
|
||||
static inline void OOSoundAtomicAdd(int32_t delta, int32_t *value)
|
||||
{
|
||||
OSAtomicAdd32(delta, value);
|
||||
}
|
||||
#else
|
||||
static inline void OOSoundAtomicAdd(int32_t delta, int32_t *value)
|
||||
{
|
||||
OTAtomicAdd32(delta, (SInt32 *)value);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// Wrappers for AU APIs changed in Leopard SDK
|
||||
#if OOLITE_LEOPARD
|
||||
|
||||
static inline OSStatus OOAUGraphAddNode(AUGraph inGraph, const ComponentDescription *inDescription, AUNode *outNode)
|
||||
{
|
||||
return AUGraphAddNode(inGraph, inDescription, outNode);
|
||||
}
|
||||
|
||||
|
||||
static inline OSStatus OOAUGraphNodeInfo(AUGraph inGraph, AUNode inNode, ComponentDescription *outDescription, AudioUnit *outAudioUnit)
|
||||
{
|
||||
return AUGraphNodeInfo(inGraph, inNode, outDescription, outAudioUnit);
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
static inline OSStatus OOAUGraphAddNode(AUGraph inGraph, const ComponentDescription *inDescription, AUNode *outNode)
|
||||
{
|
||||
return AUGraphNewNode(inGraph, inDescription, 0, NULL, outNode);
|
||||
}
|
||||
|
||||
|
||||
static inline OSStatus OOAUGraphNodeInfo(AUGraph inGraph, AUNode inNode, ComponentDescription *outDescription, AudioUnit *outAudioUnit)
|
||||
{
|
||||
return AUGraphGetNodeInfo(inGraph, inNode, outDescription, NULL, NULL, outAudioUnit);
|
||||
}
|
||||
|
||||
#endif
|
|
@ -0,0 +1,102 @@
|
|||
/*
|
||||
|
||||
OOCASoundMixer.h
|
||||
|
||||
Class responsible for managing and mixing sound channels. This class is an
|
||||
implementation detail. Do not use it directly; use an OOSoundSource to play an
|
||||
OOSound.
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <mach/port.h>
|
||||
#import <AudioToolbox/AudioToolbox.h>
|
||||
|
||||
@class OOMusic, OOSoundChannel, OOSoundSource;
|
||||
|
||||
|
||||
enum
|
||||
{
|
||||
kMixerGeneralChannels = 32
|
||||
};
|
||||
|
||||
|
||||
#define SUPPORT_SOUND_INSPECTOR 0
|
||||
|
||||
|
||||
@interface OOSoundMixer: NSObject
|
||||
{
|
||||
OOSoundChannel *_channels[kMixerGeneralChannels];
|
||||
OOSoundChannel *_freeList;
|
||||
NSLock *_listLock;
|
||||
|
||||
AUGraph _graph;
|
||||
AUNode _mixerNode;
|
||||
AUNode _outputNode;
|
||||
AudioUnit _mixerUnit;
|
||||
|
||||
uint32_t _activeChannels;
|
||||
uint32_t _maxChannels;
|
||||
uint32_t _playMask;
|
||||
|
||||
#if SUPPORT_SOUND_INSPECTOR
|
||||
IBOutlet NSMatrix *checkBoxes;
|
||||
IBOutlet NSTextField *currentField;
|
||||
IBOutlet NSTextField *maxField;
|
||||
IBOutlet NSTextField *loadField;
|
||||
IBOutlet NSProgressIndicator *loadBar;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Singleton accessor
|
||||
+ (id) sharedMixer;
|
||||
|
||||
- (void) update;
|
||||
|
||||
- (void) setMasterVolume:(float)inVolume;
|
||||
|
||||
- (OOSoundChannel *) popChannel;
|
||||
- (void) pushChannel:(OOSoundChannel *)inChannel;
|
||||
|
||||
@end
|
|
@ -0,0 +1,381 @@
|
|||
/*
|
||||
|
||||
OOCASoundMixer.m
|
||||
|
||||
Class responsible for managing and mixing sound channels. This class is an
|
||||
implementation detail. Do not use it directly; use an OOSoundSource to play an
|
||||
OOSound.
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOCASoundInternal.h"
|
||||
#import "OOCASoundChannel.h"
|
||||
#import "NSThreadOOExtensions.h"
|
||||
|
||||
|
||||
static NSString * const kOOLogSoundInspetorNotLoaded = @"sound.mixer.inspector.loadFailed";
|
||||
static NSString * const kOOLogSoundMixerOutOfChannels = @"sound.mixer.outOfChannels";
|
||||
static NSString * const kOOLogSoundMixerReplacingBrokenChannel = @"sound.mixer.replacingBrokenChannel";
|
||||
static NSString * const kOOLogSoundMixerFailedToConnectChannel = @"sound.mixer.failedToConnectChannel";
|
||||
|
||||
|
||||
@interface OOSoundMixer (Private)
|
||||
|
||||
- (void)pushChannel:(OOSoundChannel *)inChannel;
|
||||
- (OOSoundChannel *)popChannel;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
static OOSoundMixer *sSingleton = nil;
|
||||
|
||||
@implementation OOSoundMixer
|
||||
|
||||
+ (id) sharedMixer
|
||||
{
|
||||
if (nil == sSingleton)
|
||||
{
|
||||
[[self alloc] init];
|
||||
}
|
||||
return sSingleton;
|
||||
}
|
||||
|
||||
|
||||
- (id)init
|
||||
{
|
||||
OSStatus err = noErr;
|
||||
BOOL OK;
|
||||
uint32_t idx = 0, count = kMixerGeneralChannels;
|
||||
OOSoundChannel *temp;
|
||||
ComponentDescription desc;
|
||||
|
||||
if (!gOOSoundSetUp) [OOSound setUp];
|
||||
|
||||
self = [super init];
|
||||
if (nil != self)
|
||||
{
|
||||
_listLock = [[NSLock alloc] init];
|
||||
[_listLock ooSetName:@"OOSoundMixer list lock"];
|
||||
OK = nil != _listLock;
|
||||
|
||||
if (OK)
|
||||
{
|
||||
// Create audio graph
|
||||
err = NewAUGraph(&_graph);
|
||||
|
||||
// Add output node
|
||||
desc.componentType = kAudioUnitType_Output;
|
||||
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
|
||||
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
|
||||
desc.componentFlags = 0;
|
||||
desc.componentFlagsMask = 0;
|
||||
if (!err) err = OOAUGraphAddNode(_graph, &desc, &_outputNode);
|
||||
|
||||
// Add mixer node
|
||||
desc.componentType = kAudioUnitType_Mixer;
|
||||
desc.componentSubType = kAudioUnitSubType_StereoMixer;
|
||||
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
|
||||
desc.componentFlags = 0;
|
||||
desc.componentFlagsMask = 0;
|
||||
if (!err) err = OOAUGraphAddNode(_graph, &desc, &_mixerNode);
|
||||
|
||||
// Connect mixer to output
|
||||
if (!err) err = AUGraphConnectNodeInput(_graph, _mixerNode, 0, _outputNode, 0);
|
||||
|
||||
// Open the graph (turn it into concrete AUs) and extract mixer AU
|
||||
if (!err) err = AUGraphOpen(_graph);
|
||||
if (!err) err = OOAUGraphNodeInfo(_graph, _mixerNode, NULL, &_mixerUnit);
|
||||
|
||||
if (err) OK = NO;
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
// Allocate channels
|
||||
do
|
||||
{
|
||||
temp = [[OOSoundChannel alloc] initWithID:count auGraph:_graph];
|
||||
if (nil != temp)
|
||||
{
|
||||
_channels[idx++] = temp;
|
||||
[temp setNext:_freeList];
|
||||
_freeList = temp;
|
||||
}
|
||||
} while (--count);
|
||||
|
||||
if (noErr != AUGraphInitialize(_graph)) OK = NO;
|
||||
}
|
||||
|
||||
if (!OK)
|
||||
{
|
||||
[super release];
|
||||
self = nil;
|
||||
}
|
||||
|
||||
#if SUPPORT_SOUND_INSPECTOR
|
||||
if (![NSBundle loadNibNamed:@"SoundInspector" owner:self])
|
||||
{
|
||||
OOLog(kOOLogSoundInspetorNotLoaded, @"Failed to load sound inspector panel.");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
sSingleton = self;
|
||||
|
||||
return sSingleton;
|
||||
}
|
||||
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
uint32_t idx;
|
||||
|
||||
if (NULL != _graph)
|
||||
{
|
||||
AUGraphStop(_graph);
|
||||
AUGraphUninitialize(_graph);
|
||||
AUGraphClose(_graph);
|
||||
DisposeAUGraph(_graph);
|
||||
}
|
||||
for (idx = 0; idx != kMixerGeneralChannels; ++idx)
|
||||
{
|
||||
[_channels[idx] release];
|
||||
}
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
- (void)channel:(OOSoundChannel *)inChannel didFinishPlayingSound:(OOSound *)inSound
|
||||
{
|
||||
uint32_t ID;
|
||||
|
||||
[inSound decrementPlayingCount];
|
||||
|
||||
if (![inChannel isOK])
|
||||
{
|
||||
OOLog(kOOLogSoundMixerReplacingBrokenChannel, @"Sound mixer: replacing broken channel %@.", inChannel);
|
||||
ID = [inChannel ID];
|
||||
[inChannel release];
|
||||
inChannel = [[OOSoundChannel alloc] initWithID:ID auGraph:_graph];
|
||||
}
|
||||
|
||||
[self pushChannel:inChannel];
|
||||
}
|
||||
|
||||
|
||||
- (void)update
|
||||
{
|
||||
#if SUPPORT_SOUND_INSPECTOR
|
||||
uint32_t i;
|
||||
Float32 load;
|
||||
|
||||
for (i = 0; i != kMixerGeneralChannels && i != 32; ++i)
|
||||
{
|
||||
[[checkBoxes cellWithTag:i] setIntValue:_playMask & (1 << i)];
|
||||
}
|
||||
|
||||
if (_maxChannels < _activeChannels)
|
||||
{
|
||||
_maxChannels = _activeChannels;
|
||||
[maxField setIntValue:_maxChannels];
|
||||
}
|
||||
[currentField setIntValue:_activeChannels];
|
||||
|
||||
if (!AUGraphGetCPULoad(_graph, &load))
|
||||
{
|
||||
[loadBar setDoubleValue:load];
|
||||
[loadField setObjectValue:[NSString stringWithFormat:@"%.2g%%", load * 100.0]];
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
#if SUPPORT_SOUND_INSPECTOR
|
||||
- (void)awakeFromNib
|
||||
{
|
||||
uint32_t i;
|
||||
|
||||
if (nil != checkBoxes)
|
||||
{
|
||||
for (i = 0; i != kMixerGeneralChannels; ++i)
|
||||
{
|
||||
[[checkBoxes cellWithTag:i] setIntValue:0];
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
- (void)setMasterVolume:(float)inVolume
|
||||
{
|
||||
AudioUnitSetParameter(_mixerUnit, kStereoMixerParam_Volume, kAudioUnitScope_Output, 0, inVolume, 0);
|
||||
}
|
||||
|
||||
|
||||
- (OOSoundChannel *)popChannel
|
||||
{
|
||||
OOSoundChannel *result;
|
||||
uint32_t ID;
|
||||
|
||||
[_listLock lock];
|
||||
result = _freeList;
|
||||
_freeList = [result next];
|
||||
|
||||
if (nil != result)
|
||||
{
|
||||
if (0 == _activeChannels++)
|
||||
{
|
||||
AUGraphStart(_graph);
|
||||
}
|
||||
|
||||
ID = [result ID] - 1;
|
||||
if (ID < 32) _playMask |= (1 << ID);
|
||||
}
|
||||
[_listLock unlock];
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
- (void)pushChannel:(OOSoundChannel *)inChannel
|
||||
{
|
||||
uint32_t ID;
|
||||
|
||||
assert(nil != inChannel);
|
||||
|
||||
[_listLock lock];
|
||||
|
||||
[inChannel setNext:_freeList];
|
||||
_freeList = inChannel;
|
||||
|
||||
if (0 == --_activeChannels)
|
||||
{
|
||||
AUGraphStop(_graph);
|
||||
}
|
||||
ID = [inChannel ID] - 1;
|
||||
if (ID < 32) _playMask &= ~(1 << ID);
|
||||
[_listLock unlock];
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)connectChannel:(OOSoundChannel *)inChannel
|
||||
{
|
||||
AUNode node;
|
||||
OSStatus err;
|
||||
|
||||
assert(nil != inChannel);
|
||||
|
||||
node = [inChannel auSubGraphNode];
|
||||
err = AUGraphConnectNodeInput(_graph, node, 0, _mixerNode, [inChannel ID]);
|
||||
if (!err) err = AUGraphUpdate(_graph, NULL);
|
||||
|
||||
if (err) OOLog(kOOLogSoundMixerFailedToConnectChannel, @"Sound mixer: failed to connect channel %@, error = %@.", inChannel, AudioErrorNSString(err));
|
||||
|
||||
return !err;
|
||||
}
|
||||
|
||||
|
||||
- (OSStatus)disconnectChannel:(OOSoundChannel *)inChannel
|
||||
{
|
||||
OSStatus err;
|
||||
|
||||
assert(nil != inChannel);
|
||||
|
||||
err = AUGraphDisconnectNodeInput(_graph, _mixerNode, [inChannel ID]);
|
||||
if (noErr == err) AUGraphUpdate(_graph, NULL);
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation OOSoundMixer (Singleton)
|
||||
|
||||
/* Canonical singleton boilerplate.
|
||||
See Cocoa Fundamentals Guide: Creating a Singleton Instance.
|
||||
See also +sharedMixer above.
|
||||
|
||||
NOTE: assumes single-threaded access.
|
||||
*/
|
||||
|
||||
+ (id)allocWithZone:(NSZone *)inZone
|
||||
{
|
||||
if (sSingleton == nil)
|
||||
{
|
||||
sSingleton = [super allocWithZone:inZone];
|
||||
return sSingleton;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
- (id)copyWithZone:(NSZone *)inZone
|
||||
{
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (id)retain
|
||||
{
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (OOUInteger)retainCount
|
||||
{
|
||||
return UINT_MAX;
|
||||
}
|
||||
|
||||
|
||||
- (void)release
|
||||
{}
|
||||
|
||||
|
||||
- (id)autorelease
|
||||
{
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,63 @@
|
|||
/*
|
||||
|
||||
OOCASoundReferencePoint.h
|
||||
|
||||
A reference point for positional audio. The position of an OOSoundSource is
|
||||
specified relative to an OOSoundReferencePoint. Since positional audio is
|
||||
currently unimplemented, this class does nothing.
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2006 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "OOMaths.h"
|
||||
|
||||
|
||||
@interface OOSoundReferencePoint: NSObject
|
||||
|
||||
// Positional audio attributes are ignored in this implementation
|
||||
- (void)setPosition:(Vector)inPosition;
|
||||
- (void)setVelocity:(Vector)inVelocity;
|
||||
- (void)setOrientation:(Vector)inOrientation;
|
||||
|
||||
@end
|
|
@ -0,0 +1,70 @@
|
|||
/*
|
||||
|
||||
OOCASoundReferencePoint.m
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOCASoundReferencePoint.h"
|
||||
|
||||
|
||||
@implementation OOSoundReferencePoint
|
||||
|
||||
- (void)setPosition:(Vector)inPosition
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
- (void)setVelocity:(Vector)inVelocity
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
- (void)setOrientation:(Vector)inOrientation
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,66 @@
|
|||
/*
|
||||
|
||||
OOCAStreamingSound.h
|
||||
|
||||
Subclass of OOSound which streams audio from disk.
|
||||
|
||||
This class is an implementation detail. Do not use it directly; use OOSound.
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "OOSound.h"
|
||||
|
||||
@class OOCASoundDecoder;
|
||||
@class VirtualRingBuffer;
|
||||
|
||||
|
||||
@interface OOCAStreamingSound: OOSound
|
||||
{
|
||||
OOCASoundDecoder *_decoder;
|
||||
}
|
||||
|
||||
- (id) initWithDecoder:(OOCASoundDecoder *)inDecoder;
|
||||
|
||||
@end
|
|
@ -0,0 +1,405 @@
|
|||
/*
|
||||
|
||||
OOCAStreamingSound.m
|
||||
|
||||
This class is an implementation detail. Do not use it directly; use OOSound.
|
||||
|
||||
OOCASound - Core Audio sound implementation for Oolite.
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2005-2008 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOCASoundInternal.h"
|
||||
#import "OOCASoundDecoder.h"
|
||||
#import "VirtualRingBuffer.h"
|
||||
#import "NSThreadOOExtensions.h"
|
||||
|
||||
|
||||
static NSString * const kOOLogSoundStreamingRefill = @"sound.streaming.refill";
|
||||
static NSString * const kOOLogSoundStreamingLoop = @"sound.streaming.loop";
|
||||
static NSString * const kOOLogSoundStreamingUnderflow = @"sound.streaming.underflow";
|
||||
|
||||
|
||||
static BOOL sFeederThreadActive = NO;
|
||||
static MPQueueID sFeederQueue = kInvalidID;
|
||||
|
||||
|
||||
// For IMP caching of VirtualRingBuffer methods
|
||||
typedef UInt32 (*VRB_lengthAvailableToReadReturningPointerIMP)(id inSelf, SEL inSel, void ** outReturnedReadPointer);
|
||||
typedef void (*VRB_didReadLengthIMP)(id inSelf, SEL inSel, UInt32 inLength);
|
||||
|
||||
#define kSEL_VRB_lengthAvailableToReadReturningPointer @selector(lengthAvailableToReadReturningPointer:)
|
||||
#define kSEL_VRB_didReadLength @selector(didReadLength:)
|
||||
|
||||
static VRB_lengthAvailableToReadReturningPointerIMP VRB_lengthAvailableToReadReturningPointer = NULL;
|
||||
static VRB_didReadLengthIMP VRB_didReadLength = NULL;
|
||||
|
||||
|
||||
typedef struct
|
||||
{
|
||||
uint64_t readOffset;
|
||||
VirtualRingBuffer *bufferL,
|
||||
*bufferR;
|
||||
int32_t pendingCount;
|
||||
BOOL atEnd,
|
||||
loop,
|
||||
empty,
|
||||
stopped;
|
||||
} *OOCAStreamingSoundRenderContext;
|
||||
|
||||
|
||||
@interface OOCAStreamingSound (Internal)
|
||||
|
||||
+ (void)feederThread:ignored;
|
||||
- (BOOL)setUpAudioUnit;
|
||||
- (void)fillBuffersWithContext:(OOCAStreamingSoundRenderContext)inContext;
|
||||
- (void)releaseContext:(OOCAStreamingSoundRenderContext)inContext;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
enum
|
||||
{
|
||||
// Port messages
|
||||
kMsgFillBuffers = 1UL
|
||||
};
|
||||
|
||||
|
||||
enum
|
||||
{
|
||||
kStreamBufferCount = 400000, // Number of frames in buffer
|
||||
kStreamBufferRefillThreshold = kStreamBufferCount / 3, // When to request refill
|
||||
kMinRebufferFrames = kStreamBufferCount / 10, // When to ignore fill request (may get multiple requests before filler thread is scheduled)
|
||||
kStreamBufferSize = kStreamBufferCount * sizeof (float)
|
||||
};
|
||||
|
||||
|
||||
@implementation OOCAStreamingSound
|
||||
|
||||
- (id)initWithDecoder:(OOCASoundDecoder *)inDecoder
|
||||
{
|
||||
BOOL OK = YES;
|
||||
|
||||
assert(gOOSoundSetUp);
|
||||
if (gOOSoundBroken || nil == inDecoder) OK = NO;
|
||||
|
||||
if (OK && VRB_lengthAvailableToReadReturningPointer == NULL)
|
||||
{
|
||||
VRB_lengthAvailableToReadReturningPointer = (VRB_lengthAvailableToReadReturningPointerIMP)[VirtualRingBuffer instanceMethodForSelector:@selector(lengthAvailableToReadReturningPointer:)];
|
||||
VRB_didReadLength = (VRB_didReadLengthIMP)[VirtualRingBuffer instanceMethodForSelector:@selector(didReadLength:)];
|
||||
|
||||
if (VRB_lengthAvailableToReadReturningPointer == NULL || VRB_didReadLength == NULL) OK = NO;
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
self = [super init];
|
||||
if (nil == self) OK = NO;
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
_decoder = [inDecoder retain];
|
||||
}
|
||||
|
||||
if (!OK)
|
||||
{
|
||||
[self release];
|
||||
self = nil;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
assert(![self isPlaying]);
|
||||
[_decoder release];
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
- (void)play
|
||||
{
|
||||
[[OOSoundMixer sharedMixer] playSound:self];
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)prepareToPlayWithContext:(OOCASoundRenderContext *)outContext looped:(BOOL)inLoop
|
||||
{
|
||||
BOOL OK = YES;
|
||||
OOCAStreamingSoundRenderContext context = NULL;
|
||||
|
||||
assert(outContext != NULL);
|
||||
|
||||
if (OK)
|
||||
{
|
||||
context = calloc(1, sizeof *context);
|
||||
if (context != NULL)
|
||||
{
|
||||
*outContext = (OOCASoundRenderContext)context;
|
||||
context->loop = inLoop;
|
||||
context->empty = YES;
|
||||
}
|
||||
else
|
||||
{
|
||||
OK = NO;
|
||||
}
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
context->bufferL = [[VirtualRingBuffer alloc] initWithLength:kStreamBufferSize];
|
||||
context->bufferR = [[VirtualRingBuffer alloc] initWithLength:kStreamBufferSize];
|
||||
if (!context->bufferL || !context->bufferR)
|
||||
{
|
||||
OK = NO;
|
||||
}
|
||||
}
|
||||
|
||||
if (OK && sFeederQueue == kInvalidID)
|
||||
{
|
||||
OK = (noErr == MPCreateQueue(&sFeederQueue)) && (sFeederQueue != kInvalidID);
|
||||
}
|
||||
|
||||
if (OK)
|
||||
{
|
||||
if (!sFeederThreadActive) [NSThread detachNewThreadSelector:@selector(feederThread:) toTarget:[OOCAStreamingSound class] withObject:nil];
|
||||
[self retain]; // Will be released by fillBuffers... when stopped is true and pendingCount is 0.
|
||||
++context->pendingCount;
|
||||
[self fillBuffersWithContext:context];
|
||||
}
|
||||
|
||||
return OK;
|
||||
}
|
||||
|
||||
|
||||
- (void)finishStoppingWithContext:(OOCASoundRenderContext)inContext
|
||||
{
|
||||
OOCAStreamingSoundRenderContext context;
|
||||
|
||||
context = (OOCAStreamingSoundRenderContext) inContext;
|
||||
|
||||
[gOOCASoundSyncLock lock];
|
||||
context->stopped = YES;
|
||||
if (0 == context->pendingCount)
|
||||
{
|
||||
OOLog(@"sound.streaming.releaseContext.immediate", @"Streaming sound %@ stopped with 0 pendingCount, releasing context.", self);
|
||||
[self releaseContext:context];
|
||||
}
|
||||
else
|
||||
{
|
||||
OOLog(@"sound.streaming.releaseContext.deferring", @"Streaming sound %@ stopped with %i pendingCount, deferring release.", self, context->pendingCount);
|
||||
}
|
||||
[gOOCASoundSyncLock unlock];
|
||||
}
|
||||
|
||||
|
||||
+ (void)feederThread:ignored
|
||||
{
|
||||
uintptr_t msgID;
|
||||
void *param1, *param2;
|
||||
OOCAStreamingSound *sound;
|
||||
OOCAStreamingSoundRenderContext context = 0;
|
||||
NSAutoreleasePool *pool = nil;
|
||||
|
||||
assert(sFeederQueue != kInvalidID);
|
||||
|
||||
[NSThread ooSetCurrentThreadName:@"OOCAStreamingSound feeder thread"];
|
||||
sFeederThreadActive = YES;
|
||||
|
||||
for (;;)
|
||||
{
|
||||
if (noErr != MPWaitOnQueue(sFeederQueue, (void **)&msgID, ¶m1, ¶m2, kDurationForever)) continue;
|
||||
|
||||
pool = [[NSAutoreleasePool alloc] init];
|
||||
|
||||
switch (msgID)
|
||||
{
|
||||
case kMsgFillBuffers:
|
||||
sound = param1;
|
||||
context = param2;
|
||||
[sound fillBuffersWithContext:context];
|
||||
}
|
||||
|
||||
[pool release];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void)fillBuffersWithContext:(OOCAStreamingSoundRenderContext)inContext
|
||||
{
|
||||
size_t spaceL, spaceR;
|
||||
void *ptrL, *ptrR;
|
||||
size_t frames;
|
||||
|
||||
[gOOCASoundSyncLock lock];
|
||||
spaceL = [inContext->bufferL lengthAvailableToWriteReturningPointer:&ptrL];
|
||||
spaceR = [inContext->bufferR lengthAvailableToWriteReturningPointer:&ptrR];
|
||||
|
||||
// These ought to be the same
|
||||
frames = MIN(spaceL, spaceR) / sizeof (float);
|
||||
|
||||
if (kMinRebufferFrames < frames)
|
||||
{
|
||||
if (![_decoder scanToOffset:inContext->readOffset])
|
||||
{
|
||||
inContext->atEnd = YES;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (kStreamBufferCount < frames)
|
||||
{
|
||||
if (!inContext->empty) OOLog(kOOLogSoundStreamingUnderflow, @"Buffer underflow for sound %@.", self);
|
||||
inContext->empty = NO;
|
||||
}
|
||||
|
||||
OOLog(kOOLogSoundStreamingRefill, @"Buffering %u frames for sound %@.", frames, self);
|
||||
frames = [_decoder streamStereoToBufferL:(float *)ptrL bufferR:(float *)ptrR maxFrames:frames];
|
||||
inContext->readOffset += frames;
|
||||
[inContext->bufferL didWriteLength:frames * sizeof (float)];
|
||||
[inContext->bufferR didWriteLength:frames * sizeof (float)];
|
||||
|
||||
if ([_decoder atEnd])
|
||||
{
|
||||
if (inContext->loop)
|
||||
{
|
||||
OOLog(kOOLogSoundStreamingLoop, @"Resetting streaming sound %@ for looping.", self);
|
||||
inContext->readOffset = 0;
|
||||
}
|
||||
else inContext->atEnd = YES;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OOSoundAtomicAdd(-1, &inContext->pendingCount);
|
||||
if (inContext->pendingCount == 0 && inContext->stopped)
|
||||
{
|
||||
OOLog(@"sound.streaming.releaseContext.deferred", @"Stopped streaming sound %@ reached 0 pendingCount, releasing context.", self);
|
||||
[self releaseContext:inContext];
|
||||
}
|
||||
|
||||
[gOOCASoundSyncLock unlock];
|
||||
}
|
||||
|
||||
|
||||
- (void)releaseContext:(OOCAStreamingSoundRenderContext)inContext
|
||||
{
|
||||
[inContext->bufferL release];
|
||||
[inContext->bufferR release];
|
||||
free(inContext);
|
||||
[self autorelease];
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)getAudioStreamBasicDescription:(AudioStreamBasicDescription *)outFormat
|
||||
{
|
||||
assert(NULL != outFormat);
|
||||
|
||||
outFormat->mSampleRate = [_decoder sampleRate];
|
||||
outFormat->mFormatID = kAudioFormatLinearPCM;
|
||||
outFormat->mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
|
||||
outFormat->mBytesPerPacket = sizeof (float);
|
||||
outFormat->mFramesPerPacket = 1;
|
||||
outFormat->mBytesPerFrame = sizeof (float);
|
||||
outFormat->mChannelsPerFrame = 2;
|
||||
outFormat->mBitsPerChannel = sizeof (float) * 8;
|
||||
outFormat->mReserved = 0;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
- (OSStatus)renderWithFlags:(AudioUnitRenderActionFlags *)ioFlags frames:(UInt32)inNumFrames context:(OOCASoundRenderContext *)ioContext data:(AudioBufferList *)ioData
|
||||
{
|
||||
size_t available, availL, availR, remaining, underflow;
|
||||
size_t numBytes;
|
||||
void *ptrL, *ptrR;
|
||||
OOCAStreamingSoundRenderContext context;
|
||||
|
||||
context = (OOCAStreamingSoundRenderContext)*ioContext;
|
||||
|
||||
assert(2 == ioData->mNumberBuffers);
|
||||
|
||||
availL = VRB_lengthAvailableToReadReturningPointer(context->bufferL, kSEL_VRB_lengthAvailableToReadReturningPointer, &ptrL);
|
||||
availR = VRB_lengthAvailableToReadReturningPointer(context->bufferR, kSEL_VRB_lengthAvailableToReadReturningPointer, &ptrR);
|
||||
|
||||
numBytes = inNumFrames * sizeof (float);
|
||||
|
||||
available = MIN(availL, availR);
|
||||
remaining = available;
|
||||
if (numBytes < available) available = numBytes;
|
||||
|
||||
bcopy(ptrL, ioData->mBuffers[0].mData, available);
|
||||
bcopy(ptrR, ioData->mBuffers[1].mData, available);
|
||||
|
||||
VRB_didReadLength(context->bufferL, kSEL_VRB_didReadLength, available);
|
||||
VRB_didReadLength(context->bufferR, kSEL_VRB_didReadLength, available);
|
||||
|
||||
if (available < numBytes)
|
||||
{
|
||||
// Buffer underflow! Fill with silence.
|
||||
underflow = numBytes - available;
|
||||
|
||||
if (0 == available) *ioFlags |= kAudioUnitRenderAction_OutputIsSilence;
|
||||
|
||||
bzero(ioData->mBuffers[0].mData + available, underflow);
|
||||
bzero(ioData->mBuffers[0].mData + available, underflow);
|
||||
}
|
||||
|
||||
remaining -= available;
|
||||
if (!context->atEnd && remaining < kStreamBufferRefillThreshold * sizeof (float) && sFeederQueue != kInvalidID)
|
||||
{
|
||||
OOSoundAtomicAdd(1, &context->pendingCount);
|
||||
MPNotifyQueue(sFeederQueue, (void *)kMsgFillBuffers, self, context);
|
||||
}
|
||||
|
||||
return (context->atEnd && remaining == 0) ? endOfDataReached : noErr;
|
||||
}
|
||||
|
||||
|
||||
- (NSString *)name
|
||||
{
|
||||
return [_decoder name];
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,23 @@
|
|||
/*
|
||||
|
||||
OOErrorDescription.h
|
||||
|
||||
A set of functions for mapping various types of Mac OS error codes to names,
|
||||
primarily for debugging purposes.
|
||||
|
||||
For OOCASound - Core Audio sound implementation for Oolite.
|
||||
By Jens Ayton, 2005
|
||||
|
||||
This file is hereby placed in the public domain.
|
||||
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
|
||||
// Provide descriptions of various Mac-specific error codes
|
||||
NSString *OSStatusErrorNSString(OSStatus inCode);
|
||||
NSString *AudioErrorNSString(ComponentResult inCode);
|
||||
NSString *KernelResultNSString(kern_return_t inCode);
|
||||
NSString *FourCharCodeToNSString(FourCharCode inCode);
|
||||
NSString *AudioErrorShortNSString(OSStatus inCode);
|
|
@ -0,0 +1,257 @@
|
|||
/*
|
||||
|
||||
OOErrorDescription.m
|
||||
|
||||
A set of functions for mapping various types of Mac OS error codes to names,
|
||||
primarily for debugging purposes.
|
||||
|
||||
For OOCASound - Core Audio sound implementation for Oolite.
|
||||
By Jens Ayton, 2005
|
||||
|
||||
This file is hereby placed in the public domain.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOErrorDescription.h"
|
||||
#import <CoreAudio/CoreAudio.h>
|
||||
#import <AudioToolbox/AudioToolbox.h>
|
||||
#import <Carbon/Carbon.h>
|
||||
|
||||
|
||||
#define CASE(foo) case foo: return @#foo
|
||||
|
||||
|
||||
#ifndef NDEBUG
|
||||
static NSString *GetGenericOSStatusString(OSStatus inCode);
|
||||
#endif
|
||||
|
||||
|
||||
NSString *OSStatusErrorNSString(OSStatus inCode)
|
||||
{
|
||||
NSString *result = nil;
|
||||
|
||||
#ifndef NDEBUG
|
||||
result = GetGenericOSStatusString(inCode);
|
||||
#else
|
||||
if (noErr == inCode) result = @"no error";
|
||||
#endif
|
||||
|
||||
if (nil == result) result = [NSString stringWithFormat:@"%i", (int)inCode];
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
NSString *AudioErrorNSString(ComponentResult inCode)
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
switch (inCode)
|
||||
{
|
||||
CASE(kAudioConverterErr_FormatNotSupported);
|
||||
CASE(kAudioConverterErr_OperationNotSupported);
|
||||
CASE(kAudioConverterErr_PropertyNotSupported);
|
||||
CASE(kAudioConverterErr_InvalidInputSize);
|
||||
CASE(kAudioConverterErr_InvalidOutputSize);
|
||||
CASE(kAudioConverterErr_UnspecifiedError);
|
||||
CASE(kAudioConverterErr_BadPropertySizeError);
|
||||
CASE(kAudioConverterErr_RequiresPacketDescriptionsError);
|
||||
CASE(kAudioConverterErr_InputSampleRateOutOfRange);
|
||||
CASE(kAudioConverterErr_OutputSampleRateOutOfRange);
|
||||
|
||||
CASE(kAudioCodecUnknownPropertyError);
|
||||
CASE(kAudioCodecIllegalOperationError);
|
||||
CASE(kAudioCodecUnsupportedFormatError);
|
||||
CASE(kAudioCodecStateError);
|
||||
CASE(kAudioCodecNotEnoughBufferSpaceError);
|
||||
|
||||
CASE(kAudioUnitErr_InvalidProperty);
|
||||
CASE(kAudioUnitErr_InvalidParameter);
|
||||
CASE(kAudioUnitErr_InvalidElement);
|
||||
CASE(kAudioUnitErr_NoConnection);
|
||||
CASE(kAudioUnitErr_FailedInitialization);
|
||||
CASE(kAudioUnitErr_TooManyFramesToProcess);
|
||||
CASE(kAudioUnitErr_IllegalInstrument);
|
||||
CASE(kAudioUnitErr_InstrumentTypeNotFound);
|
||||
CASE(kAudioUnitErr_InvalidFile);
|
||||
CASE(kAudioUnitErr_UnknownFileType);
|
||||
CASE(kAudioUnitErr_FileNotSpecified);
|
||||
CASE(kAudioUnitErr_FormatNotSupported);
|
||||
CASE(kAudioUnitErr_Uninitialized);
|
||||
CASE(kAudioUnitErr_InvalidScope);
|
||||
CASE(kAudioUnitErr_PropertyNotWritable);
|
||||
CASE(kAudioUnitErr_CannotDoInCurrentContext);
|
||||
CASE(kAudioUnitErr_InvalidPropertyValue);
|
||||
CASE(kAudioUnitErr_PropertyNotInUse);
|
||||
CASE(kAudioUnitErr_Initialized);
|
||||
CASE(kAudioUnitErr_InvalidOfflineRender);
|
||||
CASE(kAudioUnitErr_Unauthorized);
|
||||
|
||||
CASE(kAUGraphErr_NodeNotFound);
|
||||
CASE(kAUGraphErr_InvalidConnection);
|
||||
CASE(kAUGraphErr_OutputNodeErr);
|
||||
CASE(kAUGraphErr_InvalidAudioUnit);
|
||||
|
||||
default:
|
||||
{
|
||||
NSString *result = GetGenericOSStatusString(inCode);
|
||||
if (nil != result) return result;
|
||||
}
|
||||
}
|
||||
#else
|
||||
if (noErr == inCode) return @"no error";
|
||||
#endif
|
||||
|
||||
return AudioErrorShortNSString(inCode);
|
||||
}
|
||||
|
||||
|
||||
NSString *AudioErrorShortNSString(OSStatus inCode)
|
||||
{
|
||||
#define PRINTABLE(x) (!((x) < ' ') && !((x) == 0x7F))
|
||||
|
||||
if (!(inCode & 0x80000000) &&
|
||||
PRINTABLE(inCode >> 24) &&
|
||||
PRINTABLE((inCode >> 16) & 0xFF) &&
|
||||
PRINTABLE((inCode >> 8) & 0xFF) &&
|
||||
PRINTABLE(inCode & 0xFF))
|
||||
{
|
||||
// Assume a four-char code
|
||||
return [NSString stringWithFormat:@"\'%@\'", FourCharCodeToNSString(inCode)];
|
||||
}
|
||||
else
|
||||
{
|
||||
return [NSString stringWithFormat:@"%i", (int)inCode];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
NSString *KernelResultNSString(kern_return_t inCode)
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
switch (inCode)
|
||||
{
|
||||
CASE(KERN_INVALID_ADDRESS);
|
||||
CASE(KERN_PROTECTION_FAILURE);
|
||||
CASE(KERN_NO_SPACE);
|
||||
CASE(KERN_INVALID_ARGUMENT);
|
||||
CASE(KERN_FAILURE);
|
||||
CASE(KERN_RESOURCE_SHORTAGE);
|
||||
CASE(KERN_NOT_RECEIVER);
|
||||
CASE(KERN_NO_ACCESS);
|
||||
CASE(KERN_MEMORY_FAILURE);
|
||||
CASE(KERN_MEMORY_ERROR);
|
||||
CASE(KERN_ALREADY_IN_SET);
|
||||
CASE(KERN_NOT_IN_SET);
|
||||
CASE(KERN_NAME_EXISTS);
|
||||
CASE(KERN_ABORTED);
|
||||
CASE(KERN_INVALID_NAME);
|
||||
CASE(KERN_INVALID_TASK);
|
||||
CASE(KERN_INVALID_RIGHT);
|
||||
CASE(KERN_INVALID_VALUE);
|
||||
CASE(KERN_UREFS_OVERFLOW);
|
||||
CASE(KERN_INVALID_CAPABILITY);
|
||||
CASE(KERN_RIGHT_EXISTS);
|
||||
CASE(KERN_INVALID_HOST);
|
||||
CASE(KERN_MEMORY_PRESENT);
|
||||
CASE(KERN_MEMORY_DATA_MOVED);
|
||||
CASE(KERN_MEMORY_RESTART_COPY);
|
||||
CASE(KERN_INVALID_PROCESSOR_SET);
|
||||
CASE(KERN_POLICY_LIMIT);
|
||||
CASE(KERN_INVALID_POLICY);
|
||||
CASE(KERN_INVALID_OBJECT);
|
||||
CASE(KERN_ALREADY_WAITING);
|
||||
CASE(KERN_DEFAULT_SET);
|
||||
CASE(KERN_EXCEPTION_PROTECTED);
|
||||
CASE(KERN_INVALID_LEDGER);
|
||||
CASE(KERN_INVALID_MEMORY_CONTROL);
|
||||
CASE(KERN_INVALID_SECURITY);
|
||||
CASE(KERN_NOT_DEPRESSED);
|
||||
CASE(KERN_TERMINATED);
|
||||
CASE(KERN_LOCK_SET_DESTROYED);
|
||||
CASE(KERN_LOCK_UNSTABLE);
|
||||
CASE(KERN_LOCK_OWNED);
|
||||
CASE(KERN_LOCK_OWNED_SELF);
|
||||
CASE(KERN_SEMAPHORE_DESTROYED);
|
||||
CASE(KERN_RPC_SERVER_TERMINATED);
|
||||
CASE(KERN_RPC_TERMINATE_ORPHAN);
|
||||
CASE(KERN_RPC_CONTINUE_ORPHAN);
|
||||
CASE(KERN_NOT_SUPPORTED);
|
||||
CASE(KERN_NODE_DOWN);
|
||||
CASE(KERN_NOT_WAITING);
|
||||
CASE(KERN_OPERATION_TIMED_OUT);
|
||||
CASE(MACH_MSG_IPC_SPACE);
|
||||
CASE(MACH_MSG_VM_SPACE);
|
||||
CASE(MACH_MSG_IPC_KERNEL);
|
||||
CASE(MACH_MSG_VM_KERNEL);
|
||||
CASE(MACH_SEND_IN_PROGRESS);
|
||||
CASE(MACH_SEND_INVALID_DATA);
|
||||
CASE(MACH_SEND_INVALID_DEST);
|
||||
CASE(MACH_SEND_TIMED_OUT);
|
||||
CASE(MACH_SEND_INTERRUPTED);
|
||||
CASE(MACH_SEND_MSG_TOO_SMALL);
|
||||
CASE(MACH_SEND_INVALID_REPLY);
|
||||
CASE(MACH_SEND_INVALID_RIGHT);
|
||||
CASE(MACH_SEND_INVALID_NOTIFY);
|
||||
CASE(MACH_SEND_INVALID_MEMORY);
|
||||
CASE(MACH_SEND_NO_BUFFER);
|
||||
CASE(MACH_SEND_TOO_LARGE);
|
||||
CASE(MACH_SEND_INVALID_TYPE);
|
||||
CASE(MACH_SEND_INVALID_HEADER);
|
||||
CASE(MACH_SEND_INVALID_TRAILER);
|
||||
CASE(MACH_SEND_INVALID_RT_OOL_SIZE);
|
||||
CASE(MACH_RCV_IN_PROGRESS);
|
||||
CASE(MACH_RCV_INVALID_NAME);
|
||||
CASE(MACH_RCV_TIMED_OUT);
|
||||
CASE(MACH_RCV_TOO_LARGE);
|
||||
CASE(MACH_RCV_INTERRUPTED);
|
||||
CASE(MACH_RCV_PORT_CHANGED);
|
||||
CASE(MACH_RCV_INVALID_NOTIFY);
|
||||
CASE(MACH_RCV_INVALID_DATA);
|
||||
CASE(MACH_RCV_PORT_DIED);
|
||||
CASE(MACH_RCV_IN_SET);
|
||||
CASE(MACH_RCV_HEADER_ERROR);
|
||||
CASE(MACH_RCV_BODY_ERROR);
|
||||
CASE(MACH_RCV_INVALID_TYPE);
|
||||
CASE(MACH_RCV_SCATTER_SMALL);
|
||||
CASE(MACH_RCV_INVALID_TRAILER);
|
||||
CASE(MACH_RCV_IN_PROGRESS_TIMED);
|
||||
|
||||
case 0: return @"no error";
|
||||
}
|
||||
#else
|
||||
if (0 == inCode) return @"no error";
|
||||
#endif
|
||||
|
||||
return [NSString stringWithFormat:@"0x%.8X", (unsigned)inCode];
|
||||
}
|
||||
|
||||
|
||||
NSString *FourCharCodeToNSString(FourCharCode inCode)
|
||||
{
|
||||
NSString *result;
|
||||
|
||||
result = (NSString *)UTCreateStringForOSType(inCode);
|
||||
return [result autorelease];
|
||||
}
|
||||
|
||||
|
||||
#ifndef NDEBUG
|
||||
static NSString *GetGenericOSStatusString(OSStatus inCode)
|
||||
{
|
||||
switch (inCode)
|
||||
{
|
||||
case noErr: return @"no error";
|
||||
|
||||
CASE(paramErr);
|
||||
CASE(memFullErr);
|
||||
CASE(unimpErr);
|
||||
CASE(userCanceledErr);
|
||||
CASE(dskFulErr);
|
||||
CASE(fnfErr);
|
||||
CASE(errFSBadFSRef);
|
||||
CASE(gestaltUnknownErr);
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
#endif
|
|
@ -0,0 +1,43 @@
|
|||
/*
|
||||
|
||||
OOProgressBar.h
|
||||
|
||||
Simple custom progress indicator.
|
||||
|
||||
|
||||
Copyright (C) 2008 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
|
||||
@interface OOProgressBar: NSView
|
||||
{
|
||||
@private
|
||||
double _value;
|
||||
}
|
||||
|
||||
// Meaningful values range from 0 to 1. Negative values hide the view. Default is -1.
|
||||
- (double) doubleValue;
|
||||
- (void) setDoubleValue:(double)value;
|
||||
|
||||
@end
|
|
@ -0,0 +1,73 @@
|
|||
/*
|
||||
|
||||
OOProgressBar.m
|
||||
|
||||
|
||||
Copyright (C) 2008 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOProgressBar.h"
|
||||
|
||||
|
||||
@implementation OOProgressBar
|
||||
|
||||
- (id) initWithFrame:(NSRect)frame
|
||||
{
|
||||
if ((self = [super initWithFrame:frame]))
|
||||
{
|
||||
_value = -1.0f;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (void)drawRect:(NSRect)rect
|
||||
{
|
||||
if (_value >= 0.0)
|
||||
{
|
||||
[NSGraphicsContext saveGraphicsState];
|
||||
[[NSColor yellowColor] set];
|
||||
|
||||
rect = NSInsetRect(rect, 0.5f, 0.5f);
|
||||
[NSBezierPath strokeRect:rect];
|
||||
|
||||
rect = NSInsetRect(rect, 1.5f, 1.5f);
|
||||
rect.size.width *= fmin(_value, 1.0);
|
||||
[NSBezierPath fillRect:rect];
|
||||
|
||||
[NSGraphicsContext restoreGraphicsState];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (double) doubleValue
|
||||
{
|
||||
return _value;
|
||||
}
|
||||
|
||||
|
||||
- (void) setDoubleValue:(double)value
|
||||
{
|
||||
_value = value;
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,44 @@
|
|||
/*
|
||||
|
||||
OoliteApp.h
|
||||
|
||||
This is a subclass of NSApplication for Oolite.
|
||||
|
||||
It gets around problems with the system intercepting certain events (NSKeyDown
|
||||
and NSKeyUp) before MyOpenGLView gets to see them, it does this by sending
|
||||
those events to MyOpenGLView regardless of any other processing NSApplication
|
||||
will do with them.
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOCocoa.h"
|
||||
|
||||
@class GameController;
|
||||
|
||||
|
||||
@interface OoliteApp: NSApplication
|
||||
{
|
||||
IBOutlet NSWindow *_gameWindow;
|
||||
IBOutlet GameController *_gameController;
|
||||
}
|
||||
|
||||
|
||||
@end
|
|
@ -0,0 +1,58 @@
|
|||
/*
|
||||
|
||||
OoliteApp.m
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
*/
|
||||
|
||||
#import "OoliteApp.h"
|
||||
#import "GameController.h"
|
||||
#import "MyOpenGLView.h"
|
||||
|
||||
|
||||
@implementation OoliteApp
|
||||
|
||||
- (void)sendEvent:(NSEvent *)theEvent
|
||||
{
|
||||
NSEventType etype = [theEvent type];
|
||||
MyOpenGLView* gameView = [_gameController gameView];
|
||||
|
||||
if ([NSApp keyWindow] == _gameWindow)
|
||||
{
|
||||
// Ensure key events are handled at least once when game window is key
|
||||
switch (etype)
|
||||
{
|
||||
case NSKeyDown:
|
||||
[gameView keyDown:theEvent];
|
||||
break;
|
||||
|
||||
case NSKeyUp:
|
||||
[gameView keyUp:theEvent];
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
[super sendEvent:theEvent]; // perform the default event behaviour
|
||||
}
|
||||
|
||||
|
||||
@end
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
IBClasses = (
|
||||
{CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; },
|
||||
{
|
||||
CLASS = OOCASoundMixer;
|
||||
LANGUAGE = ObjC;
|
||||
OUTLETS = {
|
||||
checkBoxes = NSMatrix;
|
||||
currentField = NSTextField;
|
||||
loadBar = NSProgressIndicator;
|
||||
loadField = NSTextField;
|
||||
maxField = NSTextField;
|
||||
};
|
||||
SUPERCLASS = NSObject;
|
||||
}
|
||||
);
|
||||
IBVersion = 1;
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>IBDocumentLocation</key>
|
||||
<string>677 140 356 240 0 0 1440 878 </string>
|
||||
<key>IBFramework Version</key>
|
||||
<string>443.0</string>
|
||||
<key>IBLockedObjects</key>
|
||||
<array>
|
||||
<integer>46</integer>
|
||||
</array>
|
||||
<key>IBOpenObjects</key>
|
||||
<array>
|
||||
<integer>46</integer>
|
||||
</array>
|
||||
<key>IBSystem Version</key>
|
||||
<string>8F46</string>
|
||||
</dict>
|
||||
</plist>
|
Binary file not shown.
|
@ -0,0 +1,87 @@
|
|||
//
|
||||
// VirtualRingBuffer.h
|
||||
// PlayBufferedSoundFile
|
||||
//
|
||||
/*
|
||||
Copyright (c) 2002, Kurt Revis. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of Snoize nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
//
|
||||
// VirtualRingBuffer implements a classic ring buffer (or circular buffer), with a couple of twists.
|
||||
//
|
||||
// * It allows reads and writes to happen in different threads, with no explicit locking,
|
||||
// so readers and writers will never block. This is useful if either thread uses the
|
||||
// time-constraint scheduling policy, since it is bad for such threads to block for
|
||||
// indefinite amounts of time.
|
||||
//
|
||||
// * It uses a virtual memory trick to allow the client to read or write using just one
|
||||
// operation, even if the data involved wraps around the end of the buffer. We allocate
|
||||
// our buffer normally, and then place a VM region immediately after it in the address
|
||||
// space which maps back to the "real" buffer. So reads and writes into both sections
|
||||
// are transparently translated into the same physical memory.
|
||||
// This makes the API much simpler to use, and saves us from doing some math to
|
||||
// calculate the wraparound points.
|
||||
// The tradeoff is that we use twice as much address space for the buffer than we would
|
||||
// otherwise. Address space is not typically constrained for most applications, though,
|
||||
// so this isn't a big problem.
|
||||
// The idea for this trick came from <http://phil.ipal.org/freeware/vrb/> (via sweetcode.org),
|
||||
// although none of that code is used here. (We use the Mach VM API directly.)
|
||||
//
|
||||
|
||||
// Threading note:
|
||||
// It is expected that this object will be shared between exactly two threads; one will
|
||||
// always read and the other will always write. In that situation, the implementation is
|
||||
// thread-safe, and this object will never block or yield.
|
||||
// It will also work in one thread, of course (although I don't know why you'd bother).
|
||||
// However, if you have multiple reader or writer threads, all bets are off!
|
||||
|
||||
#import "OOCocoa.h"
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
|
||||
@interface VirtualRingBuffer : NSObject
|
||||
{
|
||||
void *buffer;
|
||||
void *bufferEnd;
|
||||
OOUInteger bufferLength;
|
||||
// buffer is the start of the ring buffer's address space.
|
||||
// bufferEnd is the end of the "real" buffer (always buffer + bufferLength).
|
||||
// Note that the "virtual" portion of the buffer extends from bufferEnd to bufferEnd+bufferLength.
|
||||
|
||||
void *readPointer;
|
||||
void *writePointer;
|
||||
}
|
||||
|
||||
- (id)initWithLength:(OOUInteger)length;
|
||||
// Note: The specified length will be rounded up to an integral number of VM pages.
|
||||
|
||||
// Empties the buffer. It is NOT safe to do this while anyone is reading from or writing to the buffer.
|
||||
- (void)empty;
|
||||
// Checks if the buffer is empty or not. This is safe in any thread.
|
||||
- (BOOL)isEmpty;
|
||||
|
||||
// Read operations:
|
||||
|
||||
// The reading thread must call this method first.
|
||||
- (OOUInteger)lengthAvailableToReadReturningPointer:(void **)returnedReadPointer;
|
||||
// Iff a value > 0 is returned, the reading thread may go on to read that much data from the returned pointer.
|
||||
// Afterwards, the reading thread must call didReadLength:.
|
||||
- (void)didReadLength:(OOUInteger)length;
|
||||
|
||||
// Write operations:
|
||||
|
||||
// The writing thread must call this method first.
|
||||
- (OOUInteger)lengthAvailableToWriteReturningPointer:(void **)returnedWritePointer;
|
||||
// Iff a value > 0 is returned, the writing thread may then write that much data into the returned pointer.
|
||||
// Afterwards, the writing thread must call didWriteLength:.
|
||||
- (void)didWriteLength:(OOUInteger)length;
|
||||
|
||||
@end
|
|
@ -0,0 +1,308 @@
|
|||
//
|
||||
// VirtualRingBuffer.m
|
||||
// PlayBufferedSoundFile
|
||||
//
|
||||
/*
|
||||
Copyright (c) 2002, Kurt Revis. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of Snoize nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
|
||||
#import "VirtualRingBuffer.h"
|
||||
#import "OOLogging.h"
|
||||
|
||||
#include <mach/mach.h>
|
||||
#include <mach/mach_error.h>
|
||||
|
||||
|
||||
#define kOOLogUnconvertedNSLog @"unclassified.VirtualRingBuffer"
|
||||
|
||||
|
||||
@implementation VirtualRingBuffer
|
||||
|
||||
static void *allocateVirtualBuffer(OOUInteger bufferLength);
|
||||
static void deallocateVirtualBuffer(void *buffer, OOUInteger bufferLength);
|
||||
|
||||
|
||||
- (id)initWithLength:(OOUInteger)length
|
||||
{
|
||||
if (![super init])
|
||||
return nil;
|
||||
|
||||
// We need to allocate entire VM pages, so round the specified length up to the next page if necessary.
|
||||
bufferLength = round_page(length);
|
||||
|
||||
buffer = allocateVirtualBuffer(bufferLength);
|
||||
if (buffer) {
|
||||
bufferEnd = buffer + bufferLength;
|
||||
} else {
|
||||
[self release];
|
||||
return nil;
|
||||
}
|
||||
|
||||
readPointer = NULL;
|
||||
writePointer = NULL;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
if (buffer)
|
||||
deallocateVirtualBuffer(buffer, bufferLength);
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (void)empty
|
||||
{
|
||||
// Assumption:
|
||||
// No one is reading or writing from the buffer, in any thread, when this method is called.
|
||||
|
||||
readPointer = NULL;
|
||||
writePointer = NULL;
|
||||
}
|
||||
|
||||
- (BOOL)isEmpty
|
||||
{
|
||||
return (readPointer != NULL && writePointer != NULL);
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// Theory of operation:
|
||||
//
|
||||
// This class keeps a pointer to the next byte to be read (readPointer) and a pointer to the next byte to be written (writePointer).
|
||||
// readPointer is only advanced in the reading thread (except for one case: when the buffer first has data written to it).
|
||||
// writePointer is only advanced in the writing thread.
|
||||
//
|
||||
// Since loading and storing word length data is atomic, each pointer can safely be modified in one thread while the other thread
|
||||
// uses it, IF each thread is careful to make a local copy of the "opposite" pointer when necessary.
|
||||
//
|
||||
|
||||
//
|
||||
// Read operations
|
||||
//
|
||||
|
||||
- (OOUInteger)lengthAvailableToReadReturningPointer:(void **)returnedReadPointer
|
||||
{
|
||||
// Assumptions:
|
||||
// returnedReadPointer != NULL
|
||||
|
||||
OOUInteger length;
|
||||
// Read this pointer exactly once, so we're safe in case it is changed in another thread
|
||||
void *localWritePointer = writePointer;
|
||||
|
||||
// Depending on out-of-order execution and memory storage, either one of these may be NULL when the buffer is empty. So we must check both.
|
||||
if (!readPointer || !localWritePointer) {
|
||||
// The buffer is empty
|
||||
length = 0;
|
||||
} else if (localWritePointer > readPointer) {
|
||||
// Write is ahead of read in the buffer
|
||||
length = localWritePointer - readPointer;
|
||||
} else {
|
||||
// Write has wrapped around past read, OR write == read (the buffer is full)
|
||||
length = bufferLength - (readPointer - localWritePointer);
|
||||
}
|
||||
|
||||
*returnedReadPointer = readPointer;
|
||||
return length;
|
||||
}
|
||||
|
||||
- (void)didReadLength:(OOUInteger)length
|
||||
{
|
||||
// Assumptions:
|
||||
// [self lengthAvailableToReadReturningPointer:] currently returns a value >= length
|
||||
// length > 0
|
||||
|
||||
void *newReadPointer;
|
||||
|
||||
newReadPointer = readPointer + length;
|
||||
if (newReadPointer >= bufferEnd)
|
||||
newReadPointer -= bufferLength;
|
||||
|
||||
if (newReadPointer == writePointer) {
|
||||
// We just read the last data out of the buffer, so it is now empty.
|
||||
newReadPointer = NULL;
|
||||
}
|
||||
|
||||
// Store the new read pointer. This is the only place this happens in the read thread.
|
||||
readPointer = newReadPointer;
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// Write operations
|
||||
//
|
||||
|
||||
- (OOUInteger)lengthAvailableToWriteReturningPointer:(void **)returnedWritePointer
|
||||
{
|
||||
// Assumptions:
|
||||
// returnedWritePointer != NULL
|
||||
|
||||
OOUInteger length;
|
||||
// Read this pointer exactly once, so we're safe in case it is changed in another thread
|
||||
void *localReadPointer = readPointer;
|
||||
|
||||
// Either one of these may be NULL when the buffer is empty. So we must check both.
|
||||
if (!localReadPointer || !writePointer) {
|
||||
// The buffer is empty. Set it up to be written into.
|
||||
// This is one of the two places the write pointer can change; both are in the write thread.
|
||||
writePointer = buffer;
|
||||
length = bufferLength;
|
||||
} else if (writePointer <= localReadPointer) {
|
||||
// Write is before read in the buffer, OR write == read (meaning that the buffer is full).
|
||||
length = localReadPointer - writePointer;
|
||||
} else {
|
||||
// Write is behind read in the buffer. The available space wraps around.
|
||||
length = (bufferEnd - writePointer) + (localReadPointer - buffer);
|
||||
}
|
||||
|
||||
*returnedWritePointer = writePointer;
|
||||
return length;
|
||||
}
|
||||
|
||||
- (void)didWriteLength:(OOUInteger)length
|
||||
{
|
||||
// Assumptions:
|
||||
// [self lengthAvailableToWriteReturningPointer:] currently returns a value >= length
|
||||
// length > 0
|
||||
|
||||
void *oldWritePointer = writePointer;
|
||||
void *newWritePointer;
|
||||
|
||||
// Advance the write pointer, wrapping around if necessary.
|
||||
newWritePointer = writePointer + length;
|
||||
if (newWritePointer >= bufferEnd)
|
||||
newWritePointer -= bufferLength;
|
||||
|
||||
// This is one of the two places the write pointer can change; both are in the write thread.
|
||||
writePointer = newWritePointer;
|
||||
|
||||
// Also, if the read pointer is NULL, then we just wrote into a previously empty buffer, so set the read pointer.
|
||||
// This is the only place the read pointer is changed in the write thread.
|
||||
// The read thread should never change the read pointer when it is NULL, so this is safe.
|
||||
if (!readPointer)
|
||||
readPointer = oldWritePointer;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
void *allocateVirtualBuffer(OOUInteger bufferLength)
|
||||
{
|
||||
kern_return_t error;
|
||||
vm_address_t originalAddress = 0;
|
||||
vm_address_t realAddress = 0;
|
||||
mach_port_t memoryEntry;
|
||||
vm_size_t memoryEntryLength;
|
||||
vm_address_t virtualAddress = 0;
|
||||
|
||||
// We want to find where we can get 2 * bufferLength bytes of contiguous address space.
|
||||
// So let's just allocate that space, remember its address, and deallocate it.
|
||||
// (This doesn't actually have to touch all of that memory so it's not terribly expensive.)
|
||||
error = vm_allocate(mach_task_self(), &originalAddress, 2 * bufferLength, TRUE);
|
||||
if (error) {
|
||||
#if DEBUG
|
||||
mach_error("vm_allocate initial chunk", error);
|
||||
#endif
|
||||
return NULL;
|
||||
}
|
||||
|
||||
error = vm_deallocate(mach_task_self(), originalAddress, 2 * bufferLength);
|
||||
if (error) {
|
||||
#if DEBUG
|
||||
mach_error("vm_deallocate initial chunk", error);
|
||||
#endif
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Then allocate a "real" block of memory at the same address, but with the normal bufferLength.
|
||||
realAddress = originalAddress;
|
||||
error = vm_allocate(mach_task_self(), &realAddress, bufferLength, FALSE);
|
||||
if (error) {
|
||||
#if DEBUG
|
||||
mach_error("vm_allocate real chunk", error);
|
||||
#endif
|
||||
return NULL;
|
||||
}
|
||||
if (realAddress != originalAddress) {
|
||||
#if DEBUG
|
||||
NSLog(@"allocateVirtualBuffer: vm_allocate 2nd time didn't return same address (%p vs %p)", originalAddress, realAddress);
|
||||
#endif
|
||||
goto errorReturn;
|
||||
}
|
||||
|
||||
// Then make a memory entry for the area we just allocated.
|
||||
memoryEntryLength = bufferLength;
|
||||
error = mach_make_memory_entry(mach_task_self(), &memoryEntryLength, realAddress, VM_PROT_READ | VM_PROT_WRITE, &memoryEntry, 0);
|
||||
if (error) {
|
||||
#if DEBUG
|
||||
mach_error("mach_make_memory_entry", error);
|
||||
#endif
|
||||
goto errorReturn;
|
||||
}
|
||||
if (!memoryEntry) {
|
||||
#if DEBUG
|
||||
NSLog(@"mach_make_memory_entry: returned memoryEntry of NULL");
|
||||
#endif
|
||||
goto errorReturn;
|
||||
}
|
||||
if (memoryEntryLength != bufferLength) {
|
||||
#if DEBUG
|
||||
NSLog(@"mach_make_memory_entry: size changed (from %0x to %0x)", bufferLength, memoryEntryLength);
|
||||
#endif
|
||||
goto errorReturn;
|
||||
}
|
||||
|
||||
// And map the area immediately after the first block, with length bufferLength, to that memory entry.
|
||||
virtualAddress = realAddress + bufferLength;
|
||||
error = vm_map(mach_task_self(), &virtualAddress, bufferLength, 0, FALSE, memoryEntry, 0, FALSE, VM_PROT_READ | VM_PROT_WRITE, VM_PROT_READ | VM_PROT_WRITE, VM_INHERIT_DEFAULT);
|
||||
if (error) {
|
||||
#if DEBUG
|
||||
mach_error("vm_map", error);
|
||||
#endif
|
||||
// TODO Retry from the beginning, instead of failing completely. There is a tiny (but > 0) probability that someone
|
||||
// will allocate this space out from under us.
|
||||
virtualAddress = 0;
|
||||
goto errorReturn;
|
||||
}
|
||||
if (virtualAddress != realAddress + bufferLength) {
|
||||
#if DEBUG
|
||||
NSLog(@"vm_map: didn't return correct address (%p vs %p)", realAddress + bufferLength, virtualAddress);
|
||||
#endif
|
||||
goto errorReturn;
|
||||
}
|
||||
|
||||
// Success!
|
||||
return (void *)realAddress;
|
||||
|
||||
errorReturn:
|
||||
if (realAddress)
|
||||
vm_deallocate(mach_task_self(), realAddress, bufferLength);
|
||||
if (virtualAddress)
|
||||
vm_deallocate(mach_task_self(), virtualAddress, bufferLength);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void deallocateVirtualBuffer(void *buffer, OOUInteger bufferLength)
|
||||
{
|
||||
kern_return_t error;
|
||||
|
||||
// We can conveniently deallocate both the vm_allocated memory and
|
||||
// the vm_mapped region at the same time.
|
||||
error = vm_deallocate(mach_task_self(), (vm_address_t)buffer, bufferLength * 2);
|
||||
if (error) {
|
||||
#if DEBUG
|
||||
mach_error("vm_deallocate in dealloc", error);
|
||||
#endif
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
# Symbols used by Debug.OXP
|
||||
.objc_class_name_PlayerEntity
|
||||
.objc_class_name_OOCacheManager
|
||||
.objc_class_name_OOGraphicsResetManager
|
||||
.objc_class_name_OOTexture
|
||||
.objc_class_name_ResourceManager
|
||||
.objc_class_name_OOJavaScriptEngine
|
||||
.objc_class_name_OOColor
|
||||
.objc_class_name_OOWeakRefObject
|
||||
.objc_class_name_OOScript
|
||||
.objc_class_name_OOJSScript
|
||||
.objc_class_name_OODebugMonitor
|
||||
.objc_class_name_ShipEntity
|
||||
.objc_class_name_OOEntityWithDrawable
|
||||
|
||||
_OBJC_CLASS_$_ShipEntity
|
||||
_OBJC_CLASS_$_Entity
|
||||
_OBJC_IVAR_$_PlayerEntity.player_name
|
||||
_OBJC_CLASS_$_AI
|
||||
|
||||
_OOLogWithFunctionFileAndLine
|
||||
_OOLogInsertMarker
|
||||
_OOLogSetDisplayMessagesInClass
|
||||
_OOLogSetShowFileAndLine
|
||||
_OOLogSetShowFunction
|
||||
_OOLogSetShowMessageClass
|
||||
_OOLogShowFileAndLine
|
||||
_OOLogShowFunction
|
||||
_OOLogShowMessageClass
|
||||
_OOLogWillDisplayMessagesInClass
|
||||
_OOLogHandlerGetLogPath
|
||||
_OOLogIndent
|
||||
_OOLogOutdent
|
||||
_gDebugFlags
|
||||
_gSharedUniverse
|
||||
_JSBasicPrivateObjectConverter
|
||||
_JSObjectToObject
|
||||
_JSRegisterObjectConverter
|
||||
_JS_ConvertStub
|
||||
_JS_EnumerateStub
|
||||
_JS_GetPrivate
|
||||
_JS_SetPrivate
|
||||
_JS_InitClass
|
||||
_JS_NewObject
|
||||
_JS_PropertyStub
|
||||
_JS_ResolveStub
|
||||
_OOReportJSBadPropertySelector
|
||||
_OOReportJSError
|
||||
_JS_InternString
|
||||
_JS_AddNamedRoot
|
||||
_JS_RemoveRoot
|
||||
_JSValueToObject
|
||||
_JS_ValueToNumber
|
||||
_JS_SetProperty
|
||||
_OOReportJSWarning
|
||||
_OOBooleanFromObject
|
||||
_ScanClassToString
|
||||
_EntityStatusToString
|
||||
_QuaternionDescription
|
||||
_VectorDescription
|
||||
_BehaviourToString
|
||||
_kOOLogUnconvertedNSLog
|
||||
|
||||
# Debug value formatter support
|
||||
_JSValueToStrDbg
|
||||
_JSObjectToStrDbg
|
||||
_JSValueTypeDbg
|
|
@ -0,0 +1,82 @@
|
|||
# Symbols used by Debug.OXP
|
||||
.objc_class_name_PlayerEntity
|
||||
.objc_class_name_OOCacheManager
|
||||
.objc_class_name_OOGraphicsResetManager
|
||||
.objc_class_name_OOTexture
|
||||
.objc_class_name_ResourceManager
|
||||
.objc_class_name_OOJavaScriptEngine
|
||||
.objc_class_name_OOColor
|
||||
.objc_class_name_OOWeakRefObject
|
||||
.objc_class_name_OOScript
|
||||
.objc_class_name_OOJSScript
|
||||
.objc_class_name_OODebugMonitor
|
||||
.objc_class_name_ShipEntity
|
||||
.objc_class_name_OOEntityWithDrawable
|
||||
_OOLogWithFunctionFileAndLine
|
||||
_OOLogInsertMarker
|
||||
_OOLogSetDisplayMessagesInClass
|
||||
_OOLogSetShowFileAndLine
|
||||
_OOLogSetShowFunction
|
||||
_OOLogSetShowMessageClass
|
||||
_OOLogShowFileAndLine
|
||||
_OOLogShowFunction
|
||||
_OOLogShowMessageClass
|
||||
_OOLogWillDisplayMessagesInClass
|
||||
_OOLogHandlerGetLogPath
|
||||
_OOLogIndent
|
||||
_OOLogOutdent
|
||||
_gDebugFlags
|
||||
_gSharedUniverse
|
||||
_JSBasicPrivateObjectConverter
|
||||
_JSObjectToObject
|
||||
_JSRegisterObjectConverter
|
||||
_JS_ConvertStub
|
||||
_JS_EnumerateStub
|
||||
_JS_GetPrivate
|
||||
_JS_SetPrivate
|
||||
_JS_InitClass
|
||||
_JS_NewObject
|
||||
_JS_PropertyStub
|
||||
_JS_ResolveStub
|
||||
_OOReportJSBadPropertySelector
|
||||
_OOReportJSError
|
||||
_JS_InternString
|
||||
_JS_AddNamedRoot
|
||||
_JS_RemoveRoot
|
||||
_JSValueToObject
|
||||
_JS_ValueToNumber
|
||||
_JS_SetProperty
|
||||
_OOReportJSWarning
|
||||
_OOBooleanFromObject
|
||||
_ScanClassToString
|
||||
_EntityStatusToString
|
||||
_QuaternionDescription
|
||||
_VectorDescription
|
||||
_BehaviourToString
|
||||
_kOOLogUnconvertedNSLog
|
||||
|
||||
# Symbols exported for warning supression. Without these, we get lines like
|
||||
# /usr/bin/ld: warning symbol: _NXArgc referenced dynamically and must be exported
|
||||
_NXArgc
|
||||
_NXArgv
|
||||
___progname
|
||||
_environ
|
||||
_catch_exception_raise
|
||||
_catch_exception_raise_state
|
||||
_catch_exception_raise_state_identity
|
||||
_clock_alarm_reply
|
||||
_do_mach_notify_dead_name
|
||||
_do_mach_notify_no_senders
|
||||
_do_mach_notify_port_deleted
|
||||
_do_mach_notify_send_once
|
||||
_receive_samples
|
||||
__mh_execute_header
|
||||
_do_seqnos_mach_notify_dead_name
|
||||
_do_seqnos_mach_notify_no_senders
|
||||
_do_seqnos_mach_notify_port_deleted
|
||||
_do_seqnos_mach_notify_send_once
|
||||
|
||||
# Debug value formatter support
|
||||
_JSValueToStrDbg
|
||||
_JSObjectToStrDbg
|
||||
_JSValueTypeDbg
|
|
@ -0,0 +1,15 @@
|
|||
#import <Cocoa/Cocoa.h>
|
||||
#import "OOLoggingExtended.h"
|
||||
|
||||
|
||||
#ifndef NDEBUG
|
||||
uint32_t gDebugFlags = 0;
|
||||
#endif
|
||||
|
||||
|
||||
int main(int argc, const char *argv[])
|
||||
{
|
||||
OOLoggingInit();
|
||||
return NSApplicationMain(argc, argv);
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
#include "oolite-version.xcconfig"
|
||||
|
||||
|
||||
ALLOW_PROCEDURAL_PLANETS = 0
|
||||
DOCKING_CLEARANCE_ENABLED = 1
|
||||
TARGET_INCOMING_MISSILES = 1
|
||||
WORMHOLE_SCANNER = 1
|
||||
|
||||
|
||||
OOLITE_OPTION_MACROS = ALLOW_PROCEDURAL_PLANETS=$(ALLOW_PROCEDURAL_PLANETS) DOCKING_CLEARANCE_ENABLED=$(DOCKING_CLEARANCE_ENABLED) TARGET_INCOMING_MISSILES=$(TARGET_INCOMING_MISSILES) WORMHOLE_SCANNER=$(WORMHOLE_SCANNER)
|
|
@ -0,0 +1 @@
|
|||
OOLITE_VERSION = 1.73
|
|
@ -0,0 +1,115 @@
|
|||
/*
|
||||
|
||||
AI.h
|
||||
|
||||
Core NPC behaviour/artificial intelligence class.
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "OOWeakReference.h"
|
||||
#import "OOTypes.h"
|
||||
|
||||
#define AI_THINK_INTERVAL 0.125
|
||||
|
||||
|
||||
@class ShipEntity;
|
||||
#ifdef OO_BRAIN_AI
|
||||
@class OOInstinct;
|
||||
#endif
|
||||
|
||||
|
||||
@interface AI : OOWeakRefObject
|
||||
{
|
||||
id _owner; // OOWeakReference to the ShipEntity this is the AI for
|
||||
NSString *ownerDesc; // describes the object this is the AI for
|
||||
|
||||
NSDictionary *stateMachine;
|
||||
NSString *stateMachineName;
|
||||
NSString *currentState;
|
||||
NSMutableSet *pendingMessages;
|
||||
|
||||
NSMutableArray *aiStack;
|
||||
|
||||
#ifdef OO_BRAIN_AI
|
||||
OOInstinct *rulingInstinct;
|
||||
#endif
|
||||
|
||||
OOTimeAbsolute nextThinkTime;
|
||||
OOTimeDelta thinkTimeInterval;
|
||||
|
||||
}
|
||||
|
||||
+ (AI *) currentlyRunningAI;
|
||||
+ (NSString *) currentlyRunningAIDescription;
|
||||
|
||||
- (NSString *) name;
|
||||
- (NSString *) state;
|
||||
|
||||
- (void) setStateMachine:(NSString *)smName;
|
||||
- (void) setState:(NSString *)stateName;
|
||||
|
||||
- (void) setStateMachine:(NSString *)smName afterDelay:(NSTimeInterval)delay;
|
||||
- (void) setState:(NSString *)stateName afterDelay:(NSTimeInterval)delay;
|
||||
|
||||
- (id) initWithStateMachine:(NSString *) smName andState:(NSString *) stateName;
|
||||
|
||||
#ifdef OO_BRAIN_AI
|
||||
- (OOInstinct *) rulingInstinct;
|
||||
- (void) setRulingInstinct:(OOInstinct*) instinct;
|
||||
#endif
|
||||
|
||||
- (ShipEntity *)owner;
|
||||
- (void) setOwner:(ShipEntity *)ship;
|
||||
|
||||
- (void) preserveCurrentStateMachine;
|
||||
|
||||
- (void) restorePreviousStateMachine;
|
||||
|
||||
- (BOOL) hasSuspendedStateMachines;
|
||||
- (void) exitStateMachineWithMessage:(NSString *)message;
|
||||
|
||||
- (unsigned) stackDepth;
|
||||
|
||||
- (void) reactToMessage:(NSString *) message;
|
||||
|
||||
- (void) takeAction:(NSString *) action;
|
||||
|
||||
- (void) think;
|
||||
|
||||
- (void) message:(NSString *) ms;
|
||||
- (void) dropMessage:(NSString *) ms;
|
||||
- (NSSet *) pendingMessages;
|
||||
- (void) debugDumpPendingMessages;
|
||||
|
||||
- (void) setNextThinkTime:(OOTimeAbsolute) ntt;
|
||||
- (OOTimeAbsolute) nextThinkTime;
|
||||
|
||||
- (void) setThinkTimeInterval:(OOTimeDelta) tti;
|
||||
- (OOTimeDelta) thinkTimeInterval;
|
||||
|
||||
- (void) clearStack;
|
||||
|
||||
- (void) clearAllData;
|
||||
|
||||
- (void)dumpState;
|
||||
|
||||
@end
|
|
@ -0,0 +1,833 @@
|
|||
/*
|
||||
|
||||
AI.m
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2009 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
*/
|
||||
|
||||
#import "AI.h"
|
||||
#import "ResourceManager.h"
|
||||
#import "OOStringParsing.h"
|
||||
#import "OOWeakReference.h"
|
||||
#import "OOCacheManager.h"
|
||||
#import "OOCollectionExtractors.h"
|
||||
|
||||
#import "ShipEntity.h"
|
||||
|
||||
#ifdef OO_BRAIN_AI
|
||||
#import "OOInstinct.h"
|
||||
#endif
|
||||
|
||||
#define kOOLogUnconvertedNSLog @"unclassified.AI"
|
||||
|
||||
|
||||
typedef struct
|
||||
{
|
||||
AI *ai;
|
||||
SEL selector;
|
||||
id parameter;
|
||||
} OOAIDeferredCallTrampolineInfo;
|
||||
|
||||
|
||||
static AI *sCurrentlyRunningAI = nil;
|
||||
|
||||
|
||||
@interface AI (OOPrivate)
|
||||
|
||||
// Wrapper for performSelector:withObject:afterDelay: to catch/fix bugs.
|
||||
- (void)performDeferredCall:(SEL)selector withObject:(id)object afterDelay:(NSTimeInterval)delay;
|
||||
+ (void)deferredCallTrampolineWithInfo:(NSValue *)info;
|
||||
|
||||
- (void)refreshOwnerDesc;
|
||||
|
||||
// Loading/whitelisting
|
||||
- (NSDictionary *) loadStateMachine:(NSString *)smName;
|
||||
- (NSDictionary *) cleanHandlers:(NSDictionary *)handlers forState:(NSString *)stateKey stateMachine:(NSString *)smName;
|
||||
- (NSArray *) cleanActions:(NSArray *)actions forHandler:(NSString *)handlerKey state:(NSString *)stateKey stateMachine:(NSString *)smName;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation AI
|
||||
|
||||
+ (AI *) currentlyRunningAI
|
||||
{
|
||||
return sCurrentlyRunningAI;
|
||||
}
|
||||
|
||||
|
||||
+ (NSString *) currentlyRunningAIDescription
|
||||
{
|
||||
if (sCurrentlyRunningAI != nil)
|
||||
{
|
||||
return [NSString stringWithFormat:@"%@ in state %@", [sCurrentlyRunningAI name], [sCurrentlyRunningAI state]];
|
||||
}
|
||||
else
|
||||
{
|
||||
return @"<no AI running>";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (id) init
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
aiStack = [[NSMutableArray alloc] init];
|
||||
pendingMessages = [[NSMutableSet alloc] init];
|
||||
|
||||
nextThinkTime = [[NSDate distantFuture] timeIntervalSinceNow]; // don't think for a while
|
||||
thinkTimeInterval = AI_THINK_INTERVAL;
|
||||
|
||||
stateMachineName = [[NSString stringWithString:@"None allocated"] retain]; // no initial brain
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (id) initWithStateMachine:(NSString *) smName andState:(NSString *) stateName
|
||||
{
|
||||
self = [self init];
|
||||
|
||||
if (smName != nil) [self setStateMachine:smName];
|
||||
if (stateName != nil) currentState = [stateName retain];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (void) dealloc
|
||||
{
|
||||
[_owner release];
|
||||
[ownerDesc release];
|
||||
[aiStack release];
|
||||
[stateMachine release];
|
||||
[stateMachineName release];
|
||||
[currentState release];
|
||||
[pendingMessages release];
|
||||
|
||||
if (sCurrentlyRunningAI == self) sCurrentlyRunningAI = nil;
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
- (NSString *) descriptionComponents
|
||||
{
|
||||
return [NSString stringWithFormat:@"\"%@\" in state: \"%@\" for %@", stateMachineName, currentState, ownerDesc];
|
||||
}
|
||||
|
||||
|
||||
#ifdef OO_BRAIN_AI
|
||||
- (OOInstinct *) rulingInstinct
|
||||
{
|
||||
return rulingInstinct;
|
||||
}
|
||||
|
||||
|
||||
- (void) setRulingInstinct:(OOInstinct*) instinct
|
||||
{
|
||||
rulingInstinct = instinct;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
- (ShipEntity *)owner
|
||||
{
|
||||
ShipEntity *owner = [_owner weakRefUnderlyingObject];
|
||||
if (owner == nil)
|
||||
{
|
||||
[_owner release];
|
||||
_owner = nil;
|
||||
}
|
||||
|
||||
return owner;
|
||||
}
|
||||
|
||||
|
||||
- (void) setOwner:(ShipEntity *)ship
|
||||
{
|
||||
[_owner release];
|
||||
_owner = [ship weakRetain];
|
||||
[self refreshOwnerDesc];
|
||||
}
|
||||
|
||||
|
||||
- (void) preserveCurrentStateMachine
|
||||
{
|
||||
if (!stateMachine)
|
||||
return;
|
||||
|
||||
NSMutableDictionary *pickledMachine = [NSMutableDictionary dictionaryWithCapacity:3];
|
||||
|
||||
[pickledMachine setObject:stateMachine forKey:@"stateMachine"];
|
||||
[pickledMachine setObject:currentState forKey:@"currentState"];
|
||||
[pickledMachine setObject:stateMachineName forKey:@"stateMachineName"];
|
||||
[pickledMachine setObject:[[pendingMessages copy] autorelease] forKey:@"pendingMessages"];
|
||||
|
||||
if (aiStack == nil) aiStack = [[NSMutableArray alloc] init];
|
||||
|
||||
if ([aiStack count] > 32)
|
||||
{
|
||||
OOLogERR(@"ai.pushStateMachine.overflow", @"AI stack overflow for %@ stack:\n%@", [_owner shortDescription], aiStack);
|
||||
[NSException raise:@"OoliteException"
|
||||
format:@"AI stack overflow for %@", _owner];
|
||||
}
|
||||
|
||||
#ifndef NDEBUG
|
||||
if ([[self owner] reportAIMessages]) OOLog(@"ai.stack.push", @"Pushing state machine for %@", self);
|
||||
#endif
|
||||
[aiStack insertObject:pickledMachine atIndex:0]; // PUSH
|
||||
}
|
||||
|
||||
|
||||
- (void) restorePreviousStateMachine
|
||||
{
|
||||
if ([aiStack count] == 0) return;
|
||||
|
||||
NSMutableDictionary *pickledMachine = [aiStack objectAtIndex:0];
|
||||
|
||||
#ifndef NDEBUG
|
||||
if ([[self owner] reportAIMessages]) OOLog(@"ai.stack.pop", @"Popping previous state machine for %@", self);
|
||||
#endif
|
||||
|
||||
[stateMachine release];
|
||||
stateMachine = [[pickledMachine objectForKey:@"stateMachine"] retain];
|
||||
|
||||
[currentState release];
|
||||
currentState = [[pickledMachine objectForKey:@"currentState"] retain];
|
||||
|
||||
[stateMachineName release];
|
||||
stateMachineName = [[pickledMachine objectForKey:@"stateMachineName"] retain];
|
||||
|
||||
[pendingMessages release];
|
||||
pendingMessages = [[pickledMachine objectForKey:@"pendingMessages"] mutableCopy]; // restore a MUTABLE set
|
||||
|
||||
[aiStack removeObjectAtIndex:0]; // POP
|
||||
}
|
||||
|
||||
|
||||
- (BOOL) hasSuspendedStateMachines
|
||||
{
|
||||
return [aiStack count] != 0;
|
||||
}
|
||||
|
||||
|
||||
- (void) exitStateMachineWithMessage:(NSString *)message
|
||||
{
|
||||
if ([aiStack count] != 0)
|
||||
{
|
||||
[self restorePreviousStateMachine];
|
||||
if (message == nil) message = @"RESTARTED";
|
||||
[self reactToMessage:message];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void) setStateMachine:(NSString *) smName
|
||||
{
|
||||
NSDictionary *newSM = [self loadStateMachine:smName];
|
||||
|
||||
if (newSM)
|
||||
{
|
||||
[self preserveCurrentStateMachine];
|
||||
[stateMachine release]; // release old state machine
|
||||
stateMachine = [newSM retain];
|
||||
nextThinkTime = 0.0; // think at next tick
|
||||
}
|
||||
|
||||
[currentState release];
|
||||
currentState = @"GLOBAL";
|
||||
/* CRASH in objc_msgSend, apparently on [self reactToMessage:@"ENTER"] (1.69, OS X/x86).
|
||||
Analysis: self corrupted. We're being called by __NSFireDelayedPerform, which doesn't go
|
||||
through -[NSObject performSelector:withObject:], suggesting it's using IMP caching. An
|
||||
invalid self is therefore possible.
|
||||
Attempted fix: new delayed dispatch with trampoline, see -[AI setStateMachine:afterDelay:].
|
||||
-- Ahruman, 20070706
|
||||
*/
|
||||
[self reactToMessage:@"ENTER"];
|
||||
|
||||
// refresh name
|
||||
[self refreshOwnerDesc];
|
||||
|
||||
// refresh stateMachineName
|
||||
[stateMachineName release];
|
||||
stateMachineName = [smName copy];
|
||||
}
|
||||
|
||||
|
||||
- (void) setState:(NSString *) stateName
|
||||
{
|
||||
if ([stateMachine objectForKey:stateName])
|
||||
{
|
||||
/* CRASH in objc_msgSend, apparently on [self reactToMessage:@"EXIT"] (1.69, OS X/x86).
|
||||
Analysis: self corrupted. We're being called by __NSFireDelayedPerform, which doesn't go
|
||||
through -[NSObject performSelector:withObject:], suggesting it's using IMP caching. An
|
||||
invalid self is therefore possible.
|
||||
Attempted fix: new delayed dispatch with trampoline, see -[AI setState:afterDelay:].
|
||||
-- Ahruman, 20070706
|
||||
*/
|
||||
[self reactToMessage:@"EXIT"];
|
||||
[currentState release];
|
||||
currentState = [stateName retain];
|
||||
[self reactToMessage:@"ENTER"];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void) setStateMachine:(NSString *)smName afterDelay:(NSTimeInterval)delay
|
||||
{
|
||||
[self performDeferredCall:@selector(setStateMachine:) withObject:smName afterDelay:delay];
|
||||
}
|
||||
|
||||
|
||||
- (void) setState:(NSString *)stateName afterDelay:(NSTimeInterval)delay
|
||||
{
|
||||
[self performDeferredCall:@selector(setState:) withObject:stateName afterDelay:delay];
|
||||
}
|
||||
|
||||
|
||||
- (NSString *) name
|
||||
{
|
||||
return [[stateMachineName retain] autorelease];
|
||||
}
|
||||
|
||||
|
||||
- (NSString *) state
|
||||
{
|
||||
return [[currentState retain] autorelease];
|
||||
}
|
||||
|
||||
|
||||
- (unsigned) stackDepth
|
||||
{
|
||||
return [aiStack count];
|
||||
}
|
||||
|
||||
|
||||
- (void) reactToMessage:(NSString *)message
|
||||
{
|
||||
unsigned i;
|
||||
NSArray *actions = nil;
|
||||
NSDictionary *messagesForState = nil;
|
||||
ShipEntity *owner = [self owner];
|
||||
static unsigned recursionLimiter = 0;
|
||||
AI *previousRunning = sCurrentlyRunningAI;
|
||||
|
||||
|
||||
/* CRASH in _freedHandler when called via -setState: __NSFireDelayedPerform (1.69, OS X/x86).
|
||||
Analysis: owner invalid.
|
||||
Fix: make owner an OOWeakReference.
|
||||
-- Ahruman, 20070706
|
||||
*/
|
||||
if (message == nil || owner == nil || [owner universalID] == NO_TARGET) return;
|
||||
|
||||
|
||||
/* CRASH when calling reactToMessage: FOO in state FOO causes infinite
|
||||
recursion.
|
||||
FIX: recursion limiter. Alternative is to explicitly catch this case
|
||||
in takeAction:, but that could potentially miss indirect recursion via
|
||||
scripts.
|
||||
*/
|
||||
if (recursionLimiter > 32)
|
||||
{
|
||||
OOLogERR(@"ai.error.recursion", @"AI reactToMessage: recursion in AI %@, state %@, aborting. It is not valid to call reactToMessage: FOO in state FOO.", stateMachineName, currentState);
|
||||
return;
|
||||
}
|
||||
|
||||
messagesForState = [stateMachine objectForKey:currentState];
|
||||
if (messagesForState == nil) return;
|
||||
|
||||
#ifndef NDEBUG
|
||||
if (currentState != nil && ![message isEqual:@"UPDATE"] && [owner reportAIMessages])
|
||||
{
|
||||
OOLog(@"ai.message.receive", @"AI %@ for %@ in state '%@' receives message '%@'", stateMachineName, ownerDesc, currentState, message);
|
||||
}
|
||||
#endif
|
||||
|
||||
actions = [[[messagesForState objectForKey:message] copy] autorelease];
|
||||
|
||||
#ifdef OO_BRAIN_AI
|
||||
if (rulingInstinct != nil) [rulingInstinct freezeShipVars]; // preserve the pre-thinking state
|
||||
#endif
|
||||
|
||||
sCurrentlyRunningAI = self;
|
||||
if ([actions count] > 0)
|
||||
{
|
||||
NS_DURING
|
||||
++recursionLimiter;
|
||||
for (i = 0; i < [actions count]; i++)
|
||||
{
|
||||
[self takeAction:[actions objectAtIndex:i]];
|
||||
}
|
||||
--recursionLimiter;
|
||||
NS_HANDLER
|
||||
--recursionLimiter;
|
||||
NS_ENDHANDLER
|
||||
}
|
||||
else
|
||||
{
|
||||
if (currentState != nil)
|
||||
{
|
||||
if ([owner respondsToSelector:@selector(interpretAIMessage:)])
|
||||
{
|
||||
[owner performSelector:@selector(interpretAIMessage:) withObject:message];
|
||||
}
|
||||
}
|
||||
}
|
||||
sCurrentlyRunningAI = previousRunning;
|
||||
|
||||
#ifdef OO_BRAIN_AI
|
||||
if (rulingInstinct != nil)
|
||||
{
|
||||
[rulingInstinct getShipVars]; // record the post-thinking state
|
||||
[rulingInstinct unfreezeShipVars]; // restore the pre-thinking state (AI is now abstract thought = instincts motivate)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
- (void) takeAction:(NSString *) action
|
||||
{
|
||||
NSArray *tokens = ScanTokensFromString(action);
|
||||
NSString *dataString = nil;
|
||||
NSString *selectorStr;
|
||||
SEL selector;
|
||||
ShipEntity *owner = [self owner];
|
||||
|
||||
#ifndef NDEBUG
|
||||
BOOL report = [owner reportAIMessages];
|
||||
if (report)
|
||||
{
|
||||
OOLog(@"ai.takeAction", @"%@ to take action %@", ownerDesc, action);
|
||||
OOLogIndent();
|
||||
}
|
||||
#endif
|
||||
|
||||
if ([tokens count] != 0)
|
||||
{
|
||||
selectorStr = [tokens objectAtIndex:0];
|
||||
|
||||
if (owner != nil)
|
||||
{
|
||||
if ([tokens count] > 1)
|
||||
{
|
||||
dataString = [[tokens subarrayWithRange:NSMakeRange(1, [tokens count] - 1)] componentsJoinedByString:@" "];
|
||||
}
|
||||
|
||||
selector = NSSelectorFromString(selectorStr);
|
||||
if ([owner respondsToSelector:selector])
|
||||
{
|
||||
if (dataString) [owner performSelector:selector withObject:dataString];
|
||||
else [owner performSelector:selector];
|
||||
}
|
||||
else
|
||||
{
|
||||
if ([selectorStr isEqual:@"setStateTo:"]) [self setState:dataString];
|
||||
else if ([selectorStr isEqual:@"debugMessage:"])
|
||||
{
|
||||
OOLog(@"ai.takeAction.debugMessage", @"DEBUG: AI MESSAGE from %@: %@", ownerDesc, dataString);
|
||||
}
|
||||
else
|
||||
{
|
||||
OOLogERR(@"ai.takeAction.badSelector", @"in AI %@ in state %@: %@ does not respond to %@", stateMachineName, currentState, ownerDesc, selectorStr);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
OOLog(@"ai.takeAction.orphaned", @"***** AI %@, trying to perform %@, is orphaned (no owner)", stateMachineName, selectorStr);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
if (report) OOLog(@"ai.takeAction.noAction", @"DEBUG: - no action '%@'", action);
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifndef NDEBUG
|
||||
if (report)
|
||||
{
|
||||
OOLogOutdent();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
- (void) think
|
||||
{
|
||||
NSArray *ms_list = nil;
|
||||
unsigned i;
|
||||
|
||||
if ([[self owner] universalID] == NO_TARGET || stateMachine == nil) return; // don't think until launched
|
||||
|
||||
[self reactToMessage:@"UPDATE"];
|
||||
|
||||
if ([pendingMessages count] > 0) ms_list = [pendingMessages allObjects];
|
||||
[pendingMessages removeAllObjects];
|
||||
|
||||
if (ms_list != nil)
|
||||
{
|
||||
for (i = 0; i < [ms_list count]; i++)
|
||||
{
|
||||
[self reactToMessage:[ms_list objectAtIndex:i]];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void) message:(NSString *) ms
|
||||
{
|
||||
if ([[self owner] universalID] == NO_TARGET) return; // don't think until launched
|
||||
|
||||
if ([pendingMessages count] > 32)
|
||||
{
|
||||
OOLogERR(@"ai.message.failed.overflow", @"AI pending messages overflow for '%@'; pending messages:\n%@", ownerDesc, pendingMessages);
|
||||
[NSException raise:@"OoliteException"
|
||||
format:@"AI pendingMessages overflow for %@", ownerDesc];
|
||||
}
|
||||
|
||||
[pendingMessages addObject:ms];
|
||||
}
|
||||
|
||||
|
||||
- (void) dropMessage:(NSString *) ms
|
||||
{
|
||||
[pendingMessages removeObject:ms];
|
||||
}
|
||||
|
||||
|
||||
- (NSSet *) pendingMessages
|
||||
{
|
||||
return [[pendingMessages copy] autorelease];
|
||||
}
|
||||
|
||||
|
||||
- (void) debugDumpPendingMessages
|
||||
{
|
||||
NSArray *sortedMessages = nil;
|
||||
NSString *displayMessages = nil;
|
||||
|
||||
if ([pendingMessages count] > 0)
|
||||
{
|
||||
sortedMessages = [[pendingMessages allObjects] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
|
||||
displayMessages = [sortedMessages componentsJoinedByString:@", "];
|
||||
}
|
||||
else
|
||||
{
|
||||
displayMessages = @"none";
|
||||
}
|
||||
|
||||
OOLog(@"ai.debug.pendingMessages", @"Pending messages for AI %@: %@", [self descriptionComponents], displayMessages);
|
||||
}
|
||||
|
||||
|
||||
- (void) setNextThinkTime:(OOTimeAbsolute) ntt
|
||||
{
|
||||
nextThinkTime = ntt;
|
||||
}
|
||||
|
||||
|
||||
- (OOTimeAbsolute) nextThinkTime
|
||||
{
|
||||
if (!stateMachine)
|
||||
return [[NSDate distantFuture] timeIntervalSinceNow];
|
||||
|
||||
return nextThinkTime;
|
||||
}
|
||||
|
||||
|
||||
- (void) setThinkTimeInterval:(OOTimeDelta) tti
|
||||
{
|
||||
thinkTimeInterval = tti;
|
||||
}
|
||||
|
||||
|
||||
- (OOTimeDelta) thinkTimeInterval
|
||||
{
|
||||
return thinkTimeInterval;
|
||||
}
|
||||
|
||||
|
||||
- (void) clearStack
|
||||
{
|
||||
[aiStack removeAllObjects];
|
||||
}
|
||||
|
||||
|
||||
- (void) clearAllData
|
||||
{
|
||||
[aiStack removeAllObjects];
|
||||
[pendingMessages removeAllObjects];
|
||||
|
||||
nextThinkTime += 36000.0; // should dealloc in under ten hours!
|
||||
thinkTimeInterval = 36000.0;
|
||||
}
|
||||
|
||||
|
||||
- (void)dumpState
|
||||
{
|
||||
OOLog(@"dumpState.ai", @"State machine name: %@", stateMachineName);
|
||||
OOLog(@"dumpState.ai", @"Current state: %@", currentState);
|
||||
#ifdef OO_BRAIN_AI
|
||||
if (rulingInstinct!= nil && OOLogWillDisplayMessagesInClass(@"dumpState.ai.instinct"))
|
||||
{
|
||||
OOLog(@"dumpState.ai.instinct", @"Ruling instinct:");
|
||||
OOLogPushIndent();
|
||||
OOLogIndent();
|
||||
NS_DURING
|
||||
[rulingInstinct dumpState];
|
||||
NS_HANDLER
|
||||
NS_ENDHANDLER
|
||||
OOLogPopIndent();
|
||||
}
|
||||
#endif
|
||||
OOLog(@"dumpState.ai", @"Next think time: %g", nextThinkTime);
|
||||
OOLog(@"dumpState.ai", @"Next think interval: %g", thinkTimeInterval);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
/* This is an attempt to fix the bugs referred to above regarding calls from
|
||||
__NSFireDelayedPerform with a corrupt self. I'm not certain whether this
|
||||
will fix the issue or merely cause a less weird crash in
|
||||
+deferredCallTrampolineWithInfo:.
|
||||
-- Ahruman 20070706
|
||||
*/
|
||||
@implementation AI (OOPrivate)
|
||||
|
||||
- (void)performDeferredCall:(SEL)selector withObject:(id)object afterDelay:(NSTimeInterval)delay
|
||||
{
|
||||
OOAIDeferredCallTrampolineInfo infoStruct;
|
||||
NSValue *info = nil;
|
||||
|
||||
if (selector != NULL)
|
||||
{
|
||||
infoStruct.ai = [self retain];
|
||||
infoStruct.selector = selector;
|
||||
infoStruct.parameter = object;
|
||||
|
||||
info = [[NSValue alloc] initWithBytes:&infoStruct objCType:@encode(OOAIDeferredCallTrampolineInfo)];
|
||||
|
||||
[[AI class] performSelector:@selector(deferredCallTrampolineWithInfo:)
|
||||
withObject:info
|
||||
afterDelay:delay];
|
||||
[info release];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+ (void)deferredCallTrampolineWithInfo:(NSValue *)info
|
||||
{
|
||||
OOAIDeferredCallTrampolineInfo infoStruct;
|
||||
|
||||
if (info != nil)
|
||||
{
|
||||
assert(strcmp([info objCType], @encode(OOAIDeferredCallTrampolineInfo)) == 0);
|
||||
[info getValue:&infoStruct];
|
||||
|
||||
[infoStruct.ai performSelector:infoStruct.selector withObject:infoStruct.parameter];
|
||||
|
||||
[infoStruct.ai release];
|
||||
[infoStruct.parameter release];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void)refreshOwnerDesc
|
||||
{
|
||||
ShipEntity *owner = [self owner];
|
||||
[ownerDesc release];
|
||||
if (owner != nil)
|
||||
{
|
||||
ownerDesc = [[NSString alloc] initWithFormat:@"%@ %d", [owner name], [owner universalID]];
|
||||
}
|
||||
else
|
||||
{
|
||||
ownerDesc = @"no owner";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (NSDictionary *) loadStateMachine:(NSString *)smName
|
||||
{
|
||||
NSDictionary *newSM = nil;
|
||||
NSMutableDictionary *cleanSM = nil;
|
||||
OOCacheManager *cacheMgr = [OOCacheManager sharedCache];
|
||||
NSEnumerator *stateEnum = nil;
|
||||
NSString *stateKey = nil;
|
||||
NSDictionary *stateHandlers = nil;
|
||||
NSAutoreleasePool *pool = nil;
|
||||
|
||||
newSM = [cacheMgr objectForKey:smName inCache:@"AIs"];
|
||||
if (newSM != nil && ![newSM isKindOfClass:[NSDictionary class]]) return nil; // catches use of @"nil" to indicate no AI found.
|
||||
|
||||
if (newSM == nil)
|
||||
{
|
||||
pool = [[NSAutoreleasePool alloc] init];
|
||||
OOLog(@"ai.load", @"Loading and sanitizing AI \"%@\"", smName);
|
||||
OOLogPushIndent();
|
||||
OOLogIndentIf(@"ai.load");
|
||||
|
||||
NS_DURING
|
||||
// Load state machine and validate against whitelist.
|
||||
newSM = [ResourceManager dictionaryFromFilesNamed:smName inFolder:@"AIs" andMerge:NO];
|
||||
if (newSM == nil)
|
||||
{
|
||||
[cacheMgr setObject:@"nil" forKey:smName inCache:@"AIs"];
|
||||
NS_VALUERETURN(nil, NSDictionary *);
|
||||
}
|
||||
|
||||
cleanSM = [NSMutableDictionary dictionaryWithCapacity:[newSM count]];
|
||||
|
||||
for (stateEnum = [newSM keyEnumerator]; (stateKey = [stateEnum nextObject]); )
|
||||
{
|
||||
stateHandlers = [newSM objectForKey:stateKey];
|
||||
if (![stateHandlers isKindOfClass:[NSDictionary class]])
|
||||
{
|
||||
OOLogWARN(@"ai.invalidFormat.state", @"State \"%@\" in AI \"%@\" is not a dictionary, ignoring.", stateKey, smName);
|
||||
continue;
|
||||
}
|
||||
|
||||
stateHandlers = [self cleanHandlers:stateHandlers forState:stateKey stateMachine:smName];
|
||||
[cleanSM setObject:stateHandlers forKey:stateKey];
|
||||
}
|
||||
|
||||
// Make immutable.
|
||||
newSM = [[cleanSM copy] autorelease];
|
||||
|
||||
// Cache.
|
||||
[cacheMgr setObject:newSM forKey:smName inCache:@"AIs"];
|
||||
NS_HANDLER
|
||||
OOLogPopIndent();
|
||||
[localException raise];
|
||||
NS_ENDHANDLER
|
||||
|
||||
OOLogPopIndent();
|
||||
[pool release];
|
||||
}
|
||||
|
||||
return newSM;
|
||||
}
|
||||
|
||||
|
||||
- (NSDictionary *) cleanHandlers:(NSDictionary *)handlers forState:(NSString *)stateKey stateMachine:(NSString *)smName
|
||||
{
|
||||
NSEnumerator *handlerEnum = nil;
|
||||
NSString *handlerKey = nil;
|
||||
NSArray *handlerActions = nil;
|
||||
NSMutableDictionary *result = nil;
|
||||
|
||||
result = [NSMutableDictionary dictionaryWithCapacity:[handlers count]];
|
||||
for (handlerEnum = [handlers keyEnumerator]; (handlerKey = [handlerEnum nextObject]); )
|
||||
{
|
||||
handlerActions = [handlers objectForKey:handlerKey];
|
||||
if (![handlerActions isKindOfClass:[NSArray class]])
|
||||
{
|
||||
OOLogWARN(@"ai.invalidFormat.handler", @"Handler \"%@\" for state \"%@\" in AI \"%@\" is not an array, ignoring.", handlerKey, stateKey, smName);
|
||||
continue;
|
||||
}
|
||||
|
||||
handlerActions = [self cleanActions:handlerActions forHandler:handlerKey state:stateKey stateMachine:smName];
|
||||
[result setObject:handlerActions forKey:handlerKey];
|
||||
}
|
||||
|
||||
// Return immutable copy.
|
||||
return [[result copy] autorelease];
|
||||
}
|
||||
|
||||
|
||||
- (NSArray *) cleanActions:(NSArray *)actions forHandler:(NSString *)handlerKey state:(NSString *)stateKey stateMachine:(NSString *)smName
|
||||
{
|
||||
NSEnumerator *actionEnum = nil;
|
||||
NSString *action = nil;
|
||||
NSRange spaceRange;
|
||||
NSString *selector = nil;
|
||||
id aliasedSelector = nil;
|
||||
NSMutableArray *result = nil;
|
||||
static NSSet *whitelist = nil;
|
||||
static NSDictionary *aliases = nil;
|
||||
NSArray *whitelistArray1 = nil;
|
||||
NSArray *whitelistArray2 = nil;
|
||||
|
||||
if (whitelist == nil)
|
||||
{
|
||||
whitelistArray1 = [[ResourceManager whitelistDictionary] arrayForKey:@"ai_methods"];
|
||||
if (whitelistArray1 == nil) whitelistArray1 = [NSArray array];
|
||||
whitelistArray2 = [[ResourceManager whitelistDictionary] arrayForKey:@"ai_and_action_methods"];
|
||||
if (whitelistArray2 != nil) whitelistArray1 = [whitelistArray1 arrayByAddingObjectsFromArray:whitelistArray2];
|
||||
|
||||
whitelist = [[NSSet alloc] initWithArray:whitelistArray1];
|
||||
aliases = [[[ResourceManager whitelistDictionary] dictionaryForKey:@"ai_method_aliases"] retain];
|
||||
}
|
||||
|
||||
result = [NSMutableArray arrayWithCapacity:[actions count]];
|
||||
for (actionEnum = [actions objectEnumerator]; (action = [actionEnum nextObject]); )
|
||||
{
|
||||
if (![action isKindOfClass:[NSString class]])
|
||||
{
|
||||
OOLogWARN(@"ai.invalidFormat.action", @"An action in handler \"%@\" for state \"%@\" in AI \"%@\" is not a string, ignoring.", handlerKey, stateKey, smName);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Trim spaces from beginning and end.
|
||||
action = [action stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
|
||||
|
||||
// Cut off parameters.
|
||||
spaceRange = [action rangeOfString:@" "];
|
||||
if (spaceRange.location == NSNotFound) selector = action;
|
||||
else selector = [action substringToIndex:spaceRange.location];
|
||||
|
||||
// Look in alias table.
|
||||
aliasedSelector = [aliases objectForKey:selector];
|
||||
if (aliasedSelector != nil)
|
||||
{
|
||||
if ([aliasedSelector isKindOfClass:[NSString class]])
|
||||
{
|
||||
// Change selector and action to use real method name.
|
||||
selector = aliasedSelector;
|
||||
if (spaceRange.location == NSNotFound) action = aliasedSelector;
|
||||
else action = [aliasedSelector stringByAppendingString:[action substringFromIndex:spaceRange.location]];
|
||||
}
|
||||
else if ([aliasedSelector isKindOfClass:[NSArray class]] && [aliasedSelector count] != 0)
|
||||
{
|
||||
// Alias is complete expression, pretokenized in anticipation of a tokenized future.
|
||||
action = [aliasedSelector componentsJoinedByString:@" "];
|
||||
selector = [[aliasedSelector objectAtIndex:0] description];
|
||||
}
|
||||
}
|
||||
|
||||
// Check for selector in whitelist.
|
||||
if (![whitelist containsObject:selector])
|
||||
{
|
||||
OOLog(@"ai.unpermittedMethod", @"Handler \"%@\" for state \"%@\" in AI \"%@\" uses \"%@\", which is not a permitted AI method. In a future version of Oolite, this method will be removed from the handler. If you believe the handler should be a permitted method, please report it to bugs@oolite.org.", handlerKey, stateKey, smName, selector);
|
||||
// continue;
|
||||
}
|
||||
|
||||
[result addObject:action];
|
||||
}
|
||||
|
||||
// Return immutable copy.
|
||||
return [[result copy] autorelease];
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,90 @@
|
|||
/*
|
||||
|
||||
CollisionRegion.h
|
||||
|
||||
Collision regions are used to group entities which may potentially collide, to
|
||||
reduce the number of collision checks required.
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOCocoa.h"
|
||||
#import "OOMaths.h"
|
||||
|
||||
#define COLLISION_REGION_BORDER_RADIUS 32000.0f
|
||||
#define COLLISION_MAX_ENTITIES 128
|
||||
|
||||
@class Entity;
|
||||
|
||||
@interface CollisionRegion : NSObject
|
||||
{
|
||||
@public
|
||||
|
||||
BOOL isUniverse; // if YES location is origin and radius is 0.0f
|
||||
|
||||
int crid; // identifier
|
||||
Vector location; // center of the region
|
||||
GLfloat radius; // inner radius of the region
|
||||
GLfloat border_radius; // additiønal, border radius of the region (typically 32km or some value > the scanner range)
|
||||
|
||||
int checks_this_tick;
|
||||
|
||||
NSMutableArray *subregions;
|
||||
|
||||
@protected
|
||||
|
||||
BOOL isPlayerInRegion;
|
||||
|
||||
Entity **entity_array; // entities within the region
|
||||
int n_entities; // number of entities
|
||||
int max_entities; // so storage can be expanded
|
||||
|
||||
|
||||
CollisionRegion *parentRegion;
|
||||
|
||||
}
|
||||
|
||||
- (id) initAsUniverse;
|
||||
- (id) initAtLocation:(Vector) locn withRadius:(GLfloat) rad withinRegion:(CollisionRegion*) otherRegion;
|
||||
|
||||
- (void) clearSubregions;
|
||||
- (void) addSubregionAtPosition:(Vector) pos withRadius:(GLfloat) rad;
|
||||
|
||||
// update routines to check if a position is within the radius or within it's borders
|
||||
//
|
||||
BOOL positionIsWithinRegion( Vector position, CollisionRegion* region);
|
||||
BOOL sphereIsWithinRegion( Vector position, GLfloat rad, CollisionRegion* region);
|
||||
BOOL positionIsWithinBorders( Vector position, CollisionRegion* region);
|
||||
BOOL positionIsOnBorders( Vector position, CollisionRegion* region);
|
||||
NSArray* subregionsContainingPosition( Vector position, CollisionRegion* region);
|
||||
|
||||
// collision checking
|
||||
//
|
||||
- (void) clearEntityList;
|
||||
- (void) addEntity:(Entity*) ent;
|
||||
//
|
||||
- (BOOL) checkEntity:(Entity*) ent;
|
||||
//
|
||||
- (void) findCollisions;
|
||||
- (void) findShadowedEntities;
|
||||
|
||||
- (NSString*) debugOut;
|
||||
|
||||
@end
|
|
@ -0,0 +1,596 @@
|
|||
/*
|
||||
|
||||
CollisionRegion.m
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
*/
|
||||
|
||||
#import "CollisionRegion.h"
|
||||
#import "OOMaths.h"
|
||||
#import "Universe.h"
|
||||
#import "Entity.h"
|
||||
#import "ShipEntity.h"
|
||||
#import "PlanetEntity.h"
|
||||
#import "StationEntity.h"
|
||||
#import "PlayerEntity.h"
|
||||
|
||||
|
||||
@implementation CollisionRegion
|
||||
|
||||
- (NSString *) description
|
||||
{
|
||||
int n_subs = [subregions count];
|
||||
return [NSString stringWithFormat:@"ID: %d, %d subregions, %d ents", crid, n_subs, n_entities];
|
||||
}
|
||||
|
||||
// basic alloc/ dealloc routines
|
||||
//
|
||||
static int crid_counter = 1;
|
||||
//
|
||||
- (id) initAsUniverse
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
location = kZeroVector;
|
||||
radius = 0.0f;
|
||||
border_radius = 0.0f;
|
||||
isUniverse = YES;
|
||||
isPlayerInRegion = NO;
|
||||
|
||||
max_entities = COLLISION_MAX_ENTITIES;
|
||||
n_entities = 0;
|
||||
entity_array = (Entity**) malloc( max_entities * sizeof(Entity*));
|
||||
|
||||
subregions = [[NSMutableArray alloc] initWithCapacity: 32]; // retained
|
||||
|
||||
parentRegion = nil;
|
||||
|
||||
crid = crid_counter++;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id) initAtLocation:(Vector) locn withRadius:(GLfloat) rad withinRegion:(CollisionRegion*) otherRegion
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
location = locn;
|
||||
radius = rad;
|
||||
border_radius = COLLISION_REGION_BORDER_RADIUS;
|
||||
isUniverse = NO;
|
||||
isPlayerInRegion = NO;
|
||||
|
||||
max_entities = COLLISION_MAX_ENTITIES;
|
||||
n_entities = 0;
|
||||
entity_array = (Entity**) malloc( max_entities * sizeof(Entity*));
|
||||
|
||||
subregions = [[NSMutableArray alloc] initWithCapacity: 32]; // retained
|
||||
|
||||
if (otherRegion)
|
||||
parentRegion = otherRegion;
|
||||
|
||||
crid = crid_counter++;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void) dealloc
|
||||
{
|
||||
if (entity_array)
|
||||
free((void *)entity_array); // free up the allocated space
|
||||
if (subregions)
|
||||
[subregions release];
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (void) clearSubregions
|
||||
{
|
||||
int i;
|
||||
int n_subs = [subregions count];
|
||||
for (i = 0; i < n_subs; i++)
|
||||
[(CollisionRegion*)[subregions objectAtIndex: i] clearSubregions];
|
||||
[subregions removeAllObjects];
|
||||
}
|
||||
|
||||
- (void) addSubregionAtPosition:(Vector) pos withRadius:(GLfloat) rad
|
||||
{
|
||||
// check if this can be fitted within any of the subregions
|
||||
//
|
||||
int i;
|
||||
int n_subs = [subregions count];
|
||||
for (i = 0; i < n_subs; i++)
|
||||
{
|
||||
CollisionRegion* sub = (CollisionRegion*)[subregions objectAtIndex: i];
|
||||
if (sphereIsWithinRegion( pos, rad, sub))
|
||||
{
|
||||
// if it fits, put it in!
|
||||
[sub addSubregionAtPosition: pos withRadius: rad];
|
||||
return;
|
||||
}
|
||||
if (positionIsWithinRegion( pos, sub))
|
||||
{
|
||||
// crosses the border of this region already - leave it out
|
||||
return;
|
||||
}
|
||||
}
|
||||
// no subregion fit - move on...
|
||||
//
|
||||
CollisionRegion* sub = [[CollisionRegion alloc] initAtLocation: pos withRadius: rad withinRegion: self];
|
||||
[subregions addObject:sub];
|
||||
[sub release];
|
||||
}
|
||||
|
||||
|
||||
// update routines to check if a position is within the radius or within it's borders
|
||||
//
|
||||
BOOL positionIsWithinRegion( Vector position, CollisionRegion* region)
|
||||
{
|
||||
if (!region)
|
||||
return NO;
|
||||
|
||||
if (region->isUniverse)
|
||||
return YES;
|
||||
|
||||
Vector loc = region->location;
|
||||
GLfloat r1 = region->radius;
|
||||
|
||||
if ((position.x < loc.x - r1)||(position.x > loc.x + r1)||
|
||||
(position.y < loc.y - r1)||(position.y > loc.y + r1)||
|
||||
(position.z < loc.z - r1)||(position.z > loc.z + r1))
|
||||
return NO;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
BOOL sphereIsWithinRegion( Vector position, GLfloat rad, CollisionRegion* region)
|
||||
{
|
||||
if (!region)
|
||||
return NO;
|
||||
|
||||
if (region->isUniverse)
|
||||
return YES;
|
||||
|
||||
Vector loc = region->location;
|
||||
GLfloat r1 = region->radius;
|
||||
|
||||
if ((position.x - rad < loc.x - r1)||(position.x + rad > loc.x + r1)||
|
||||
(position.y - rad < loc.y - r1)||(position.y + rad > loc.y + r1)||
|
||||
(position.z - rad < loc.z - r1)||(position.z + rad > loc.z + r1))
|
||||
return NO;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
BOOL positionIsWithinBorders( Vector position, CollisionRegion* region)
|
||||
{
|
||||
if (!region)
|
||||
return NO;
|
||||
|
||||
if (region->isUniverse)
|
||||
return YES;
|
||||
|
||||
Vector loc = region->location;
|
||||
GLfloat r1 = region->radius + region->border_radius;
|
||||
|
||||
if ((position.x < loc.x - r1)||(position.x > loc.x + r1)||
|
||||
(position.y < loc.y - r1)||(position.y > loc.y + r1)||
|
||||
(position.z < loc.z - r1)||(position.z > loc.z + r1))
|
||||
return NO;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
BOOL positionIsOnBorders( Vector position, CollisionRegion* region)
|
||||
{
|
||||
if (!region)
|
||||
return NO;
|
||||
|
||||
if (region->isUniverse)
|
||||
return NO;
|
||||
|
||||
Vector loc = region->location;
|
||||
GLfloat r2 = region->radius + region->border_radius;
|
||||
|
||||
if ((position.x < loc.x - r2)||(position.x > loc.x + r2)||
|
||||
(position.y < loc.y - r2)||(position.y > loc.y + r2)||
|
||||
(position.z < loc.z - r2)||(position.z > loc.z + r2))
|
||||
return NO;
|
||||
|
||||
return (!positionIsWithinRegion( position, region));
|
||||
}
|
||||
|
||||
NSArray* subregionsContainingPosition( Vector position, CollisionRegion* region)
|
||||
{
|
||||
NSArray* subs = region->subregions;
|
||||
NSMutableArray* result = [NSMutableArray array]; // autoreleased
|
||||
|
||||
if (!subs)
|
||||
return result; // empty array
|
||||
|
||||
int i;
|
||||
int n_subs = [subs count];
|
||||
for (i = 0; i < n_subs; i++)
|
||||
if (positionIsWithinBorders( position, (CollisionRegion*)[subs objectAtIndex: i]))
|
||||
[result addObject: [subs objectAtIndex: i]];
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// collision checking
|
||||
//
|
||||
- (void) clearEntityList
|
||||
{
|
||||
n_entities = 0;
|
||||
int i;
|
||||
int n_subs = [subregions count];
|
||||
for (i = 0; i < n_subs; i++)
|
||||
[(CollisionRegion*)[subregions objectAtIndex: i] clearEntityList];
|
||||
isPlayerInRegion = NO;
|
||||
}
|
||||
|
||||
- (void) addEntity:(Entity*) ent
|
||||
{
|
||||
// expand if necessary
|
||||
//
|
||||
if (n_entities == max_entities)
|
||||
{
|
||||
max_entities = 1 + max_entities * 2;
|
||||
Entity** new_store = (Entity**) malloc( max_entities * sizeof(Entity*));
|
||||
int i;
|
||||
for (i = 0; i < n_entities; i++)
|
||||
new_store[i] = entity_array[i];
|
||||
free( (void*)entity_array);
|
||||
entity_array = new_store;
|
||||
}
|
||||
|
||||
isPlayerInRegion |= (ent->isPlayer);
|
||||
entity_array[n_entities++] = ent;
|
||||
}
|
||||
|
||||
- (BOOL) checkEntity:(Entity*) ent
|
||||
{
|
||||
Vector position = ent->position;
|
||||
|
||||
// check subregions
|
||||
BOOL foundRegion = NO;
|
||||
int n_subs = [subregions count];
|
||||
int i;
|
||||
for (i = 0; i < n_subs; i++)
|
||||
{
|
||||
CollisionRegion* sub = (CollisionRegion*)[subregions objectAtIndex:i];
|
||||
if (positionIsWithinBorders( position, sub))
|
||||
foundRegion |= [sub checkEntity:ent];
|
||||
}
|
||||
if (foundRegion)
|
||||
return YES; // it's in a subregion so no further action is neccesary
|
||||
|
||||
if (!positionIsWithinBorders( position, self))
|
||||
return NO;
|
||||
|
||||
[self addEntity: ent];
|
||||
[ent setCollisionRegion: self];
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
- (void) findCollisions
|
||||
{
|
||||
//
|
||||
// According to Shark, when this was in Universe this was where Oolite spent most time!
|
||||
//
|
||||
Entity *e1,*e2;
|
||||
Vector p1, p2;
|
||||
double dist2, r1, r2, r0, min_dist2;
|
||||
int i;
|
||||
Entity* entities_to_test[n_entities];
|
||||
//
|
||||
|
||||
// reject trivial cases
|
||||
//
|
||||
if (n_entities < 2)
|
||||
return;
|
||||
|
||||
// only check unfiltered entities
|
||||
int n_entities_to_test = 0;
|
||||
for (i = 0; i < n_entities; i++)
|
||||
{
|
||||
e1 = entity_array[i];
|
||||
if (!(e1->collisionTestFilter))
|
||||
entities_to_test[n_entities_to_test++] = e1;
|
||||
}
|
||||
|
||||
#ifndef NDEBUG
|
||||
if (gDebugFlags & DEBUG_COLLISIONS)
|
||||
OOLog(@"collisionRegion.debug", @"DEBUG in collision region %@ testing %d out of %d entities", self, n_entities_to_test, n_entities);
|
||||
#endif
|
||||
|
||||
if (n_entities_to_test < 2)
|
||||
return;
|
||||
|
||||
// clear collision variables
|
||||
//
|
||||
for (i = 0; i < n_entities_to_test; i++)
|
||||
{
|
||||
e1 = entities_to_test[i];
|
||||
if (e1->hasCollided)
|
||||
[[e1 collisionArray] removeAllObjects];
|
||||
e1->hasCollided = NO;
|
||||
if (e1->isShip)
|
||||
[(ShipEntity*)e1 setProximity_alert:nil];
|
||||
e1->collider = nil;
|
||||
}
|
||||
|
||||
// test for collisions in each subregion
|
||||
//
|
||||
int n_subs = [subregions count];
|
||||
for (i = 0; i < n_subs; i++)
|
||||
[(CollisionRegion*)[subregions objectAtIndex: i] findCollisions];
|
||||
//
|
||||
|
||||
checks_this_tick = 0;
|
||||
|
||||
// test each entity in this region against the entities in its collision chain
|
||||
//
|
||||
for (i = 0; i < n_entities_to_test; i++)
|
||||
{
|
||||
e1 = entities_to_test[i];
|
||||
p1 = e1->position;
|
||||
r1 = e1->collision_radius;
|
||||
|
||||
// check against the first in the collision chain
|
||||
e2 = e1->collision_chain;
|
||||
while (e2 != nil)
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
if (gDebugFlags & DEBUG_COLLISIONS)
|
||||
{
|
||||
OOLog(@"collisionRegion.debug", @"DEBUG Testing collision between %@ (%@) and %@ (%@)",
|
||||
e1, (e1->collisionTestFilter)?@"YES":@"NO", e2, (e2->collisionTestFilter)?@"YES":@"NO");
|
||||
}
|
||||
#endif
|
||||
|
||||
checks_this_tick++;
|
||||
|
||||
p2 = e2->position;
|
||||
r2 = e2->collision_radius;
|
||||
r0 = r1 + r2;
|
||||
p2.x -= p1.x; p2.y -= p1.y; p2.z -= p1.z;
|
||||
dist2 = p2.x*p2.x + p2.y*p2.y + p2.z*p2.z;
|
||||
min_dist2 = r0 * r0;
|
||||
if (dist2 < PROXIMITY_WARN_DISTANCE2 * min_dist2)
|
||||
{
|
||||
if ((e1->isShip) && (e2->isShip))
|
||||
{
|
||||
if ((dist2 < PROXIMITY_WARN_DISTANCE2 * r2 * r2) || (dist2 < PROXIMITY_WARN_DISTANCE2 * r1 * r1))
|
||||
{
|
||||
[(ShipEntity*)e1 setProximity_alert:(ShipEntity*)e2];
|
||||
[(ShipEntity*)e2 setProximity_alert:(ShipEntity*)e1];
|
||||
}
|
||||
}
|
||||
if (dist2 < min_dist2)
|
||||
{
|
||||
BOOL collision = NO;
|
||||
|
||||
if (e1->isStation)
|
||||
{
|
||||
StationEntity* se1 = (StationEntity*) e1;
|
||||
if ([se1 shipIsInDockingCorridor: (ShipEntity*)e2])
|
||||
collision = NO;
|
||||
else
|
||||
collision = [e1 checkCloseCollisionWith: e2];
|
||||
}
|
||||
else if (e2->isStation)
|
||||
{
|
||||
StationEntity* se2 = (StationEntity*) e2;
|
||||
if ([se2 shipIsInDockingCorridor: (ShipEntity*)e1])
|
||||
collision = NO;
|
||||
else
|
||||
collision = [e2 checkCloseCollisionWith: e1];
|
||||
}
|
||||
else
|
||||
collision = [e1 checkCloseCollisionWith: e2];
|
||||
|
||||
if (collision)
|
||||
{
|
||||
// now we have no need to check the e2-e1 collision
|
||||
if (e1->collider)
|
||||
[[e1 collisionArray] addObject:e1->collider];
|
||||
else
|
||||
[[e1 collisionArray] addObject:e2];
|
||||
e1->hasCollided = YES;
|
||||
//
|
||||
if (e2->collider)
|
||||
[[e2 collisionArray] addObject:e2->collider];
|
||||
else
|
||||
[[e2 collisionArray] addObject:e1];
|
||||
e2->hasCollided = YES;
|
||||
}
|
||||
}
|
||||
}
|
||||
// check the next in the collision chain
|
||||
e2 = e2->collision_chain;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BOOL testEntityOccludedByEntity(Entity* e1, Entity* e2, PlanetEntity* the_sun)
|
||||
{
|
||||
// simple tests
|
||||
if (e1 == e2)
|
||||
return NO; // you can't shade self
|
||||
//
|
||||
if (e2 == the_sun)
|
||||
return NO; // sun can't shade itself
|
||||
//
|
||||
if ((e2->isShip == NO)&&(e2->isPlanet == NO))
|
||||
return NO; // only ships and planets shade
|
||||
//
|
||||
if (e2->collision_radius < e1->collision_radius)
|
||||
return NO; // smaller can't shade bigger
|
||||
//
|
||||
if (e2->isSunlit == NO)
|
||||
return NO; // things already /in/ shade can't shade things more.
|
||||
//
|
||||
// check projected sizes of discs
|
||||
GLfloat d2_sun = distance2( e1->position, the_sun->position);
|
||||
GLfloat d2_e2sun = distance2( e2->position, the_sun->position);
|
||||
if (d2_e2sun > d2_sun)
|
||||
return NO; // you are nearer the sun than the potential occluder, so it can't shade you
|
||||
//
|
||||
GLfloat d2_e2 = distance2( e1->position, e2->position);
|
||||
GLfloat cr_sun = the_sun->collision_radius;
|
||||
GLfloat cr_e2 = e2->collision_radius;
|
||||
if (e2->isShip)
|
||||
cr_e2 *= 0.90f; // 10% smaller shadow for ships
|
||||
if (e2->isPlanet)
|
||||
cr_e2 = e2->collision_radius; // use collision radius for planets
|
||||
//
|
||||
GLfloat cr2_sun_scaled = cr_sun * cr_sun * d2_e2 / d2_sun;
|
||||
if (cr_e2 * cr_e2 < cr2_sun_scaled)
|
||||
return NO; // if solar disc projected to the distance of e2 > collision radius it can't be shaded by e2
|
||||
//
|
||||
// check angles subtended by sun and occluder
|
||||
double theta_sun = asin( cr_sun / sqrt(d2_sun)); // 1/2 angle subtended by sun
|
||||
double theta_e2 = asin( cr_e2 / sqrt(d2_e2)); // 1/2 angle subtended by e2
|
||||
Vector p_sun = the_sun->position;
|
||||
Vector p_e2 = e2->position;
|
||||
Vector p_e1 = e1->position;
|
||||
Vector v_sun = make_vector( p_sun.x - p_e1.x, p_sun.y - p_e1.y, p_sun.z - p_e1.z);
|
||||
if (v_sun.x||v_sun.y||v_sun.z)
|
||||
v_sun = vector_normal(v_sun);
|
||||
else
|
||||
v_sun.z = 1.0f;
|
||||
//
|
||||
Vector v_e2 = make_vector( p_e2.x - p_e1.x, p_e2.y - p_e1.y, p_e2.z - p_e1.z);
|
||||
if (v_e2.x||v_e2.y||v_e2.z)
|
||||
v_e2 = vector_normal(v_e2);
|
||||
else
|
||||
v_e2.x = 1.0f;
|
||||
double phi = acos( dot_product( v_sun, v_e2)); // angle between sun and e2 from e1's viewpoint
|
||||
//
|
||||
if (theta_sun + phi > theta_e2)
|
||||
return NO; // sun is not occluded
|
||||
//
|
||||
// all tests done e1 is in shade!
|
||||
//
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void) findShadowedEntities
|
||||
{
|
||||
//
|
||||
// Copy/pasting the collision code to detect occlusion!
|
||||
//
|
||||
Entity* e1;
|
||||
int i,j;
|
||||
|
||||
if ([UNIVERSE reducedDetail]) return; // don't do this in reduced detail mode
|
||||
|
||||
PlanetEntity* the_sun = [UNIVERSE sun];
|
||||
|
||||
if (!the_sun)
|
||||
return; // sun is required
|
||||
|
||||
//
|
||||
// get a list of planet entities because they can shade across regions
|
||||
int ent_count = UNIVERSE->n_entities;
|
||||
Entity** uni_entities = UNIVERSE->sortedEntities; // grab the public sorted list
|
||||
Entity* planets[ent_count];
|
||||
int n_planets = 0;
|
||||
for (i = 0; i < ent_count; i++)
|
||||
if ((uni_entities[i]->isPlanet)&&(uni_entities[i] != the_sun))
|
||||
planets[n_planets++] = uni_entities[i]; // don't bother retaining - nothing will happen to them!
|
||||
//
|
||||
|
||||
// reject trivial cases
|
||||
//
|
||||
if (n_entities < 2)
|
||||
return;
|
||||
|
||||
// test for shadows in each subregion
|
||||
//
|
||||
int n_subs = [subregions count];
|
||||
for (i = 0; i < n_subs; i++)
|
||||
[[subregions objectAtIndex: i] findShadowedEntities];
|
||||
//
|
||||
|
||||
// test each entity in this region against the others
|
||||
//
|
||||
for (i = 0; i < n_entities; i++)
|
||||
{
|
||||
e1 = entity_array[i];
|
||||
BOOL occluder_moved = NO;
|
||||
if ([e1 status] == STATUS_COCKPIT_DISPLAY)
|
||||
{
|
||||
e1->isSunlit = YES;
|
||||
e1->shadingEntityID = NO_TARGET;
|
||||
continue; // don't check shading in demo mode
|
||||
}
|
||||
if (e1->isSunlit == NO)
|
||||
{
|
||||
Entity* occluder = [UNIVERSE entityForUniversalID:e1->shadingEntityID];
|
||||
if (occluder)
|
||||
occluder_moved = occluder->hasMoved;
|
||||
}
|
||||
if (((e1->isShip)||(e1->isPlanet))&&((e1->hasMoved)||occluder_moved))
|
||||
{
|
||||
e1->isSunlit = YES; // sunlit by default
|
||||
e1->shadingEntityID = NO_TARGET;
|
||||
//
|
||||
// check demo mode here..
|
||||
if ((e1->isPlayer)&&([(PlayerEntity*)e1 showDemoShips]))
|
||||
continue; // don't check shading in demo mode
|
||||
//
|
||||
// test planets
|
||||
//
|
||||
for (j = 0; j < n_planets; j++)
|
||||
{
|
||||
if (testEntityOccludedByEntity(e1, planets[j], the_sun))
|
||||
{
|
||||
e1->isSunlit = NO;
|
||||
e1->shadingEntityID = [planets[j] universalID];
|
||||
}
|
||||
}
|
||||
//
|
||||
// test local entities
|
||||
//
|
||||
for (j = i + 1; j < n_entities; j++)
|
||||
{
|
||||
if (testEntityOccludedByEntity(e1, entity_array[j], the_sun))
|
||||
{
|
||||
e1->isSunlit = NO;
|
||||
e1->shadingEntityID = [entity_array[j] universalID];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (NSString*) debugOut
|
||||
{
|
||||
int i;
|
||||
int n_subs = [subregions count];
|
||||
NSMutableString* result = [[NSMutableString alloc] initWithFormat:@"%d:", n_entities];
|
||||
for (i = 0; i < n_subs; i++)
|
||||
[result appendString:[(CollisionRegion*)[subregions objectAtIndex:i] debugOut]];
|
||||
return [result autorelease];
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,104 @@
|
|||
/*
|
||||
|
||||
OODebugMonitor.h
|
||||
|
||||
Debugging services object for Oolite.
|
||||
|
||||
The debug controller implements Oolite's part of debugging support. It can
|
||||
connect to one debugger object, which conforms to the OODebuggerInterface
|
||||
formal protocol. This can either be (part of) a debugger loaded into Oolite
|
||||
itself (as in the Mac Debug OXP), or provide communications with an external
|
||||
debugger (for instance, over Distributed Objects or TCP/IP).
|
||||
|
||||
|
||||
Oolite Debug OXP
|
||||
|
||||
Copyright (C) 2007 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOCocoa.h"
|
||||
#import "OOWeakReference.h"
|
||||
#import "OODebuggerInterface.h"
|
||||
|
||||
@class OOScript;
|
||||
|
||||
|
||||
@protocol OODebugMonitorInterface
|
||||
|
||||
// Note: disconnectDebugger:message: will cause a disconnectDebugMonitor:message: message to be sent to the debugger. The debugger should not send disconnectDebugger:message: in response to disconnectDebugMonitor:message:.
|
||||
- (void)disconnectDebugger:(in id<OODebuggerInterface>)debugger
|
||||
message:(in NSString *)message;
|
||||
|
||||
|
||||
// *** JavaScript console support.
|
||||
|
||||
// Perform a JS command as though entered at the console, including echoing.
|
||||
- (oneway void)performJSConsoleCommand:(in NSString *)command;
|
||||
|
||||
- (id)configurationValueForKey:(in NSString *)key;
|
||||
- (void)setConfigurationValue:(in id)value forKey:(in NSString *)key;
|
||||
|
||||
- (NSString *)sourceCodeForFile:(in NSString *)filePath line:(in unsigned)line;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@interface OODebugMonitor: OOWeakRefObject <OODebugMonitorInterface>
|
||||
{
|
||||
id<OODebuggerInterface> _debugger;
|
||||
|
||||
// JavaScript console support.
|
||||
OOScript *_script;
|
||||
struct JSObject *_jsSelf;
|
||||
|
||||
NSDictionary *_configFromOXPs; // Settings from debugConfig.plist
|
||||
NSMutableDictionary *_configOverrides; // Settings from preferences, modifiable through JS.
|
||||
|
||||
// Caches
|
||||
NSMutableDictionary *_fgColors,
|
||||
*_bgColors,
|
||||
*_sourceFiles;
|
||||
}
|
||||
|
||||
+ (id)sharedDebugMonitor;
|
||||
- (BOOL)setDebugger:(id<OODebuggerInterface>)debugger;
|
||||
|
||||
// *** JavaScript console support.
|
||||
- (void)appendJSConsoleLine:(id)string
|
||||
colorKey:(NSString *)colorKey
|
||||
emphasisRange:(NSRange)emphasisRange;
|
||||
|
||||
- (void)appendJSConsoleLine:(id)string
|
||||
colorKey:(NSString *)colorKey;
|
||||
|
||||
- (void)clearJSConsole;
|
||||
- (void)showJSConsole;
|
||||
|
||||
- (id)configurationValueForKey:(NSString *)key class:(Class)class defaultValue:(id)value;
|
||||
- (long long)configurationIntValueForKey:(NSString *)key defaultValue:(long long)value;
|
||||
|
||||
- (NSArray *)configurationKeys;
|
||||
|
||||
- (BOOL) debuggerConnected;
|
||||
|
||||
@end
|
||||
|
|
@ -0,0 +1,622 @@
|
|||
/*
|
||||
|
||||
OODebugMonitor.m
|
||||
|
||||
|
||||
Oolite Debug OXP
|
||||
|
||||
Copyright (C) 2007 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#ifndef OO_EXCLUDE_DEBUG_SUPPORT
|
||||
|
||||
|
||||
#import "OODebugMonitor.h"
|
||||
#import "OOCollectionExtractors.h"
|
||||
#import "OOLogging.h"
|
||||
#import "ResourceManager.h"
|
||||
#import "NSStringOOExtensions.h"
|
||||
|
||||
#import "OOJSConsole.h"
|
||||
#import "OOScript.h"
|
||||
#import "OOJSScript.h"
|
||||
#import "OOJavaScriptEngine.h"
|
||||
#import "OOJSSpecialFunctions.h"
|
||||
|
||||
|
||||
static OODebugMonitor *sSingleton = nil;
|
||||
|
||||
|
||||
@interface OODebugMonitor (Private) <OOJavaScriptEngineMonitor>
|
||||
|
||||
- (void)disconnectDebuggerWithMessage:(NSString *)message;
|
||||
|
||||
- (NSDictionary *)mergedConfiguration;
|
||||
|
||||
/* Convert a configuration dictionary to a standard form. In particular,
|
||||
convert all colour specifiers to RGBA arrays with values in [0, 1], and
|
||||
converts "show-console" values to booleans.
|
||||
*/
|
||||
- (NSMutableDictionary *)normalizeConfigDictionary:(NSDictionary *)dictionary;
|
||||
- (id)normalizeConfigValue:(id)value forKey:(NSString *)key;
|
||||
|
||||
- (NSArray *)loadSourceFile:(NSString *)filePath;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation OODebugMonitor
|
||||
|
||||
- (id)init
|
||||
{
|
||||
NSUserDefaults *defaults = nil;
|
||||
NSDictionary *jsProps = nil;
|
||||
NSDictionary *config = nil;
|
||||
#if OOLITE_GNUSTEP
|
||||
NSString *NSApplicationWillTerminateNotification = @"ApplicationWillTerminate";
|
||||
#endif
|
||||
|
||||
self = [super init];
|
||||
if (self != nil)
|
||||
{
|
||||
config = [[[ResourceManager dictionaryFromFilesNamed:@"debugConfig.plist"
|
||||
inFolder:@"Config"
|
||||
andMerge:YES] mutableCopy] autorelease];
|
||||
_configFromOXPs = [[self normalizeConfigDictionary:config] copy];
|
||||
|
||||
defaults = [NSUserDefaults standardUserDefaults];
|
||||
config = [defaults dictionaryForKey:@"debug-settings-override"];
|
||||
config = [self normalizeConfigDictionary:config];
|
||||
if (config == nil) config = [NSMutableDictionary dictionary];
|
||||
_configOverrides = [config retain];
|
||||
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil];
|
||||
|
||||
#if OOJSENGINE_MONITOR_SUPPORT
|
||||
[[OOJavaScriptEngine sharedEngine] setMonitor:self];
|
||||
#endif
|
||||
|
||||
// Set up JavaScript side of console.
|
||||
jsProps = [NSDictionary dictionaryWithObjectsAndKeys:
|
||||
self, @"console",
|
||||
JSSpecialFunctionsObjectWrapper(NULL), @"special",
|
||||
nil];
|
||||
_script = [[OOScript nonLegacyScriptFromFileNamed:@"oolite-debug-console.js" properties:jsProps] retain];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
[self disconnectDebuggerWithMessage:@"Debug controller object destroyed while debugging in progress."];
|
||||
|
||||
[_configFromOXPs release];
|
||||
[_configOverrides release];
|
||||
|
||||
[_fgColors release];
|
||||
[_bgColors release];
|
||||
[_sourceFiles release];
|
||||
|
||||
if (_jsSelf != NULL)
|
||||
{
|
||||
[[OOJavaScriptEngine sharedEngine] removeGCRoot:&_jsSelf];
|
||||
}
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
+ (id)sharedDebugMonitor
|
||||
{
|
||||
// NOTE: assumes single-threaded access. The debug monitor is not, on the whole, thread safe.
|
||||
if (sSingleton == nil)
|
||||
{
|
||||
[[self alloc] init];
|
||||
}
|
||||
|
||||
return sSingleton;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)setDebugger:(id<OODebuggerInterface>)newDebugger
|
||||
{
|
||||
NSString *error = nil;
|
||||
|
||||
if (newDebugger != _debugger)
|
||||
{
|
||||
// Disconnect existing debugger, if any.
|
||||
if (newDebugger != nil)
|
||||
{
|
||||
[self disconnectDebuggerWithMessage:@"New debugger set."];
|
||||
}
|
||||
else
|
||||
{
|
||||
[self disconnectDebuggerWithMessage:@"Debugger disconnected programatically."];
|
||||
}
|
||||
|
||||
// If a new debugger was specified, try to connect it.
|
||||
if (newDebugger != nil)
|
||||
{
|
||||
NS_DURING
|
||||
if ([newDebugger connectDebugMonitor:self errorMessage:&error])
|
||||
{
|
||||
[newDebugger debugMonitor:self
|
||||
noteConfiguration:[self mergedConfiguration]];
|
||||
_debugger = [newDebugger retain];
|
||||
}
|
||||
else
|
||||
{
|
||||
OOLog(@"debugMonitor.setDebugger.failed", @"Could not connect to debugger %@, because an error occurred: %@", newDebugger, error);
|
||||
}
|
||||
NS_HANDLER
|
||||
OOLog(@"debugMonitor.setDebugger.failed", @"Could not connect to debugger %@, because an exception occurred: %@ -- %@", newDebugger, [localException name], [localException reason]);
|
||||
NS_ENDHANDLER
|
||||
}
|
||||
}
|
||||
|
||||
return _debugger == newDebugger;
|
||||
}
|
||||
|
||||
|
||||
- (oneway void)performJSConsoleCommand:(in NSString *)command
|
||||
{
|
||||
[_script doEvent:@"consolePerformJSCommand" withArgument:command];
|
||||
}
|
||||
|
||||
|
||||
- (void)appendJSConsoleLine:(id)string
|
||||
colorKey:(NSString *)colorKey
|
||||
emphasisRange:(NSRange)emphasisRange
|
||||
{
|
||||
if (string == nil) return;
|
||||
NS_DURING
|
||||
[_debugger debugMonitor:self
|
||||
jsConsoleOutput:string
|
||||
colorKey:colorKey
|
||||
emphasisRange:emphasisRange];
|
||||
NS_HANDLER
|
||||
OOLog(@"debugMonitor.debuggerConnection.exception", @"Exception while attempting to send JavaScript console text to debugger: %@ -- %@", [localException name], [localException reason]);
|
||||
NS_ENDHANDLER
|
||||
}
|
||||
|
||||
|
||||
- (void)appendJSConsoleLine:(id)string
|
||||
colorKey:(NSString *)colorKey
|
||||
{
|
||||
[self appendJSConsoleLine:string
|
||||
colorKey:colorKey
|
||||
emphasisRange:NSMakeRange(0, 0)];
|
||||
}
|
||||
|
||||
|
||||
- (void)clearJSConsole
|
||||
{
|
||||
NS_DURING
|
||||
[_debugger debugMonitorClearConsole:self];
|
||||
NS_HANDLER
|
||||
OOLog(@"debugMonitor.debuggerConnection.exception", @"Exception while attempting to clear JavaScript console: %@ -- %@", [localException name], [localException reason]);
|
||||
NS_ENDHANDLER
|
||||
}
|
||||
|
||||
|
||||
- (void)showJSConsole
|
||||
{
|
||||
NS_DURING
|
||||
[_debugger debugMonitorShowConsole:self];
|
||||
NS_HANDLER
|
||||
OOLog(@"debugMonitor.debuggerConnection.exception", @"Exception while attempting to show JavaScript console: %@ -- %@", [localException name], [localException reason]);
|
||||
NS_ENDHANDLER
|
||||
}
|
||||
|
||||
|
||||
- (id)configurationValueForKey:(in NSString *)key
|
||||
{
|
||||
return [self configurationValueForKey:key class:Nil defaultValue:nil];
|
||||
}
|
||||
|
||||
|
||||
- (id)configurationValueForKey:(NSString *)key class:(Class)class defaultValue:(id)value
|
||||
{
|
||||
id result = nil;
|
||||
|
||||
if (class == Nil) class = [NSObject class];
|
||||
|
||||
result = [_configOverrides objectForKey:key];
|
||||
if (![result isKindOfClass:class] && result != [NSNull null]) result = [_configFromOXPs objectForKey:key];
|
||||
if (![result isKindOfClass:class] && result != [NSNull null]) result = [[value retain] autorelease];
|
||||
if (result == [NSNull null]) result = nil;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
- (long long)configurationIntValueForKey:(NSString *)key defaultValue:(long long)value
|
||||
{
|
||||
long long result;
|
||||
id object = nil;
|
||||
|
||||
object = [self configurationValueForKey:key];
|
||||
if ([object respondsToSelector:@selector(longLongValue)]) result = [object longLongValue];
|
||||
else if ([object respondsToSelector:@selector(intValue)]) result = [object intValue];
|
||||
else result = value;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
- (void)setConfigurationValue:(in id)value forKey:(in NSString *)key
|
||||
{
|
||||
if (key == nil) return;
|
||||
|
||||
value = [self normalizeConfigValue:value forKey:key];
|
||||
|
||||
if (value == nil)
|
||||
{
|
||||
[_configOverrides removeObjectForKey:key];
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_configOverrides == nil) _configOverrides = [[NSMutableDictionary alloc] init];
|
||||
[_configOverrides setObject:value forKey:key];
|
||||
}
|
||||
|
||||
// Send changed value to debugger
|
||||
if (value == nil)
|
||||
{
|
||||
// Setting a nil value removes an override, and may reveal an underlying OXP-defined value
|
||||
value = [self configurationValueForKey:key];
|
||||
}
|
||||
NS_DURING
|
||||
[_debugger debugMonitor:self
|
||||
noteChangedConfigrationValue:value
|
||||
forKey:key];
|
||||
NS_HANDLER
|
||||
OOLog(@"debugMonitor.debuggerConnection.exception", @"Exception while attempting to send configuration update to debugger: %@ -- %@", [localException name], [localException reason]);
|
||||
NS_ENDHANDLER
|
||||
}
|
||||
|
||||
|
||||
- (NSArray *)configurationKeys
|
||||
{
|
||||
NSMutableSet *result = nil;
|
||||
|
||||
result = [NSMutableSet setWithCapacity:[_configFromOXPs count] + [_configOverrides count]];
|
||||
[result addObjectsFromArray:[_configFromOXPs allKeys]];
|
||||
[result addObjectsFromArray:[_configOverrides allKeys]];
|
||||
|
||||
return [[result allObjects] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
|
||||
}
|
||||
|
||||
|
||||
- (BOOL) debuggerConnected
|
||||
{
|
||||
return _debugger != nil;
|
||||
}
|
||||
|
||||
|
||||
- (NSString *)sourceCodeForFile:(in NSString *)filePath line:(in unsigned)line
|
||||
{
|
||||
id linesForFile = nil;
|
||||
|
||||
linesForFile = [_sourceFiles objectForKey:filePath];
|
||||
|
||||
if (linesForFile == nil)
|
||||
{
|
||||
linesForFile = [self loadSourceFile:filePath];
|
||||
if (linesForFile == nil) linesForFile = [NSArray arrayWithObject:[NSString stringWithFormat:@"<Can't load file %@>", filePath]];
|
||||
|
||||
if (_sourceFiles == nil) _sourceFiles = [[NSMutableDictionary alloc] init];
|
||||
[_sourceFiles setObject:linesForFile forKey:filePath];
|
||||
}
|
||||
|
||||
if ([linesForFile count] < line || line == 0) return @"<line out of range!>";
|
||||
|
||||
return [linesForFile objectAtIndex:line - 1];
|
||||
}
|
||||
|
||||
|
||||
- (void)disconnectDebugger:(in id<OODebuggerInterface>)debugger
|
||||
message:(in NSString *)message
|
||||
{
|
||||
if (debugger == nil) return;
|
||||
|
||||
if (debugger == _debugger)
|
||||
{
|
||||
[self disconnectDebuggerWithMessage:message];
|
||||
}
|
||||
else
|
||||
{
|
||||
OOLog(@"debugMonitor.disconnect.ignored", @"Attempt to disconnect debugger %@, which is not current debugger; ignoring.", debugger);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void)applicationWillTerminate:(NSNotification *)notification
|
||||
{
|
||||
if (_configOverrides != nil)
|
||||
{
|
||||
[[NSUserDefaults standardUserDefaults] setObject:_configOverrides forKey:@"debug-settings-override"];
|
||||
}
|
||||
|
||||
[self disconnectDebuggerWithMessage:@"Oolite is terminating."];
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation OODebugMonitor (Private)
|
||||
|
||||
- (void)disconnectDebuggerWithMessage:(NSString *)message
|
||||
{
|
||||
NS_DURING
|
||||
[_debugger disconnectDebugMonitor:self message:message];
|
||||
NS_HANDLER
|
||||
OOLog(@"debugMonitor.debuggerConnection.exception", @"Exception while attempting to disconnect debugger: %@ -- %@", [localException name], [localException reason]);
|
||||
NS_ENDHANDLER
|
||||
|
||||
id debugger = _debugger;
|
||||
_debugger = nil;
|
||||
[debugger release];
|
||||
}
|
||||
|
||||
|
||||
- (NSDictionary *)mergedConfiguration
|
||||
{
|
||||
NSMutableDictionary *result = nil;
|
||||
|
||||
result = [NSMutableDictionary dictionary];
|
||||
if (_configFromOXPs != nil) [result addEntriesFromDictionary:_configFromOXPs];
|
||||
if (_configOverrides != nil) [result addEntriesFromDictionary:_configOverrides];
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
- (NSArray *)loadSourceFile:(NSString *)filePath
|
||||
{
|
||||
NSString *contents = nil;
|
||||
NSArray *lines = nil;
|
||||
|
||||
if (filePath == nil) return nil;
|
||||
|
||||
contents = [NSString stringWithContentsOfUnicodeFile:filePath];
|
||||
if (contents == nil) return nil;
|
||||
|
||||
/* Extract lines from file.
|
||||
FIXME: this works with CRLF and LF, but not CR.
|
||||
*/
|
||||
lines = [contents componentsSeparatedByString:@"\n"];
|
||||
return lines;
|
||||
}
|
||||
|
||||
|
||||
- (NSMutableDictionary *)normalizeConfigDictionary:(NSDictionary *)dictionary
|
||||
{
|
||||
NSMutableDictionary *result = nil;
|
||||
NSEnumerator *keyEnum = nil;
|
||||
NSString *key = nil;
|
||||
id value = nil;
|
||||
|
||||
result = [NSMutableDictionary dictionaryWithCapacity:[dictionary count]];
|
||||
for (keyEnum = [dictionary keyEnumerator]; (key = [keyEnum nextObject]); )
|
||||
{
|
||||
value = [dictionary objectForKey:key];
|
||||
value = [self normalizeConfigValue:value forKey:key];
|
||||
|
||||
if (key != nil && value != nil) [result setObject:value forKey:key];
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
- (id)normalizeConfigValue:(id)value forKey:(NSString *)key
|
||||
{
|
||||
OOColor *color = nil;
|
||||
BOOL boolValue;
|
||||
|
||||
if (value != nil)
|
||||
{
|
||||
if ([key hasSuffix:@"-color"] || [key hasSuffix:@"-colour"])
|
||||
{
|
||||
color = [OOColor colorWithDescription:value];
|
||||
value = [color normalizedArray];
|
||||
}
|
||||
else if ([key hasPrefix:@"show-console"])
|
||||
{
|
||||
boolValue = OOBooleanFromObject(value, NO);
|
||||
value = [NSNumber numberWithBool:boolValue];
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
- (oneway void)jsEngine:(in byref OOJavaScriptEngine *)engine
|
||||
context:(in JSContext *)context
|
||||
error:(in JSErrorReport *)errorReport
|
||||
stackSkip:(unsigned)stackSkip
|
||||
withMessage:(in NSString *)message
|
||||
{
|
||||
NSString *colorKey = nil;
|
||||
NSString *prefix = nil;
|
||||
NSString *filePath = nil;
|
||||
NSString *sourceLine = nil;
|
||||
NSString *scriptLine = nil;
|
||||
NSMutableString *formattedMessage = nil;
|
||||
NSRange emphasisRange;
|
||||
NSString *showKey = nil;
|
||||
|
||||
if (_debugger == nil) return;
|
||||
|
||||
if (errorReport->flags & JSREPORT_WARNING)
|
||||
{
|
||||
colorKey = @"warning";
|
||||
prefix = @"Warning";
|
||||
}
|
||||
else if (errorReport->flags & JSREPORT_EXCEPTION)
|
||||
{
|
||||
colorKey = @"exception";
|
||||
prefix = @"Exception";
|
||||
}
|
||||
else
|
||||
{
|
||||
colorKey = @"error";
|
||||
prefix = @"Error";
|
||||
}
|
||||
|
||||
if (errorReport->flags & JSREPORT_STRICT)
|
||||
{
|
||||
prefix = [prefix stringByAppendingString:@" (strict mode)"];
|
||||
}
|
||||
|
||||
// Prefix and subsequent colon should be bold:
|
||||
emphasisRange = NSMakeRange(0, [prefix length] + 1);
|
||||
|
||||
formattedMessage = [NSMutableString stringWithFormat:@"%@: %@", prefix, message];
|
||||
|
||||
// Note that the "active script" isn't necessarily the one causing the
|
||||
// error, since one script can call another's methods.
|
||||
scriptLine = [[OOJSScript currentlyRunningScript] displayName];
|
||||
if (scriptLine != nil)
|
||||
{
|
||||
[formattedMessage appendFormat:@"\n Active script: %@", scriptLine];
|
||||
}
|
||||
|
||||
if (stackSkip == 0)
|
||||
{
|
||||
// Append file name and line
|
||||
if (errorReport->filename != NULL) filePath = [NSString stringWithUTF8String:errorReport->filename];
|
||||
if ([filePath length] != 0)
|
||||
{
|
||||
[formattedMessage appendFormat:@"\n %@, line %u", [filePath lastPathComponent], errorReport->lineno];
|
||||
|
||||
// Append source code
|
||||
sourceLine = [self sourceCodeForFile:filePath line:errorReport->lineno];
|
||||
if (sourceLine != nil)
|
||||
{
|
||||
[formattedMessage appendFormat:@":\n %@", sourceLine];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[self appendJSConsoleLine:formattedMessage
|
||||
colorKey:colorKey
|
||||
emphasisRange:emphasisRange];
|
||||
|
||||
if (errorReport->flags & JSREPORT_WARNING) showKey = @"show-console-on-warning";
|
||||
else showKey = @"show-console-on-warning";
|
||||
if (OOBooleanFromObject([self configurationValueForKey:showKey], NO))
|
||||
{
|
||||
[self showJSConsole];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (oneway void)jsEngine:(in byref OOJavaScriptEngine *)engine
|
||||
context:(in JSContext *)context
|
||||
logMessage:(in NSString *)message
|
||||
ofClass:(in NSString *)messageClass
|
||||
{
|
||||
[self appendJSConsoleLine:message colorKey:@"log"];
|
||||
if (OOBooleanFromObject([self configurationValueForKey:@"show-console-on-log"], NO))
|
||||
{
|
||||
[self showJSConsole];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (jsval)javaScriptValueInContext:(JSContext *)context
|
||||
{
|
||||
if (_jsSelf == NULL)
|
||||
{
|
||||
_jsSelf = DebugMonitorToJSConsole(context, self);
|
||||
if (_jsSelf != NULL)
|
||||
{
|
||||
if (!JS_AddNamedRoot(context, &_jsSelf, "debug console"))
|
||||
{
|
||||
_jsSelf = NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (_jsSelf != NULL) return OBJECT_TO_JSVAL(_jsSelf);
|
||||
else return JSVAL_NULL;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation OODebugMonitor (Singleton)
|
||||
|
||||
/* Canonical singleton boilerplate.
|
||||
See Cocoa Fundamentals Guide: Creating a Singleton Instance.
|
||||
See also +sharedDebugMonitor above.
|
||||
|
||||
NOTE: assumes single-threaded access.
|
||||
*/
|
||||
|
||||
+ (id)allocWithZone:(NSZone *)inZone
|
||||
{
|
||||
if (sSingleton == nil)
|
||||
{
|
||||
sSingleton = [super allocWithZone:inZone];
|
||||
return sSingleton;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
- (id)copyWithZone:(NSZone *)inZone
|
||||
{
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (id)retain
|
||||
{
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (OOUInteger)retainCount
|
||||
{
|
||||
return UINT_MAX;
|
||||
}
|
||||
|
||||
|
||||
- (void)release
|
||||
{}
|
||||
|
||||
|
||||
- (id)autorelease
|
||||
{
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif /* OO_EXCLUDE_DEBUG_SUPPORT */
|
|
@ -0,0 +1,59 @@
|
|||
/*
|
||||
|
||||
OODebugSupport.h
|
||||
|
||||
Set up debug support.
|
||||
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2007 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#ifndef OO_EXCLUDE_DEBUG_SUPPORT
|
||||
|
||||
void OOInitDebugSupport(void);
|
||||
|
||||
#else
|
||||
|
||||
#define OOInitDebugSupport() do {} while (0)
|
||||
|
||||
#endif
|
|
@ -0,0 +1,155 @@
|
|||
/*
|
||||
|
||||
OODebugSupport.m
|
||||
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2007 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#ifndef OO_EXCLUDE_DEBUG_SUPPORT
|
||||
|
||||
|
||||
#import "OODebugSupport.h"
|
||||
#import "ResourceManager.h"
|
||||
#import "OOCollectionExtractors.h"
|
||||
#import "OODebugMonitor.h"
|
||||
#import "OODebugTCPConsoleClient.h"
|
||||
|
||||
#if OOLITE_MAC_OS_X
|
||||
static id LoadDebugPlugIn(NSString *path);
|
||||
#else
|
||||
#define LoadDebugPlugIn(path) nil
|
||||
#endif
|
||||
|
||||
|
||||
@interface NSObject (OODebugPlugInController)
|
||||
|
||||
- (id<OODebuggerInterface>) setUpDebugger;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
void OOInitDebugSupport(void)
|
||||
{
|
||||
NSString *debugOXPPath = nil;
|
||||
id plugInController = nil;
|
||||
NSDictionary *debugSettings = nil;
|
||||
NSString *consoleHost = nil;
|
||||
unsigned short consolePort = 0;
|
||||
id<OODebuggerInterface> debugger = nil;
|
||||
|
||||
// Check that the debug OXP is installed. If not, we don't enable debug support.
|
||||
debugOXPPath = [ResourceManager pathForFileNamed:@"DebugOXPLocatorBeacon.magic" inFolder:@"nil"];
|
||||
if (debugOXPPath != nil)
|
||||
{
|
||||
// Load plug-in debugging code on platforms where this is supported.
|
||||
plugInController = LoadDebugPlugIn(debugOXPPath);
|
||||
|
||||
// Load debug settings.
|
||||
debugSettings = [ResourceManager dictionaryFromFilesNamed:@"debugConfig.plist"
|
||||
inFolder:@"Config"
|
||||
mergeMode:MERGE_BASIC
|
||||
cache:NO];
|
||||
|
||||
consoleHost = [debugSettings stringForKey:@"console-host"];
|
||||
consolePort = [debugSettings unsignedShortForKey:@"console-port"];
|
||||
|
||||
// If consoleHost is nil, and the debug plug-in can set up a debugger, use that.
|
||||
if (consoleHost == nil && [plugInController respondsToSelector:@selector(setUpDebugger)])
|
||||
{
|
||||
debugger = [plugInController setUpDebugger];
|
||||
}
|
||||
|
||||
// Otherwise, use TCP debugger connection.
|
||||
if (debugger == nil)
|
||||
{
|
||||
debugger = [[OODebugTCPConsoleClient alloc] initWithAddress:consoleHost
|
||||
port:consolePort];
|
||||
[debugger autorelease];
|
||||
}
|
||||
|
||||
// Set up monitor and register debugger, if any.
|
||||
if (debugger != nil)
|
||||
{
|
||||
[[OODebugMonitor sharedDebugMonitor] setDebugger:debugger];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#if OOLITE_MAC_OS_X
|
||||
|
||||
// Note: it should in principle be possible to use this code to load a plug-in under GNUstep, too.
|
||||
static id LoadDebugPlugIn(NSString *path)
|
||||
{
|
||||
Class principalClass = Nil;
|
||||
NSString *bundlePath = nil;
|
||||
NSBundle *bundle = nil;
|
||||
id debugController = nil;
|
||||
|
||||
bundlePath = [path stringByDeletingLastPathComponent];
|
||||
bundle = [NSBundle bundleWithPath:bundlePath];
|
||||
if ([bundle load])
|
||||
{
|
||||
principalClass = [bundle principalClass];
|
||||
if (principalClass != Nil)
|
||||
{
|
||||
// Instantiate principal class of debug bundle, and let it do whatever it wants.
|
||||
debugController = [[principalClass alloc] init];
|
||||
}
|
||||
else
|
||||
{
|
||||
OOLog(@"debugOXP.load.failed", @"Failed to find principal class of debug bundle.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
OOLog(@"debugOXP.load.failed", @"Failed to load debug OXP plug-in from %@.", bundlePath);
|
||||
}
|
||||
|
||||
return debugController;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#endif /* OO_EXCLUDE_DEBUG_SUPPORT */
|
|
@ -0,0 +1,60 @@
|
|||
/*
|
||||
|
||||
OODebugTCPConsoleClient.h
|
||||
|
||||
|
||||
Oolite Debug OXP
|
||||
|
||||
Copyright (C) 2007 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOCocoa.h"
|
||||
#import "OODebuggerInterface.h"
|
||||
|
||||
@class OODebugMonitor;
|
||||
|
||||
|
||||
typedef enum
|
||||
{
|
||||
kOOTCPClientNotConnected,
|
||||
kOOTCPClientStartedConnectionStage1,
|
||||
kOOTCPClientStartedConnectionStage2,
|
||||
kOOTCPClientConnected,
|
||||
kOOTCPClientConnectionRefused,
|
||||
kOOTCPClientDisconnected
|
||||
} OOTCPClientConnectionStatus;
|
||||
|
||||
|
||||
@interface OODebugTCPConsoleClient: NSObject <OODebuggerInterface>
|
||||
{
|
||||
NSHost *_host;
|
||||
NSOutputStream *_outStream;
|
||||
NSInputStream *_inStream;
|
||||
OOTCPClientConnectionStatus _status;
|
||||
OODebugMonitor *_monitor;
|
||||
struct OOTCPStreamDecoder *_decoder;
|
||||
}
|
||||
|
||||
- (id) initWithAddress:(NSString *)address // Pass nil for localhost
|
||||
port:(uint16_t)port; // Pass 0 for default port
|
||||
|
||||
@end
|
|
@ -0,0 +1,710 @@
|
|||
/*
|
||||
|
||||
OODebugTCPConsoleClient.m
|
||||
|
||||
|
||||
Oolite Debug OXP
|
||||
|
||||
Copyright (C) 2009 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#ifndef OO_EXCLUDE_DEBUG_SUPPORT
|
||||
|
||||
|
||||
#import "OODebugTCPConsoleClient.h"
|
||||
#import "OODebugTCPConsoleProtocol.h"
|
||||
#import "OODebugMonitor.h"
|
||||
#import "OOFunctionAttributes.h"
|
||||
#import "OOLogging.h"
|
||||
#import <stdint.h>
|
||||
|
||||
#if OOLITE_WINDOWS
|
||||
#import <winsock2.h>
|
||||
#else
|
||||
#import <arpa/inet.h> // For htonl
|
||||
#endif
|
||||
|
||||
#import "OOCollectionExtractors.h"
|
||||
#import "OOTCPStreamDecoder.h"
|
||||
|
||||
|
||||
#ifdef OO_LOG_DEBUG_PROTOCOL_PACKETS
|
||||
static void LogSendPacket(NSDictionary *packet);
|
||||
#else
|
||||
#define LogSendPacket(packet) do {} while (0)
|
||||
#endif
|
||||
|
||||
|
||||
static void DecoderPacket(void *cbInfo, OOALStringRef packetType, OOALDictionaryRef packet);
|
||||
static void DecoderError(void *cbInfo, OOALStringRef errorDesc);
|
||||
|
||||
|
||||
OOINLINE BOOL StatusIsSendable(OOTCPClientConnectionStatus status)
|
||||
{
|
||||
return status == kOOTCPClientStartedConnectionStage1 || status == kOOTCPClientStartedConnectionStage2 || status == kOOTCPClientConnected;
|
||||
}
|
||||
|
||||
|
||||
@interface OODebugTCPConsoleClient (OOPrivate)
|
||||
|
||||
- (void) closeConnection;
|
||||
|
||||
- (BOOL) sendBytes:(const void *)bytes count:(size_t)count;
|
||||
- (void) sendDictionary:(NSDictionary *)dictionary;
|
||||
|
||||
- (void) sendPacket:(NSString *)packetType
|
||||
withParameters:(NSDictionary *)parameters;
|
||||
|
||||
- (void) sendPacket:(NSString *)packetType
|
||||
withValue:(id)value
|
||||
forParameter:(NSString *)paramKey;
|
||||
|
||||
- (void) readData;
|
||||
- (void) dispatchPacket:(NSDictionary *)packet ofType:(NSString *)packetType;
|
||||
|
||||
- (void) handleApproveConnectionPacket:(NSDictionary *)packet;
|
||||
- (void) handleRejectConnectionPacket:(NSDictionary *)packet;
|
||||
- (void) handleCloseConnectionPacket:(NSDictionary *)packet;
|
||||
- (void) handleNoteConfigurationChangePacket:(NSDictionary *)packet;
|
||||
- (void) handlePerformCommandPacket:(NSDictionary *)packet;
|
||||
- (void) handleRequestConfigurationValuePacket:(NSDictionary *)packet;
|
||||
- (void) handlePingPacket:(NSDictionary *)packet;
|
||||
- (void) handlePongPacket:(NSDictionary *)packet;
|
||||
|
||||
- (void) disconnectFromServerWithMessage:(NSString *)message;
|
||||
- (void) breakConnectionWithMessage:(NSString *)message;
|
||||
- (void) breakConnectionWithBadStream:(NSStream *)stream;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation OODebugTCPConsoleClient
|
||||
|
||||
- (id) init
|
||||
{
|
||||
return [self initWithAddress:nil port:0];
|
||||
}
|
||||
|
||||
|
||||
- (id) initWithAddress:(NSString *)address port:(uint16_t)port
|
||||
{
|
||||
BOOL OK = NO;
|
||||
NSDictionary *parameters = nil;
|
||||
|
||||
if (address == nil) address = @"127.0.0.1";
|
||||
if (port == 0) port = kOOTCPConsolePort;
|
||||
|
||||
self = [super init];
|
||||
if (self != nil)
|
||||
{
|
||||
_host = [NSHost hostWithName:address];
|
||||
if (_host != nil)
|
||||
{
|
||||
[_host retain];
|
||||
[NSStream getStreamsToHost:_host
|
||||
port:port
|
||||
inputStream:&_inStream
|
||||
outputStream:&_outStream];
|
||||
}
|
||||
|
||||
if (_inStream != nil && _outStream != nil)
|
||||
{
|
||||
[_inStream retain];
|
||||
[_outStream retain];
|
||||
[_inStream setDelegate:self];
|
||||
[_outStream setDelegate:self];
|
||||
[_inStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
|
||||
[_outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
|
||||
[_inStream open];
|
||||
[_outStream open];
|
||||
|
||||
// Need to wait for the streams to reach open status before we can send packets
|
||||
// TODO: Might be neater to use the handleEvent callback to flag this.. - Micha 20090425
|
||||
NSRunLoop * myRunLoop = [NSRunLoop currentRunLoop];
|
||||
NSDate * timeOut = [NSDate dateWithTimeIntervalSinceNow:3]; // Wait up to 3 seconds
|
||||
while( _host != nil && ([_inStream streamStatus] < 2 || [_outStream streamStatus] < 2) &&
|
||||
[myRunLoop runMode:NSDefaultRunLoopMode beforeDate:timeOut] )
|
||||
; // Wait
|
||||
|
||||
_decoder = OOTCPStreamDecoderCreate(DecoderPacket, DecoderError, NULL, self);
|
||||
}
|
||||
|
||||
if (_decoder != NULL)
|
||||
{
|
||||
OK = YES;
|
||||
_status = kOOTCPClientStartedConnectionStage1;
|
||||
|
||||
|
||||
// Attempt to connect
|
||||
parameters = [NSDictionary dictionaryWithObjectsAndKeys:
|
||||
[NSNumber numberWithUnsignedInt:kOOTCPProtocolVersion_1_1_0], kOOTCPProtocolVersion,
|
||||
[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"], kOOTCPOoliteVersion,
|
||||
nil];
|
||||
[self sendPacket:kOOTCPPacket_RequestConnection
|
||||
withParameters:parameters];
|
||||
|
||||
if (_status == kOOTCPClientStartedConnectionStage1) _status = kOOTCPClientStartedConnectionStage2;
|
||||
else OK = NO; // Connection failed.
|
||||
}
|
||||
|
||||
if (!OK)
|
||||
{
|
||||
OOLog(@"debugTCP.connect.failed", @"Failed to connect to debug console at %@:%i.", address, port);
|
||||
[self release];
|
||||
self = nil;
|
||||
}
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (void) dealloc
|
||||
{
|
||||
if (StatusIsSendable(_status))
|
||||
{
|
||||
[self disconnectFromServerWithMessage:@"TCP console bridge unexpectedly released while active."];
|
||||
}
|
||||
if (_monitor)
|
||||
{
|
||||
[_monitor disconnectDebugger:self message:@"TCP console bridge unexpectedly released while active."];
|
||||
}
|
||||
|
||||
|
||||
[self closeConnection];
|
||||
|
||||
OOTCPStreamDecoderDestroy(_decoder);
|
||||
_decoder = NULL;
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
- (BOOL)connectDebugMonitor:(in OODebugMonitor *)debugMonitor
|
||||
errorMessage:(out NSString **)message
|
||||
{
|
||||
if (_status == kOOTCPClientConnectionRefused)
|
||||
{
|
||||
if (message != NULL) *message = @"Connection refused.";
|
||||
return NO;
|
||||
}
|
||||
if (_status == kOOTCPClientDisconnected)
|
||||
{
|
||||
if (message != NULL) *message = @"Cannot reconnect after disconnecting.";
|
||||
return NO;
|
||||
}
|
||||
|
||||
_monitor = debugMonitor;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
- (void)disconnectDebugMonitor:(in OODebugMonitor *)debugMonitor
|
||||
message:(in NSString *)message
|
||||
{
|
||||
[self disconnectFromServerWithMessage:message];
|
||||
_monitor = nil;
|
||||
}
|
||||
|
||||
|
||||
- (oneway void)debugMonitor:(in OODebugMonitor *)debugMonitor
|
||||
jsConsoleOutput:(in NSString *)output
|
||||
colorKey:(in NSString *)colorKey
|
||||
emphasisRange:(in NSRange)emphasisRange
|
||||
{
|
||||
NSMutableDictionary *parameters = nil;
|
||||
NSArray *range = nil;
|
||||
|
||||
parameters = [NSMutableDictionary dictionaryWithCapacity:3];
|
||||
[parameters setObject:output forKey:kOOTCPMessage];
|
||||
[parameters setObject:colorKey ? colorKey : (NSString *)@"general" forKey:kOOTCPColorKey];
|
||||
if (emphasisRange.length != 0)
|
||||
{
|
||||
range = [NSArray arrayWithObjects:
|
||||
[NSNumber numberWithUnsignedInt:emphasisRange.location],
|
||||
[NSNumber numberWithUnsignedInt:emphasisRange.length],
|
||||
nil];
|
||||
[parameters setObject:range forKey:kOOTCPEmphasisRanges];
|
||||
}
|
||||
|
||||
[self sendPacket:kOOTCPPacket_ConsoleOutput
|
||||
withParameters:parameters];
|
||||
}
|
||||
|
||||
|
||||
- (oneway void)debugMonitorClearConsole:(in OODebugMonitor *)debugMonitor
|
||||
{
|
||||
[self sendPacket:kOOTCPPacket_ClearConsole
|
||||
withParameters:nil];
|
||||
}
|
||||
|
||||
|
||||
- (oneway void)debugMonitorShowConsole:(in OODebugMonitor *)debugMonitor;
|
||||
{
|
||||
[self sendPacket:kOOTCPPacket_ShowConsole
|
||||
withParameters:nil];
|
||||
}
|
||||
|
||||
|
||||
- (oneway void)debugMonitor:(in OODebugMonitor *)debugMonitor
|
||||
noteConfiguration:(in NSDictionary *)configuration
|
||||
{
|
||||
[self sendPacket:kOOTCPPacket_NoteConfiguration
|
||||
withValue:configuration
|
||||
forParameter:kOOTCPConfiguration];
|
||||
}
|
||||
|
||||
|
||||
- (oneway void)debugMonitor:(in OODebugMonitor *)debugMonitor
|
||||
noteChangedConfigrationValue:(in id)newValue
|
||||
forKey:(in NSString *)key
|
||||
{
|
||||
if (newValue != nil)
|
||||
{
|
||||
[self sendPacket:kOOTCPPacket_NoteConfiguration
|
||||
withValue:[NSDictionary dictionaryWithObject:newValue forKey:key]
|
||||
forParameter:kOOTCPConfiguration];
|
||||
}
|
||||
else
|
||||
{
|
||||
[self sendPacket:kOOTCPPacket_NoteConfiguration
|
||||
withValue:[NSArray arrayWithObject:key]
|
||||
forParameter:kOOTCPRemovedConfigurationKeys];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
|
||||
{
|
||||
if (_status > kOOTCPClientConnected) return;
|
||||
|
||||
if (stream == _inStream && eventCode == NSStreamEventHasBytesAvailable)
|
||||
{
|
||||
[self readData];
|
||||
}
|
||||
else if (eventCode == NSStreamEventErrorOccurred)
|
||||
{
|
||||
[self breakConnectionWithBadStream:stream];
|
||||
}
|
||||
else if (eventCode == NSStreamEventErrorOccurred)
|
||||
{
|
||||
[self breakConnectionWithMessage:[NSString stringWithFormat:
|
||||
@"Console closed the connection."]];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation OODebugTCPConsoleClient (OOPrivate)
|
||||
|
||||
- (void) closeConnection
|
||||
{
|
||||
[_inStream close];
|
||||
[_inStream setDelegate:nil];
|
||||
[_inStream release];
|
||||
_inStream = nil;
|
||||
|
||||
[_outStream close];
|
||||
[_outStream setDelegate:nil];
|
||||
[_outStream release];
|
||||
_outStream = nil;
|
||||
|
||||
[_host release];
|
||||
_host = nil;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL) sendBytes:(const void *)bytes count:(size_t)count
|
||||
{
|
||||
int written;
|
||||
|
||||
if (bytes == NULL || count == 0) return YES;
|
||||
if (!StatusIsSendable(_status) || _outStream == nil) return NO;
|
||||
|
||||
do
|
||||
{
|
||||
written = [_outStream write:bytes maxLength:count];
|
||||
if (written < 1) return NO;
|
||||
|
||||
count -= written;
|
||||
bytes += written;
|
||||
}
|
||||
while (count > 0);
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
- (void) sendDictionary:(NSDictionary *)dictionary
|
||||
{
|
||||
NSData *data = nil;
|
||||
NSString *errorDesc = nil;
|
||||
size_t count;
|
||||
const uint8_t *bytes = NULL;
|
||||
uint32_t header;
|
||||
|
||||
if (dictionary == nil || !StatusIsSendable(_status)) return;
|
||||
|
||||
data = [NSPropertyListSerialization dataFromPropertyList:dictionary
|
||||
format:NSPropertyListXMLFormat_v1_0
|
||||
errorDescription:&errorDesc];
|
||||
|
||||
if (data == nil)
|
||||
{
|
||||
OOLog(@"debugTCP.conversionFailure", @"Could not convert dictionary to data for transmission to debug console: %@", errorDesc ? errorDesc : (NSString *)@"unknown error.");
|
||||
#if OOLITE_RELEASE_PLIST_ERROR_STRINGS
|
||||
[errorDesc autorelease];
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
|
||||
LogSendPacket(dictionary);
|
||||
|
||||
count = [data length];
|
||||
if (count == 0) return;
|
||||
header = htonl(count);
|
||||
|
||||
bytes = [data bytes];
|
||||
if (![self sendBytes:&header count:sizeof header] || ![self sendBytes:bytes count:count])
|
||||
{
|
||||
[self breakConnectionWithBadStream:_outStream];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void) sendPacket:(NSString *)packetType
|
||||
withParameters:(NSDictionary *)parameters
|
||||
{
|
||||
NSMutableDictionary *dict = nil;
|
||||
|
||||
if (packetType == nil) return;
|
||||
|
||||
if (parameters != nil)
|
||||
{
|
||||
dict = [parameters mutableCopy];
|
||||
[dict setObject:packetType forKey:kOOTCPPacketType];
|
||||
}
|
||||
else
|
||||
{
|
||||
dict = [[NSDictionary alloc] initWithObjectsAndKeys:packetType, kOOTCPPacketType, nil];
|
||||
}
|
||||
|
||||
[self sendDictionary:dict];
|
||||
[dict release];
|
||||
}
|
||||
|
||||
|
||||
- (void) sendPacket:(NSString *)packetType
|
||||
withValue:(id)value
|
||||
forParameter:(NSString *)paramKey
|
||||
{
|
||||
if (packetType == nil) return;
|
||||
if (paramKey == nil) value = nil;
|
||||
|
||||
[self sendDictionary:[NSDictionary dictionaryWithObjectsAndKeys:
|
||||
packetType, kOOTCPPacketType,
|
||||
value, paramKey,
|
||||
nil]];
|
||||
}
|
||||
|
||||
|
||||
- (void) readData
|
||||
{
|
||||
enum { kBufferSize = 16 << 10 };
|
||||
|
||||
uint8_t buffer[kBufferSize];
|
||||
int length;
|
||||
NSData *data;
|
||||
|
||||
length = [_inStream read:buffer maxLength:kBufferSize];
|
||||
while( length > 0 )
|
||||
{
|
||||
/* This test is superfluous after the rewrite to fix Bug#014643
|
||||
* TODO: Put the BadStream test back into the code
|
||||
if (length < 1)
|
||||
{
|
||||
// Under GNUstep, but not OS X (currently), -hasBytesAvailable will return YES when the buffer is in fact empty.
|
||||
if ([_inStream streamStatus] == NSStreamStatusReading) break;
|
||||
|
||||
[self breakConnectionWithBadStream:_inStream];
|
||||
return;
|
||||
}
|
||||
*/
|
||||
|
||||
data = [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:NO];
|
||||
OOTCPStreamDecoderReceiveData(_decoder, data);
|
||||
length = [_inStream read:buffer maxLength:kBufferSize];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void) dispatchPacket:(NSDictionary *)packet ofType:(NSString *)packetType
|
||||
{
|
||||
if (packet == nil || packetType == nil) return;
|
||||
|
||||
#define PACKET_CASE(x) else if ([packetType isEqualToString:kOOTCPPacket_##x]) { [self handle##x##Packet:packet]; }
|
||||
|
||||
if (0) {}
|
||||
PACKET_CASE(ApproveConnection)
|
||||
PACKET_CASE(RejectConnection)
|
||||
PACKET_CASE(CloseConnection)
|
||||
PACKET_CASE(NoteConfigurationChange)
|
||||
PACKET_CASE(PerformCommand)
|
||||
PACKET_CASE(RequestConfigurationValue)
|
||||
PACKET_CASE(Ping)
|
||||
PACKET_CASE(Pong)
|
||||
else
|
||||
{
|
||||
OOLog(@"debugTCP.protocolError.unknownPacketType", @"Unhandled packet type %@.", packetType);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void) handleApproveConnectionPacket:(NSDictionary *)packet
|
||||
{
|
||||
NSMutableString *connectedMessage = nil;
|
||||
NSString *consoleIdentity = nil;
|
||||
NSString *hostName = nil;
|
||||
|
||||
if (_status == kOOTCPClientStartedConnectionStage2)
|
||||
{
|
||||
_status = kOOTCPClientConnected;
|
||||
|
||||
// Build "Connected..." message with two optional parts, console identity and host name.
|
||||
connectedMessage = [NSMutableString stringWithString:@"Connected to external debug console"];
|
||||
|
||||
consoleIdentity = [packet stringForKey:kOOTCPConsoleIdentity];
|
||||
if (consoleIdentity != nil) [connectedMessage appendFormat:@" \"%@\"", consoleIdentity];
|
||||
|
||||
hostName = [_host name];
|
||||
if ([hostName length] != 0 &&
|
||||
![hostName isEqual:@"localhost"] &&
|
||||
![hostName isEqual:@"127.0.0.1"] &&
|
||||
![hostName isEqual:@"::1"])
|
||||
{
|
||||
[connectedMessage appendFormat:@" at %@", hostName];
|
||||
}
|
||||
|
||||
OOLog(@"debugTCP.connected", @"%@.", connectedMessage);
|
||||
}
|
||||
else
|
||||
{
|
||||
OOLog(@"debugTCP.protocolError.outOfOrder", @"Got %@ packet from debug console in wrong context.", kOOTCPPacket_ApproveConnection);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void) handleRejectConnectionPacket:(NSDictionary *)packet
|
||||
{
|
||||
NSString *message = nil;
|
||||
|
||||
if (_status == kOOTCPClientStartedConnectionStage2)
|
||||
{
|
||||
_status = kOOTCPClientConnectionRefused;
|
||||
}
|
||||
else
|
||||
{
|
||||
OOLog(@"debugTCP.protocolError.outOfOrder", @"Got %@ packet from debug console in wrong context.", kOOTCPPacket_RejectConnection);
|
||||
}
|
||||
|
||||
message = [packet stringForKey:kOOTCPMessage];
|
||||
if (message == nil) message = @"Console refused connection.";
|
||||
[self breakConnectionWithMessage:message];
|
||||
}
|
||||
|
||||
|
||||
- (void) handleCloseConnectionPacket:(NSDictionary *)packet
|
||||
{
|
||||
NSString *message = nil;
|
||||
|
||||
if (!StatusIsSendable(_status))
|
||||
{
|
||||
OOLog(@"debugTCP.protocolError.outOfOrder", @"Got %@ packet from debug console in wrong context.", kOOTCPPacket_CloseConnection);
|
||||
}
|
||||
message = [packet stringForKey:kOOTCPMessage];
|
||||
if (message == nil) message = @"Console closed connection.";
|
||||
[self breakConnectionWithMessage:message];
|
||||
}
|
||||
|
||||
|
||||
- (void) handleNoteConfigurationChangePacket:(NSDictionary *)packet
|
||||
{
|
||||
NSDictionary *configuration = nil;
|
||||
NSArray *removed = nil;
|
||||
NSEnumerator *keyEnum = nil;
|
||||
NSString *key = nil;
|
||||
id value = nil;
|
||||
|
||||
if (_monitor == nil) return;
|
||||
|
||||
configuration = [packet dictionaryForKey:kOOTCPConfiguration];
|
||||
if (configuration != nil)
|
||||
{
|
||||
for (keyEnum = [configuration keyEnumerator]; (key = [keyEnum nextObject]); )
|
||||
{
|
||||
value = [configuration objectForKey:key];
|
||||
[_monitor setConfigurationValue:value forKey:key];
|
||||
}
|
||||
}
|
||||
|
||||
removed = [configuration arrayForKey:kOOTCPRemovedConfigurationKeys];
|
||||
for (keyEnum = [removed objectEnumerator]; (key = [keyEnum nextObject]); )
|
||||
{
|
||||
[_monitor setConfigurationValue:nil forKey:key];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void) handlePerformCommandPacket:(NSDictionary *)packet
|
||||
{
|
||||
NSString *message = nil;
|
||||
|
||||
message = [packet stringForKey:kOOTCPMessage];
|
||||
if (message != nil) [_monitor performJSConsoleCommand:message];
|
||||
}
|
||||
|
||||
|
||||
- (void) handleRequestConfigurationValuePacket:(NSDictionary *)packet
|
||||
{
|
||||
NSString *key = nil;
|
||||
id value = nil;
|
||||
|
||||
key = [packet stringForKey:kOOTCPConfigurationKey];
|
||||
if (key != nil)
|
||||
{
|
||||
value = [_monitor configurationValueForKey:key];
|
||||
[self debugMonitor:_monitor
|
||||
noteChangedConfigrationValue:value
|
||||
forKey:key];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- (void) handlePingPacket:(NSDictionary *)packet
|
||||
{
|
||||
id message = nil;
|
||||
|
||||
message = [packet objectForKey:kOOTCPMessage];
|
||||
[self sendPacket:kOOTCPPacket_Pong
|
||||
withValue:message
|
||||
forParameter:kOOTCPMessage];
|
||||
}
|
||||
|
||||
|
||||
- (void) handlePongPacket:(NSDictionary *)packet
|
||||
{
|
||||
// Do nothing; we don't currently send pings.
|
||||
}
|
||||
|
||||
|
||||
- (void) disconnectFromServerWithMessage:(NSString *)message
|
||||
{
|
||||
if (StatusIsSendable(_status))
|
||||
{
|
||||
[self sendPacket:kOOTCPPacket_CloseConnection
|
||||
withValue:message
|
||||
forParameter:kOOTCPMessage];
|
||||
}
|
||||
[self closeConnection];
|
||||
|
||||
_status = kOOTCPClientDisconnected;
|
||||
}
|
||||
|
||||
|
||||
- (void) breakConnectionWithMessage:(NSString *)message
|
||||
{
|
||||
[self closeConnection];
|
||||
|
||||
if (_status != kOOTCPClientConnectionRefused) _status = kOOTCPClientDisconnected;
|
||||
|
||||
if ([message length] > 0)
|
||||
{
|
||||
OOLog(@"debugTCP.disconnect", @"Debug console disconnected with message %@", message);
|
||||
}
|
||||
else
|
||||
{
|
||||
OOLog(@"debugTCP.disconnect", @"Debug console disconnected.");
|
||||
}
|
||||
|
||||
#if 0
|
||||
// Disconnecting causes crashiness for reasons I don't understand, and isn't very important anyway.
|
||||
[_monitor disconnectDebugger:self message:message];
|
||||
_monitor = nil;
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
- (void) breakConnectionWithBadStream:(NSStream *)stream
|
||||
{
|
||||
NSString *errorDesc = nil;
|
||||
NSError *error = nil;
|
||||
|
||||
error = [stream streamError];
|
||||
errorDesc = [error localizedDescription];
|
||||
if (errorDesc == nil) errorDesc = [error description];
|
||||
if (errorDesc == nil) errorDesc = @"unknown error.";
|
||||
[self breakConnectionWithMessage:[NSString stringWithFormat:
|
||||
@"Lost connection to remote debug console. outStream status: %i, inStream status: %i. Stream error: %@",
|
||||
[_outStream streamStatus], [_inStream streamStatus], errorDesc]];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
static void DecoderPacket(void *cbInfo, OOALStringRef packetType, OOALDictionaryRef packet)
|
||||
{
|
||||
[(OODebugTCPConsoleClient *)cbInfo dispatchPacket:packet ofType:packetType];
|
||||
}
|
||||
|
||||
|
||||
static void DecoderError(void *cbInfo, OOALStringRef errorDesc)
|
||||
{
|
||||
[(OODebugTCPConsoleClient *)cbInfo breakConnectionWithMessage:errorDesc];
|
||||
}
|
||||
|
||||
|
||||
#ifdef OO_LOG_DEBUG_PROTOCOL_PACKETS
|
||||
void LogOOTCPStreamDecoderPacket(NSDictionary *packet)
|
||||
{
|
||||
NSData *data = nil;
|
||||
NSString *xml = nil;
|
||||
|
||||
data = [NSPropertyListSerialization dataFromPropertyList:packet format:NSPropertyListXMLFormat_v1_0 errorDescription:NULL];
|
||||
xml = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
||||
OOLog(@"debugTCP.receive", @"Received packet:\n%@", xml);
|
||||
}
|
||||
|
||||
|
||||
static void LogSendPacket(NSDictionary *packet)
|
||||
{
|
||||
NSData *data = nil;
|
||||
NSString *xml = nil;
|
||||
|
||||
data = [NSPropertyListSerialization dataFromPropertyList:packet format:NSPropertyListXMLFormat_v1_0 errorDescription:NULL];
|
||||
xml = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
||||
OOLog(@"debugTCP.send", @"Sent packet:\n%@", xml);
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* OO_EXCLUDE_DEBUG_SUPPORT */
|
|
@ -0,0 +1,331 @@
|
|||
/*
|
||||
|
||||
OODebugTCPConsoleProtocol.h
|
||||
|
||||
Definitions used in Oolite remote debug console protocol.
|
||||
|
||||
|
||||
Oolite Debug OXP
|
||||
|
||||
Copyright (C) 2007 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
|
||||
#ifndef OOALSTR
|
||||
#ifdef __OBJC__
|
||||
#import <Foundation/Foundation.h>
|
||||
#define OOALSTR(x) @""x
|
||||
#else // C
|
||||
#include <CoreFoundation/CoreFoundation.h>
|
||||
#define OOALSTR(x) CFSTR(x)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
enum
|
||||
{
|
||||
kOOTCPConsolePort = 0x002173 /* = 8563 */
|
||||
};
|
||||
|
||||
|
||||
/* PROTOCOL OVERVIEW
|
||||
|
||||
The basic unit of the protocol is property lists. Property lists originate
|
||||
with OpenStep and are thus defined in Cocoa and GNUstep, but they're also
|
||||
implemented in CoreFoundation (Mac OS X) and CFLite (cross-platform), with
|
||||
a C interface.
|
||||
|
||||
The protocol uses a TCP stream in each direction. Each stream consists of
|
||||
a series of property lists in the Apple XML encoding. Each property list
|
||||
is framed in the simplest possible way: it is preceeded by an unsigned
|
||||
32-bit length, in network-endian order. Each length + property list
|
||||
combination is referred to as a packet.
|
||||
|
||||
Every packet's property list must have a dictionary as its root element.
|
||||
The dictionary must contain a kOOTCPConsolePacketType key, whose value
|
||||
determines the meaning of the rest of the dictionary.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
/* *** Packet types *** */
|
||||
/* kOOTCPacket_RequestConnection
|
||||
client --> server
|
||||
Message sent from client (Oolite) to server (console) to request a cosole
|
||||
connection.
|
||||
|
||||
Required values:
|
||||
kOOTCPProtocolVersion
|
||||
kOOTCPOoliteVersion
|
||||
Expected responses:
|
||||
kOOTCPacket_ApproveConnection
|
||||
OR
|
||||
kOOTCPacket_RejectConnection
|
||||
*/
|
||||
#define kOOTCPPacket_RequestConnection OOALSTR("Request Connection")
|
||||
|
||||
/* kOOTCPPacket_ApproveConnection
|
||||
client <-- server
|
||||
Message sent in response to kOOTCPacket_RequestConnection if connection is
|
||||
established successfully.
|
||||
|
||||
Optional values:
|
||||
kOOTCPConsoleIdentity
|
||||
*/
|
||||
#define kOOTCPPacket_ApproveConnection OOALSTR("Approve Connection")
|
||||
|
||||
/* kOOTCPPacket_RejectConnection
|
||||
client <-- server
|
||||
Message sent in response to kOOTCPacket_RequestConnection if connection is
|
||||
not established successfully. After this message is sent, the connection
|
||||
is closed with no further traffic.
|
||||
|
||||
Optional values:
|
||||
kOOTCPMessage
|
||||
Expected responses:
|
||||
None permitted.
|
||||
*/
|
||||
#define kOOTCPPacket_RejectConnection OOALSTR("Reject Connection")
|
||||
|
||||
/* kOOTCPPacket_CloseConnection
|
||||
client <-> server
|
||||
Message sent by either party to cleanly close connection.
|
||||
|
||||
Optional values:
|
||||
kOOTCPMessage
|
||||
Expected responses:
|
||||
None permitted.
|
||||
*/
|
||||
#define kOOTCPPacket_CloseConnection OOALSTR("Close Connection")
|
||||
|
||||
/* kOOTCPPacket_ConsoleOutput
|
||||
client --> server
|
||||
Message sent by Oolite to print text to console.
|
||||
|
||||
Required values:
|
||||
kOOTCPMessage
|
||||
kOOTCPColorKey
|
||||
Optional values:
|
||||
kOOTCPEmphasisRanges
|
||||
*/
|
||||
#define kOOTCPPacket_ConsoleOutput OOALSTR("Console Output")
|
||||
|
||||
/* kOOTCPPacket_ClearConsole
|
||||
client --> server
|
||||
Message sent by Oolite to clear console output.
|
||||
*/
|
||||
#define kOOTCPPacket_ClearConsole OOALSTR("Clear Console")
|
||||
|
||||
/* kOOTCPPacket_ShowConsole
|
||||
client --> server
|
||||
Message sent by Oolite to request that the cosole makes itself visible and
|
||||
active.
|
||||
*/
|
||||
#define kOOTCPPacket_ShowConsole OOALSTR("Show Console")
|
||||
|
||||
/* kOOTCPPacket_NoteConfiguration
|
||||
client --> server
|
||||
Message sent by Oolite to appraise the console of the contents of the
|
||||
configuration dictionary. Sent once after the initial handshake.
|
||||
|
||||
Required values:
|
||||
kOOTCPConfiguration
|
||||
*/
|
||||
#define kOOTCPPacket_NoteConfiguration OOALSTR("Note Configuration")
|
||||
|
||||
/* kOOTCPPacket_NoteConfigurationChange
|
||||
client <-> server
|
||||
Message sent by Oolite when the contents of the configuration dictionary
|
||||
change, or by console to change the configuration dictionary (in which
|
||||
case a confirmation will be returned in form of one or more
|
||||
kOOTCPPacket_NoteConfigurationChange messages). For this message,
|
||||
kOOTCPConfiguration is a delta -- keys not contained in it are not to be
|
||||
removed, they are simply unchanged. Deletions are handled with
|
||||
kOOTCPRemovedConfigurationKeys.
|
||||
|
||||
This key is also sent in response to a kOOTCPPacket_RequestConfigurationValue
|
||||
message, even if no configuration value has changed.
|
||||
|
||||
Required values (at least one of):
|
||||
kOOTCPConfiguration
|
||||
kOOTCPRemovedConfigurationKeys
|
||||
*/
|
||||
#define kOOTCPPacket_NoteConfigurationChange OOALSTR("Note Configuration Change")
|
||||
|
||||
/* kOOTCPPacket_PerformCommand
|
||||
client <-- server
|
||||
Message sent by console to issue a command.
|
||||
|
||||
Required values:
|
||||
kOOTCPMessage
|
||||
*/
|
||||
#define kOOTCPPacket_PerformCommand OOALSTR("Perform Command")
|
||||
|
||||
/* kOOTCPPacket_RequestConfigurationValue
|
||||
client <-- server
|
||||
Message sent by console to request a configuration value. This will result
|
||||
in a kOOTCPPacket_NoteConfigurationChange message being sent. If the value
|
||||
is nil, the response will contain a kOOTCPRemovedConfigurationKeys value.
|
||||
|
||||
Required values:
|
||||
kOOTCPConfigurationKey
|
||||
Expected response:
|
||||
kOOTCPPacket_NoteConfigurationChange
|
||||
*/
|
||||
#define kOOTCPPacket_RequestConfigurationValue OOALSTR("Request Configuration Value")
|
||||
|
||||
/* kOOTCPPacket_Ping
|
||||
client <-> server
|
||||
Must be responded to with a kOOTCPPacket_Pong message containing the same
|
||||
kOOTCPMessage, if any.
|
||||
|
||||
Optional values:
|
||||
kOOTCPMessage
|
||||
Expected response:
|
||||
kOOTCPPacket_Pong
|
||||
*/
|
||||
#define kOOTCPPacket_Ping OOALSTR("Ping")
|
||||
|
||||
/* kOOTCPPacket_Pong
|
||||
client <-> server
|
||||
Must be sent in response to kOOTCPPacket_Ping. If the kOOTCPPacket_Ping
|
||||
packet had a kOOTCPMessage, the same kOOTCPMessage value must be attached
|
||||
to the kOOTCPPacket_Pong.
|
||||
|
||||
Optional values:
|
||||
kOOTCPMessage (required if included in ping)
|
||||
*/
|
||||
#define kOOTCPPacket_Pong OOALSTR("Pong")
|
||||
|
||||
|
||||
|
||||
|
||||
/* *** Value keys *** */
|
||||
/* kOOTCPPacketType
|
||||
String indicating packet type. See above under
|
||||
|
||||
See constants below under *** Packet types ***.
|
||||
*/
|
||||
#define kOOTCPPacketType OOALSTR("packet type")
|
||||
|
||||
/* kOOTCPProtocolVersion
|
||||
Number indicating version of debug console TCP protocol. Sent with
|
||||
kOOTCPPacket_RequestConnection.
|
||||
|
||||
See constants below under *** Version constants ***.
|
||||
*/
|
||||
#define kOOTCPProtocolVersion OOALSTR("protocol version")
|
||||
|
||||
/* kOOTCPOoliteVersion
|
||||
String indicating the version of Oolite, for example "1.70" or "1.71.1 b2".
|
||||
Consists of two or more integers separated by .s, optionally followed by
|
||||
a space and additional information in unspecified format. Sent with
|
||||
kOOTCPPacket_RequestConnection.
|
||||
*/
|
||||
#define kOOTCPOoliteVersion OOALSTR("Oolite version")
|
||||
|
||||
/* kOOTCPMessage
|
||||
Textual message sent with various packet types. No specified format.
|
||||
*/
|
||||
#define kOOTCPMessage OOALSTR("message")
|
||||
|
||||
/* kOOTCPConsoleIdentity
|
||||
String identifying console software. No specified format.
|
||||
*/
|
||||
#define kOOTCPConsoleIdentity OOALSTR("console identity")
|
||||
|
||||
/* kOOTCPColorKey
|
||||
String identifying colour/formatting to be used. The configuration
|
||||
dictionary contains keys of the form foo-foreground-color and
|
||||
foo-background-color to be used. If no colour is specified for the
|
||||
specified key, the key "general" should be tried. The colour values are
|
||||
specified as arrays of three numbers in the range 0-1, specifying RGB
|
||||
colours.
|
||||
|
||||
For example, if the configuration key contains:
|
||||
{
|
||||
general-background-color = (1,1,1);
|
||||
general-foreground-color = (0,0,0);
|
||||
foo-background-color = (1,0,0);
|
||||
}
|
||||
the colour key "foo" maps to the background colour (1,0,0) and the
|
||||
foreground color (0,0,0). Sent with kOOTCPPacket_ConsoleOutput.
|
||||
*/
|
||||
#define kOOTCPColorKey OOALSTR("color key")
|
||||
|
||||
/* kOOTCPEmphasisRanges
|
||||
An array containing an even number of integers. Each pair of integers
|
||||
specifies a range (in the form offset, length) which should be emphasized.
|
||||
Sent with kOOTCPPacket_ConsoleOutput.
|
||||
*/
|
||||
#define kOOTCPEmphasisRanges OOALSTR("emphasis ranges")
|
||||
|
||||
/* kOOTCPConfiguration
|
||||
A dictionary of key/value pairs to add/set in the configuration
|
||||
dictionary. Sent with kOOTCPPacket_NoteConfiguration and
|
||||
kOOTCPPacket_NoteConfiguration.
|
||||
*/
|
||||
#define kOOTCPConfiguration OOALSTR("configuration")
|
||||
|
||||
/* kOOTCPConfiguration
|
||||
An array of keys to remove from the configuration dictionary. Sent with
|
||||
kOOTCPPacket_NoteConfiguration.
|
||||
*/
|
||||
#define kOOTCPRemovedConfigurationKeys OOALSTR("removed configuration keys")
|
||||
|
||||
/* kOOTCPConfigurationKey
|
||||
A string specifying the configuration key for which a value is requested.
|
||||
Sent with kOOTCPPacket_RequestConfigurationValue.
|
||||
*/
|
||||
#define kOOTCPConfigurationKey OOALSTR("configuration key")
|
||||
|
||||
|
||||
|
||||
/* *** Version constants *** */
|
||||
/* Version constants have three components: format, major and minor. The
|
||||
format version will change if the framing mechanism is changed, that is,
|
||||
if we switch from the property-list basted protocol in use. The major
|
||||
version will be changed to indicate compatibility-breaking changes. The
|
||||
minor version will be changed when new non-critical packets are added.
|
||||
*/
|
||||
|
||||
#define OOTCP_ENCODE_VERSION(f, mj, mi) \
|
||||
((((f) << 16) & kOOTCPProtocolVersionFormatMask) | \
|
||||
(((f) << 8) & kOOTCPProtocolVersionMajorMask) | \
|
||||
((mi) & kOOTCPProtocolVersionMinorMask))
|
||||
|
||||
#define OOTCP_VERSION_FORMAT(v) (((v) & kOOTCPProtocolVersionFormatMask) >> 16)
|
||||
#define OOTCP_VERSION_MAJOR(v) (((v) & kOOTCPProtocolVersionMajorMask) >> 8)
|
||||
#define OOTCP_VERSION_MINOR(v) ((v) & kOOTCPProtocolVersionMinorMask)
|
||||
|
||||
enum
|
||||
{
|
||||
kOOTCPProtocolVersionFormatMask = 0x00FF0000,
|
||||
kOOTCPProtocolVersionMajorMask = 0x0000FF00,
|
||||
kOOTCPProtocolVersionMinorMask = 0x000000FF,
|
||||
|
||||
kOOTCPProtocolVersionPListFormat = 1,
|
||||
|
||||
// 1:1.0, first version.
|
||||
kOOTCPProtocolVersion_1_1_0 = OOTCP_ENCODE_VERSION(kOOTCPProtocolVersionPListFormat, 1, 0)
|
||||
};
|
|
@ -0,0 +1,70 @@
|
|||
/*
|
||||
|
||||
OODebuggerInterface.h
|
||||
|
||||
Protocols for communication between OODebugMonitor and OODebuggerInterface.
|
||||
|
||||
|
||||
Oolite Debug OXP
|
||||
|
||||
Copyright (C) 2007 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
|
||||
@class OODebugMonitor;
|
||||
|
||||
// Interface for debugger.
|
||||
|
||||
@protocol OODebuggerInterface <NSObject>
|
||||
|
||||
// Sent to establish connection.
|
||||
- (BOOL)connectDebugMonitor:(in OODebugMonitor *)debugMonitor
|
||||
errorMessage:(out NSString **)message;
|
||||
|
||||
// Sent to close connection.
|
||||
- (void)disconnectDebugMonitor:(in OODebugMonitor *)debugMonitor
|
||||
message:(in NSString *)message;
|
||||
|
||||
// Sent to print to the JavaScript console.
|
||||
// colorKey is intended to be used to look up a foreground/background colour pair
|
||||
// in the configuration. EmphasisRange is to specify a bold section of text.
|
||||
- (oneway void)debugMonitor:(in OODebugMonitor *)debugMonitor
|
||||
jsConsoleOutput:(in NSString *)output
|
||||
colorKey:(in NSString *)colorKey
|
||||
emphasisRange:(in NSRange)emphasisRange;
|
||||
|
||||
// Sent to clear the JavaScript console.
|
||||
- (oneway void)debugMonitorClearConsole:(in OODebugMonitor *)debugMonitor;
|
||||
|
||||
// Sent to show the console, for instance in response to a warning or error message.
|
||||
- (oneway void)debugMonitorShowConsole:(in OODebugMonitor *)debugMonitor;
|
||||
|
||||
// Sent once when the debugger is connected.
|
||||
- (oneway void)debugMonitor:(in OODebugMonitor *)debugMonitor
|
||||
noteConfiguration:(in NSDictionary *)configuration;
|
||||
|
||||
// Sent when configuration changes. newValue may be nil.
|
||||
- (oneway void)debugMonitor:(in OODebugMonitor *)debugMonitor
|
||||
noteChangedConfigrationValue:(in id)newValue
|
||||
forKey:(in NSString *)key;
|
||||
|
||||
@end
|
|
@ -0,0 +1,38 @@
|
|||
/*
|
||||
|
||||
OOJSConsole.h
|
||||
|
||||
JavaScript object representing the JavaScript console.
|
||||
|
||||
|
||||
Oolite Debug OXP
|
||||
|
||||
Copyright (C) 2007 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <jsapi.h>
|
||||
|
||||
@class OODebugMonitor;
|
||||
|
||||
|
||||
JSObject *DebugMonitorToJSConsole(JSContext *context, OODebugMonitor *monitor);
|
|
@ -0,0 +1,487 @@
|
|||
/*
|
||||
|
||||
OOJSConsole.m
|
||||
|
||||
|
||||
Oolite Debug OXP
|
||||
|
||||
Copyright (C) 2007 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#ifndef OO_EXCLUDE_DEBUG_SUPPORT
|
||||
|
||||
#import "OOJSConsole.h"
|
||||
#import "OODebugMonitor.h"
|
||||
#import <stdint.h>
|
||||
|
||||
#import "OOJavaScriptEngine.h"
|
||||
#import "OOJSScript.h"
|
||||
#import "OOJSVector.h"
|
||||
#import "OOJSEntity.h"
|
||||
#import "OOJSCall.h"
|
||||
#import "OOLoggingExtended.h"
|
||||
|
||||
|
||||
@interface Entity (OODebugInspector)
|
||||
|
||||
// Method added by inspector in Debug OXP under OS X only.
|
||||
- (void) inspect;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
static JSObject *sConsolePrototype = NULL;
|
||||
static JSObject *sConsoleSettingsPrototype = NULL;
|
||||
|
||||
|
||||
static JSBool ConsoleGetProperty(JSContext *context, JSObject *this, jsval name, jsval *outValue);
|
||||
static JSBool ConsoleSetProperty(JSContext *context, JSObject *this, jsval name, jsval *value);
|
||||
static void ConsoleFinalize(JSContext *context, JSObject *this);
|
||||
|
||||
// Methods
|
||||
static JSBool ConsoleConsoleMessage(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult);
|
||||
static JSBool ConsoleClearConsole(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult);
|
||||
static JSBool ConsoleScriptStack(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult);
|
||||
static JSBool ConsoleInspectEntity(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult);
|
||||
static JSBool ConsoleCallObjCMethod(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult);
|
||||
static JSBool ConsoleIsExecutableJavaScript(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult);
|
||||
static JSBool ConsoleDisplayMessagesInClass(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult);
|
||||
static JSBool ConsoleSetDisplayMessagesInClass(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult);
|
||||
|
||||
static JSBool ConsoleSettingsDeleteProperty(JSContext *context, JSObject *this, jsval name, jsval *outValue);
|
||||
static JSBool ConsoleSettingsGetProperty(JSContext *context, JSObject *this, jsval name, jsval *outValue);
|
||||
static JSBool ConsoleSettingsSetProperty(JSContext *context, JSObject *this, jsval name, jsval *value);
|
||||
|
||||
|
||||
static JSClass sConsoleClass =
|
||||
{
|
||||
"Console",
|
||||
JSCLASS_HAS_PRIVATE | JSCLASS_IS_ANONYMOUS,
|
||||
|
||||
JS_PropertyStub, // addProperty
|
||||
JS_PropertyStub, // delProperty
|
||||
ConsoleGetProperty, // getProperty
|
||||
ConsoleSetProperty, // setProperty
|
||||
JS_EnumerateStub, // enumerate
|
||||
JS_ResolveStub, // resolve
|
||||
JS_ConvertStub, // convert
|
||||
ConsoleFinalize, // finalize
|
||||
JSCLASS_NO_OPTIONAL_MEMBERS
|
||||
};
|
||||
|
||||
|
||||
enum
|
||||
{
|
||||
// Property IDs
|
||||
kConsole_debugFlags // debug flags, integer, read/write
|
||||
};
|
||||
|
||||
|
||||
static JSPropertySpec sConsoleProperties[] =
|
||||
{
|
||||
// JS name ID flags
|
||||
{ "debugFlags", kConsole_debugFlags, JSPROP_PERMANENT | JSPROP_ENUMERATE },
|
||||
{ 0 }
|
||||
};
|
||||
|
||||
|
||||
static JSFunctionSpec sConsoleMethods[] =
|
||||
{
|
||||
// JS name Function min args
|
||||
{ "consoleMessage", ConsoleConsoleMessage, 2 },
|
||||
{ "clearConsole", ConsoleClearConsole, 0 },
|
||||
{ "scriptStack", ConsoleScriptStack, 0 },
|
||||
{ "inspectEntity", ConsoleInspectEntity, 1 },
|
||||
{ "__callObjCMethod", ConsoleCallObjCMethod, 1 },
|
||||
{ "isExecutableJavaScript", ConsoleIsExecutableJavaScript, 2 },
|
||||
{ "displayMessagesInClass", ConsoleDisplayMessagesInClass, 1 },
|
||||
{ "setDisplayMessagesInClass", ConsoleSetDisplayMessagesInClass, 2 },
|
||||
{ 0 }
|
||||
};
|
||||
|
||||
|
||||
static JSClass sConsoleSettingsClass =
|
||||
{
|
||||
"ConsoleSettings",
|
||||
JSCLASS_HAS_PRIVATE,
|
||||
|
||||
JS_PropertyStub, // addProperty
|
||||
ConsoleSettingsDeleteProperty, // delProperty
|
||||
ConsoleSettingsGetProperty, // getProperty
|
||||
ConsoleSettingsSetProperty, // setProperty
|
||||
JS_EnumerateStub, // enumerate. FIXME: this should work.
|
||||
JS_ResolveStub, // resolve
|
||||
JS_ConvertStub, // convert
|
||||
ConsoleFinalize, // finalize (same as Console)
|
||||
JSCLASS_NO_OPTIONAL_MEMBERS
|
||||
};
|
||||
|
||||
|
||||
static void InitOOJSConsole(JSContext *context, JSObject *global)
|
||||
{
|
||||
sConsolePrototype = JS_InitClass(context, global, NULL, &sConsoleClass, NULL, 0, sConsoleProperties, sConsoleMethods, NULL, NULL);
|
||||
JSRegisterObjectConverter(&sConsoleClass, JSBasicPrivateObjectConverter);
|
||||
|
||||
sConsoleSettingsPrototype = JS_InitClass(context, global, NULL, &sConsoleSettingsClass, NULL, 0, NULL, NULL, NULL, NULL);
|
||||
JSRegisterObjectConverter(&sConsoleSettingsClass, JSBasicPrivateObjectConverter);
|
||||
}
|
||||
|
||||
|
||||
JSObject *DebugMonitorToJSConsole(JSContext *context, OODebugMonitor *monitor)
|
||||
{
|
||||
OOJavaScriptEngine *engine = nil;
|
||||
JSObject *object = NULL;
|
||||
JSObject *settingsObject = NULL;
|
||||
jsval value;
|
||||
|
||||
engine = [OOJavaScriptEngine sharedEngine];
|
||||
|
||||
if (sConsolePrototype == NULL)
|
||||
{
|
||||
InitOOJSConsole(context, [engine globalObject]);
|
||||
}
|
||||
|
||||
// Create Console object
|
||||
object = JS_NewObject(context, &sConsoleClass, sConsolePrototype, NULL);
|
||||
if (object != NULL)
|
||||
{
|
||||
if (!JS_SetPrivate(context, object, [monitor weakRetain])) object = NULL;
|
||||
}
|
||||
|
||||
if (object != NULL)
|
||||
{
|
||||
// Create ConsoleSettings object
|
||||
settingsObject = JS_NewObject(context, &sConsoleSettingsClass, sConsoleSettingsPrototype, NULL);
|
||||
if (settingsObject != NULL)
|
||||
{
|
||||
if (!JS_SetPrivate(context, settingsObject, [monitor weakRetain])) settingsObject = NULL;
|
||||
}
|
||||
if (settingsObject != NULL)
|
||||
{
|
||||
value = OBJECT_TO_JSVAL(settingsObject);
|
||||
if (!JS_SetProperty(context, object, "settings", &value))
|
||||
{
|
||||
settingsObject = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
if (settingsObject == NULL) object = NULL;
|
||||
}
|
||||
|
||||
return object;
|
||||
}
|
||||
|
||||
|
||||
static JSBool ConsoleGetProperty(JSContext *context, JSObject *this, jsval name, jsval *outValue)
|
||||
{
|
||||
if (!JSVAL_IS_INT(name)) return YES;
|
||||
|
||||
switch (JSVAL_TO_INT(name))
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
case kConsole_debugFlags:
|
||||
*outValue = INT_TO_JSVAL(gDebugFlags);
|
||||
break;
|
||||
#endif
|
||||
default:
|
||||
OOReportJSBadPropertySelector(context, @"Console", JSVAL_TO_INT(name));
|
||||
return NO;
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
static JSBool ConsoleSetProperty(JSContext *context, JSObject *this, jsval name, jsval *value)
|
||||
{
|
||||
int32 iValue;
|
||||
|
||||
if (!JSVAL_IS_INT(name)) return YES;
|
||||
|
||||
switch (JSVAL_TO_INT(name))
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
case kConsole_debugFlags:
|
||||
if (JS_ValueToInt32(context, *value, &iValue))
|
||||
{
|
||||
gDebugFlags = iValue;
|
||||
}
|
||||
break;
|
||||
#endif
|
||||
default:
|
||||
OOReportJSBadPropertySelector(context, @"Console", JSVAL_TO_INT(name));
|
||||
return NO;
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
static void ConsoleFinalize(JSContext *context, JSObject *this)
|
||||
{
|
||||
[(id)JS_GetPrivate(context, this) release];
|
||||
JS_SetPrivate(context, this, nil);
|
||||
}
|
||||
|
||||
|
||||
static JSBool ConsoleSettingsDeleteProperty(JSContext *context, JSObject *this, jsval name, jsval *outValue)
|
||||
{
|
||||
NSString *key = nil;
|
||||
id monitor = nil;
|
||||
|
||||
if (!JSVAL_IS_STRING(name)) return NO;
|
||||
|
||||
key = [NSString stringWithJavaScriptValue:name inContext:context];
|
||||
|
||||
monitor = JSObjectToObject(context, this);
|
||||
if (![monitor isKindOfClass:[OODebugMonitor class]])
|
||||
{
|
||||
OOReportJSError(context, @"Expected OODebugMonitor, got %@ in %s. This is an internal error, please report it.", [monitor class], __PRETTY_FUNCTION__);
|
||||
return NO;
|
||||
}
|
||||
|
||||
[monitor setConfigurationValue:nil forKey:key];
|
||||
*outValue = JSVAL_TRUE;
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
static JSBool ConsoleSettingsGetProperty(JSContext *context, JSObject *this, jsval name, jsval *outValue)
|
||||
{
|
||||
NSString *key = nil;
|
||||
id value = nil;
|
||||
id monitor = nil;
|
||||
|
||||
if (!JSVAL_IS_STRING(name)) return YES;
|
||||
key = [NSString stringWithJavaScriptValue:name inContext:context];
|
||||
|
||||
monitor = JSObjectToObject(context, this);
|
||||
if (![monitor isKindOfClass:[OODebugMonitor class]])
|
||||
{
|
||||
OOReportJSError(context, @"Expected OODebugMonitor, got %@ in %s. This is an internal error, please report it.", [monitor class], __PRETTY_FUNCTION__);
|
||||
return NO;
|
||||
}
|
||||
|
||||
value = [monitor configurationValueForKey:key];
|
||||
*outValue = [value javaScriptValueInContext:context];
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
static JSBool ConsoleSettingsSetProperty(JSContext *context, JSObject *this, jsval name, jsval *inValue)
|
||||
{
|
||||
NSString *key = nil;
|
||||
id value = nil;
|
||||
id monitor = nil;
|
||||
|
||||
if (!JSVAL_IS_STRING(name)) return YES;
|
||||
key = [NSString stringWithJavaScriptValue:name inContext:context];
|
||||
|
||||
monitor = JSObjectToObject(context, this);
|
||||
if (![monitor isKindOfClass:[OODebugMonitor class]])
|
||||
{
|
||||
OOReportJSError(context, @"Expected OODebugMonitor, got %@ in %s. This is an internal error, please report it.", [monitor class], __PRETTY_FUNCTION__);
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (JSVAL_IS_NULL(*inValue) || JSVAL_IS_VOID(*inValue))
|
||||
{
|
||||
[monitor setConfigurationValue:nil forKey:key];
|
||||
}
|
||||
else
|
||||
{
|
||||
value = JSValueToObject(context, *inValue);
|
||||
if (value != nil)
|
||||
{
|
||||
[monitor setConfigurationValue:value forKey:key];
|
||||
}
|
||||
else
|
||||
{
|
||||
OOReportJSWarning(context, @"debugConsole.settings: could not convert %@ to native object.", [NSString stringWithJavaScriptValue:*inValue inContext:context]);
|
||||
}
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
// *** Methods ***
|
||||
|
||||
// function consoleMessage(message : String) : void
|
||||
static JSBool ConsoleConsoleMessage(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult)
|
||||
{
|
||||
id monitor = nil;
|
||||
NSString *colorKey = nil,
|
||||
*message = nil;
|
||||
NSRange emphasisRange = {0, 0};
|
||||
jsdouble location, length;
|
||||
|
||||
monitor = JSObjectToObject(context, this);
|
||||
if (![monitor isKindOfClass:[OODebugMonitor class]])
|
||||
{
|
||||
OOReportJSError(context, @"Expected OODebugMonitor, got %@ in %s. This is an internal error, please report it.", [monitor class], __PRETTY_FUNCTION__);
|
||||
return NO;
|
||||
}
|
||||
|
||||
colorKey = JSValToNSString(context,argv[0]);
|
||||
message = JSValToNSString(context,argv[1]);
|
||||
|
||||
if (4 <= argc)
|
||||
{
|
||||
// Attempt to get two numbers, specifying an emphasis range.
|
||||
if (JS_ValueToNumber(context, argv[2], &location) &&
|
||||
JS_ValueToNumber(context, argv[3], &length))
|
||||
{
|
||||
emphasisRange = NSMakeRange(location, length);
|
||||
}
|
||||
}
|
||||
|
||||
if (message == nil)
|
||||
{
|
||||
if (colorKey == nil)
|
||||
{
|
||||
OOReportJSWarning(context, @"Console.consoleMessage() called with no parameters.");
|
||||
}
|
||||
else
|
||||
{
|
||||
message = colorKey;
|
||||
colorKey = @"command-result";
|
||||
}
|
||||
}
|
||||
|
||||
if (message != nil)
|
||||
{
|
||||
[monitor appendJSConsoleLine:message
|
||||
colorKey:colorKey
|
||||
emphasisRange:emphasisRange];
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
// function clearConsole() : void
|
||||
static JSBool ConsoleClearConsole(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult)
|
||||
{
|
||||
id monitor = nil;
|
||||
|
||||
monitor = JSObjectToObject(context, this);
|
||||
if (![monitor isKindOfClass:[OODebugMonitor class]])
|
||||
{
|
||||
OOReportJSError(context, @"Expected OODebugMonitor, got %@ in %s. This is an internal error, please report it.", [monitor class], __PRETTY_FUNCTION__);
|
||||
return NO;
|
||||
}
|
||||
|
||||
[monitor clearJSConsole];
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
// function scriptStack() : Array
|
||||
static JSBool ConsoleScriptStack(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult)
|
||||
{
|
||||
NSArray *result = nil;
|
||||
|
||||
result = [OOJSScript scriptStack];
|
||||
*outResult = [result javaScriptValueInContext:context];
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
// function inspectEntity(entity : Entity) : void
|
||||
static JSBool ConsoleInspectEntity(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult)
|
||||
{
|
||||
Entity *entity = nil;
|
||||
|
||||
if (JSValueToEntity(context, argv[0], &entity))
|
||||
{
|
||||
if ([entity respondsToSelector:@selector(inspect)])
|
||||
{
|
||||
[entity inspect];
|
||||
}
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
// function __callObjCMethod(selector : String [, ...]) : Object
|
||||
static JSBool ConsoleCallObjCMethod(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult)
|
||||
{
|
||||
id object = nil;
|
||||
|
||||
object = JSObjectToObject(context, this);
|
||||
if (object == nil)
|
||||
{
|
||||
OOReportJSError(context, @"Attempt to call __callObjCMethod() for non-Objective-C object %@.", [NSString stringWithJavaScriptValue:OBJECT_TO_JSVAL(this) inContext:context]);
|
||||
return NO;
|
||||
}
|
||||
|
||||
return OOJSCallObjCObjectMethod(context, object, [object jsClassName], argc, argv, outResult);
|
||||
}
|
||||
|
||||
|
||||
// function isExecutableJavaScript(this : Object, string : String) : Boolean
|
||||
static JSBool ConsoleIsExecutableJavaScript(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult)
|
||||
{
|
||||
JSObject *target = NULL;
|
||||
JSString *string = NULL;
|
||||
|
||||
*outResult = JSVAL_FALSE;
|
||||
if (argc < 2) return YES;
|
||||
if (!JS_ValueToObject(context, argv[0], &target) || !JSVAL_IS_STRING(argv[1])) return YES; // Fail silently
|
||||
string = JSVAL_TO_STRING(argv[1]);
|
||||
|
||||
*outResult = BOOLEAN_TO_JSVAL(JS_BufferIsCompilableUnit(context, target, JS_GetStringBytes(string), JS_GetStringLength(string)));
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
// function displayMessagesInClass(class : String) : Boolean
|
||||
static JSBool ConsoleDisplayMessagesInClass(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult)
|
||||
{
|
||||
NSString *messageClass = nil;
|
||||
|
||||
messageClass = [NSString stringWithJavaScriptValue:argv[0] inContext:context];
|
||||
*outResult = BOOLEAN_TO_JSVAL(OOLogWillDisplayMessagesInClass(messageClass));
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
// function setDisplayMessagesInClass(class : String, flag : Boolean) : void
|
||||
static JSBool ConsoleSetDisplayMessagesInClass(JSContext *context, JSObject *this, uintN argc, jsval *argv, jsval *outResult)
|
||||
{
|
||||
NSString *messageClass = nil;
|
||||
JSBool flag;
|
||||
|
||||
messageClass = JSValToNSString(context, argv[0]);
|
||||
if (messageClass != nil && JS_ValueToBoolean(context, argv[1], &flag))
|
||||
{
|
||||
OOLogSetDisplayMessagesInClass(messageClass, flag);
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
#endif /* OO_EXCLUDE_DEBUG_SUPPORT */
|
|
@ -0,0 +1,266 @@
|
|||
/*
|
||||
|
||||
OOTCPStreamDecoder.c
|
||||
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2007 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
#ifndef OO_EXCLUDE_DEBUG_SUPPORT
|
||||
|
||||
|
||||
#include "OOTCPStreamDecoder.h"
|
||||
#include <stdlib.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdint.h>
|
||||
#include "OODebugTCPConsoleProtocol.h"
|
||||
|
||||
|
||||
#ifdef OO_LOG_DEBUG_PROTOCOL_PACKETS
|
||||
extern void LogOOTCPStreamDecoderPacket(OOALDictionaryRef packet);
|
||||
#else
|
||||
#define LogOOTCPStreamDecoderPacket(packet) do {} while (0)
|
||||
#endif
|
||||
|
||||
|
||||
struct OOTCPStreamDecoder
|
||||
{
|
||||
uint8_t header[4];
|
||||
uint32_t headerSpaceUsed;
|
||||
OOALMutableDataRef nextPacketData;
|
||||
uint32_t nextSize;
|
||||
|
||||
OOTCPStreamDecoderPacketCallback Packet;
|
||||
OOTCPStreamDecoderErrorCallback Error;
|
||||
OOTCPStreamDecoderFinalizeCallback Finalize;
|
||||
|
||||
void *cbInfo;
|
||||
};
|
||||
|
||||
|
||||
static void Error(OOTCPStreamDecoderRef decoder, OOALStringRef format, ...);
|
||||
static void PacketReady(OOTCPStreamDecoderRef decoder);
|
||||
|
||||
|
||||
OOTCPStreamDecoderRef OOTCPStreamDecoderCreate(OOTCPStreamDecoderPacketCallback packetCB, OOTCPStreamDecoderErrorCallback errorCB, OOTCPStreamDecoderFinalizeCallback finalizeCB, void *cbInfo)
|
||||
{
|
||||
OOTCPStreamDecoderRef decoder = NULL;
|
||||
|
||||
if (packetCB == NULL) return NULL;
|
||||
|
||||
decoder = malloc(sizeof *decoder);
|
||||
if (decoder == NULL) return NULL;
|
||||
|
||||
decoder->headerSpaceUsed = 0;
|
||||
decoder->nextPacketData = NULL;
|
||||
decoder->nextSize = 0;
|
||||
decoder->Packet = packetCB;
|
||||
decoder->Error = errorCB;
|
||||
decoder->Finalize = finalizeCB;
|
||||
decoder->cbInfo = cbInfo;
|
||||
|
||||
return decoder;
|
||||
}
|
||||
|
||||
|
||||
void OOTCPStreamDecoderDestroy(OOTCPStreamDecoderRef decoder)
|
||||
{
|
||||
if (decoder == NULL) return;
|
||||
|
||||
if (decoder->Finalize != NULL)
|
||||
{
|
||||
decoder->Finalize(decoder->cbInfo);
|
||||
}
|
||||
|
||||
if (decoder->nextPacketData != NULL)
|
||||
{
|
||||
OOALRelease(decoder->nextPacketData);
|
||||
decoder->nextPacketData = NULL;
|
||||
}
|
||||
|
||||
free(decoder);
|
||||
}
|
||||
|
||||
|
||||
void OOTCPStreamDecoderReceiveData(OOTCPStreamDecoderRef decoder, OOALDataRef data)
|
||||
{
|
||||
if (decoder == NULL || data == NULL) return;
|
||||
|
||||
OOTCPStreamDecoderReceiveBytes(decoder, OOALDataGetBytePtr(data), OOALDataGetLength(data));
|
||||
}
|
||||
|
||||
|
||||
void OOTCPStreamDecoderReceiveBytes(OOTCPStreamDecoderRef decoder, const void *inBytes, size_t length)
|
||||
{
|
||||
const unsigned char *bytes = NULL;
|
||||
size_t remaining;
|
||||
size_t bytesToAdd;
|
||||
OOALAutoreleasePoolRef pool = NULL;
|
||||
|
||||
if (decoder == NULL) return;
|
||||
|
||||
bytes = inBytes;
|
||||
remaining = length;
|
||||
|
||||
if (bytes == NULL && remaining != 0)
|
||||
{
|
||||
Error(decoder, OOALSTR("Invalid data -- NULL bytes but %u byte count."), remaining);
|
||||
return;
|
||||
}
|
||||
|
||||
while (remaining != 0)
|
||||
{
|
||||
if (decoder->nextPacketData != NULL)
|
||||
{
|
||||
// More data expected
|
||||
bytesToAdd = remaining;
|
||||
if (decoder->nextSize < bytesToAdd) bytesToAdd = decoder->nextSize;
|
||||
|
||||
OOALMutableDataAppendBytes(decoder->nextPacketData, bytes, bytesToAdd);
|
||||
|
||||
remaining -= bytesToAdd;
|
||||
decoder->nextSize -= bytesToAdd;
|
||||
bytes += bytesToAdd;
|
||||
|
||||
if (decoder->nextSize == 0)
|
||||
{
|
||||
// Packet is ready.
|
||||
pool = OOALCreateAutoreleasePool();
|
||||
PacketReady(decoder);
|
||||
OOALDestroyAutoreleasePool(pool);
|
||||
pool = NULL;
|
||||
|
||||
OOALRelease(decoder->nextPacketData);
|
||||
decoder->nextPacketData = NULL;
|
||||
}
|
||||
}
|
||||
else if (decoder->headerSpaceUsed < 4)
|
||||
{
|
||||
// Read bytes for packet header
|
||||
remaining--;
|
||||
decoder->header[decoder->headerSpaceUsed++] = *bytes++;
|
||||
}
|
||||
else if (decoder->headerSpaceUsed == 4)
|
||||
{
|
||||
// We've read a header, start on a packet.
|
||||
decoder->nextSize = (decoder->header[0] << 24) |
|
||||
(decoder->header[1] << 16) |
|
||||
(decoder->header[2] << 8) |
|
||||
(decoder->header[3] << 0);
|
||||
|
||||
decoder->headerSpaceUsed = 0;
|
||||
if (decoder->nextSize != 0)
|
||||
{
|
||||
decoder->nextPacketData = OOALDataCreateMutable(decoder->nextSize);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Error(decoder, OOALSTR("OOTCPStreamDecoder internal error: reached unreachable state. nextSize = %lu, bufferUsed = %lu, nextPacketData = %@."), (unsigned long)decoder->nextSize, (unsigned long)decoder->headerSpaceUsed, decoder->nextPacketData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static void PacketReady(OOTCPStreamDecoderRef decoder)
|
||||
{
|
||||
OOALDictionaryRef packet = NULL;
|
||||
OOALStringRef errorString = NULL;
|
||||
OOALStringRef packetType = NULL;
|
||||
|
||||
packet = OOALPropertyListFromData(decoder->nextPacketData, &errorString);
|
||||
|
||||
// Ensure that it's a property list.
|
||||
if (packet == NULL)
|
||||
{
|
||||
Error(decoder, OOALSTR("Protocol error: packet is not property list (property list error: %@)."), errorString);
|
||||
OOALRelease(errorString);
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure that it's a dictionary.
|
||||
if (!OOALIsDictionary(packet))
|
||||
{
|
||||
Error(decoder, OOALSTR("Protocol error: packet is a %@, not a dictionary."), OOTypeDescription(packet));
|
||||
return;
|
||||
}
|
||||
|
||||
LogOOTCPStreamDecoderPacket(packet);
|
||||
|
||||
// Get packet type (and ensure that there is one).
|
||||
packetType = OOALDictionaryGetValue(packet, kOOTCPPacketType);
|
||||
if (packetType == NULL)
|
||||
{
|
||||
Error(decoder, OOALSTR("Protocol error: packet contains no packet type."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!OOALIsString(packetType))
|
||||
{
|
||||
Error(decoder, OOALSTR("Protocol error: packet type is a %@, not a string."), OOTypeDescription(packetType));
|
||||
return;
|
||||
}
|
||||
|
||||
decoder->Packet(decoder->cbInfo, packetType, packet);
|
||||
}
|
||||
|
||||
|
||||
static void Error(OOTCPStreamDecoderRef decoder, OOALStringRef format, ...)
|
||||
{
|
||||
va_list args;
|
||||
OOALStringRef string = NULL;
|
||||
|
||||
if (decoder == NULL || decoder->Error == NULL || format == NULL) return;
|
||||
|
||||
va_start(args, format);
|
||||
string = OOALStringCreateWithFormatAndArguments(format, args);
|
||||
va_end(args);
|
||||
|
||||
if (string != NULL)
|
||||
{
|
||||
decoder->Error(decoder->cbInfo, string);
|
||||
OOALRelease(string);
|
||||
}
|
||||
}
|
||||
|
||||
#endif /* OO_EXCLUDE_DEBUG_SUPPORT */
|
|
@ -0,0 +1,72 @@
|
|||
/*
|
||||
|
||||
OOTCPStreamDecoder.h
|
||||
|
||||
Psuedo-object to take blobs of data, create Oolite TCP debug console
|
||||
protocol packets.
|
||||
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
|
||||
This file may also be distributed under the MIT/X11 license:
|
||||
|
||||
Copyright (C) 2007 Jens Ayton
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
|
||||
#ifndef INCLUDED_OOTCPStreamDecoder_h
|
||||
#define INCLUDED_OOTCPStreamDecoder_h
|
||||
|
||||
#include "OOTCPStreamDecoderAbstractionLayer.h"
|
||||
|
||||
|
||||
typedef struct OOTCPStreamDecoder *OOTCPStreamDecoderRef;
|
||||
|
||||
typedef void (*OOTCPStreamDecoderPacketCallback)(void *cbInfo, OOALStringRef packetType, OOALDictionaryRef packet);
|
||||
typedef void (*OOTCPStreamDecoderErrorCallback)(void *cbInfo, OOALStringRef errorDesc);
|
||||
typedef void (*OOTCPStreamDecoderFinalizeCallback)(void *cbInfo);
|
||||
|
||||
|
||||
OOTCPStreamDecoderRef OOTCPStreamDecoderCreate(OOTCPStreamDecoderPacketCallback packetCB, OOTCPStreamDecoderErrorCallback errorCB, OOTCPStreamDecoderFinalizeCallback finalizeCB, void *cbInfo);
|
||||
void OOTCPStreamDecoderDestroy(OOTCPStreamDecoderRef decoder);
|
||||
|
||||
void OOTCPStreamDecoderReceiveData(OOTCPStreamDecoderRef decoder, OOALDataRef data);
|
||||
void OOTCPStreamDecoderReceiveBytes(OOTCPStreamDecoderRef decoder, const void *bytes, size_t length);
|
||||
|
||||
#endif /* INCLUDED_OOTCPStreamDecoder_h */
|
|
@ -0,0 +1,122 @@
|
|||
/* OOTCPStreamDecoderAbstractionLayer.h
|
||||
|
||||
Abstraction layer to allow OOTCPStreamDecoder to work with CoreFoundation/
|
||||
CF-Lite, Cocoa Foundation or GNUstep Foundation.
|
||||
*/
|
||||
|
||||
#ifndef INCLUDED_OOTCPStreamDecoderAbstractionLayer_h
|
||||
#define INCLUDED_OOTCPStreamDecoderAbstractionLayer_h
|
||||
|
||||
#ifndef OOTCPSTREAM_USE_COREFOUNDATION
|
||||
#define OOTCPSTREAM_USE_COREFOUNDATION 0
|
||||
#endif
|
||||
|
||||
#if OOTCPSTREAM_USE_COREFOUNDATION
|
||||
|
||||
#include <CoreFoundation/CoreFoundation.h>
|
||||
#import "JAAutoreleasePool.h"
|
||||
|
||||
|
||||
#define OOALRelease(object) CFRelease(object)
|
||||
|
||||
#define OOTypeDescription(object) JAAutorelease(CFCopyTypeIDDescription(CFGetTypeID(object)))
|
||||
|
||||
|
||||
|
||||
typedef CFStringRef OOALStringRef;
|
||||
#define OOALIsString(object) (CFGetTypeID(object) == CFStringGetTypeID())
|
||||
|
||||
#define OOALSTR(str) CFSTR(str)
|
||||
|
||||
#define OOALStringCreateWithFormatAndArguments(format, args) CFStringCreateWithFormatAndArguments(kCFAllocatorDefault, NULL, format, args)
|
||||
|
||||
|
||||
|
||||
typedef CFDictionaryRef OOALDictionaryRef;
|
||||
#define OOALIsDictionary(object) (CFGetTypeID(object) == CFDictionaryGetTypeID())
|
||||
|
||||
#define OOALDictionaryGetValue(dictionary, key) CFDictionaryGetValue(dictionary, key)
|
||||
|
||||
|
||||
|
||||
typedef CFDataRef OOALDataRef;
|
||||
typedef CFMutableDataRef OOALMutableDataRef;
|
||||
#define OOALIsData(object) (CFGetTypeID(object) == CFDataGetTypeID())
|
||||
|
||||
#define OOALDataCreateMutable(capacity) CFDataCreateMutable(kCFAllocatorDefault, capacity)
|
||||
|
||||
#define OOALMutableDataAppendBytes(data, bytes, length) CFDataAppendBytes(data, bytes, length)
|
||||
|
||||
#define OOALDataGetBytePtr(data) CFDataGetBytePtr(data)
|
||||
#define OOALDataGetLength(data) CFDataGetLength(data)
|
||||
|
||||
|
||||
|
||||
typedef JAAutoreleasePoolRef OOALAutoreleasePoolRef;
|
||||
|
||||
#define OOALCreateAutoreleasePool() JACreateAutoreleasePool()
|
||||
#define OOALDestroyAutoreleasePool(pool) JADestroyAutoreleasePool(pool)
|
||||
|
||||
|
||||
|
||||
#define OOALPropertyListFromData(data, errStr) JAAutorelease(CFPropertyListCreateFromXMLData(kCFAllocatorDefault, data, kCFPropertyListImmutable, errStr))
|
||||
|
||||
#else /* !OOTCPSTREAM_USE_COREFOUNDATION */
|
||||
|
||||
#include <stdarg.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
|
||||
#if __OBJC__
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
typedef id OOALObjectRef;
|
||||
|
||||
typedef NSString *OOALStringRef;
|
||||
typedef NSData *OOALDataRef;
|
||||
typedef NSMutableData *OOALMutableDataRef;
|
||||
typedef NSDictionary *OOALDictionaryRef;
|
||||
typedef NSAutoreleasePool *OOALAutoreleasePoolRef;
|
||||
|
||||
#define OOALSTR(x) @""x
|
||||
|
||||
#else
|
||||
|
||||
typedef const void *OOALObjectRef;
|
||||
|
||||
typedef const struct NSString *OOALStringRef;
|
||||
typedef const struct NSData *OOALDataRef;
|
||||
typedef struct NSData *OOALMutableDataRef;
|
||||
typedef const struct NSDictionary *OOALDictionaryRef;
|
||||
typedef const struct NSAutoreleasePool *OOALAutoreleasePoolRef;
|
||||
|
||||
OOALStringRef OOALGetConstantString(const char *string); // Should only be used with string literals!
|
||||
#define OOALSTR(string) OOALGetConstantString("" string "")
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
void OOALRelease(OOALObjectRef object);
|
||||
OOALStringRef OOTypeDescription(OOALObjectRef object);
|
||||
|
||||
bool OOALIsString(OOALObjectRef object);
|
||||
OOALStringRef OOALStringCreateWithFormatAndArguments(OOALStringRef format, va_list args);
|
||||
|
||||
bool OOALIsDictionary(OOALObjectRef object);
|
||||
OOALObjectRef OOALDictionaryGetValue(OOALDictionaryRef dictionary, OOALObjectRef key);
|
||||
|
||||
bool OOALIsData(OOALObjectRef object);
|
||||
OOALMutableDataRef OOALDataCreateMutable(size_t capacity);
|
||||
void OOALMutableDataAppendBytes(OOALMutableDataRef data, const void *bytes, size_t length);
|
||||
const void *OOALDataGetBytePtr(OOALDataRef data);
|
||||
size_t OOALDataGetLength(OOALDataRef data);
|
||||
|
||||
OOALAutoreleasePoolRef OOALCreateAutoreleasePool(void);
|
||||
#define OOALDestroyAutoreleasePool(pool) OOALRelease(pool)
|
||||
|
||||
OOALObjectRef OOALPropertyListFromData(OOALMutableDataRef data, OOALStringRef *errStr);
|
||||
|
||||
#endif /* OOTCPSTREAM_USE_COREFOUNDATION */
|
||||
#endif /* INCLUDED_OOTCPStreamDecoderAbstractionLayer_h */
|
|
@ -0,0 +1,127 @@
|
|||
/* OOTCPStreamDecoderAbstractionLayer.h
|
||||
|
||||
Abstraction layer to allow OOTCPStreamDecoder to work with CoreFoundation/
|
||||
CF-Lite, Cocoa Foundation or GNUstep Foundation.
|
||||
|
||||
Foundation implementation.
|
||||
*/
|
||||
|
||||
#ifndef OO_EXCLUDE_DEBUG_SUPPORT
|
||||
|
||||
#import "OOTCPStreamDecoderAbstractionLayer.h"
|
||||
#import "OOCocoa.h"
|
||||
|
||||
|
||||
// Simulate literal CF/NS strings. Each literal string that is used becomes a single object. Since it uses pointers as keys, it should only be used with literals.
|
||||
OOALStringRef OOALGetConstantString(const char *string)
|
||||
{
|
||||
static NSMutableDictionary *sStrings = nil;
|
||||
NSValue *key = nil;
|
||||
NSString *value = nil;
|
||||
|
||||
if (sStrings == nil)
|
||||
{
|
||||
sStrings = [[NSMutableDictionary alloc] init];
|
||||
}
|
||||
|
||||
key = [NSValue valueWithPointer:string];
|
||||
value = [sStrings objectForKey:key];
|
||||
if (value == nil)
|
||||
{
|
||||
// Note: non-ASCII strings are not permitted, but we don't bother to detect them.
|
||||
value = [NSString stringWithUTF8String:string];
|
||||
if (value != nil) [sStrings setObject:value forKey:key];
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
void OOALRelease(OOALObjectRef object)
|
||||
{
|
||||
[object release];
|
||||
}
|
||||
|
||||
|
||||
OOALStringRef OOTypeDescription(OOALObjectRef object)
|
||||
{
|
||||
return [[object class] description];
|
||||
}
|
||||
|
||||
|
||||
bool OOALIsString(OOALObjectRef object)
|
||||
{
|
||||
return [object isKindOfClass:[NSString class]];
|
||||
}
|
||||
|
||||
|
||||
OOALStringRef OOALStringCreateWithFormatAndArguments(OOALStringRef format, va_list args)
|
||||
{
|
||||
return [[NSString alloc] initWithFormat:format arguments:args];
|
||||
}
|
||||
|
||||
|
||||
bool OOALIsDictionary(OOALObjectRef object)
|
||||
{
|
||||
return [object isKindOfClass:[NSDictionary class]];
|
||||
}
|
||||
|
||||
|
||||
OOALObjectRef OOALDictionaryGetValue(OOALDictionaryRef dictionary, OOALObjectRef key)
|
||||
{
|
||||
return [dictionary objectForKey:key];
|
||||
}
|
||||
|
||||
|
||||
bool OOALIsData(OOALObjectRef object)
|
||||
{
|
||||
return [object isKindOfClass:[NSData class]];
|
||||
}
|
||||
|
||||
|
||||
OOALMutableDataRef OOALDataCreateMutable(size_t capacity)
|
||||
{
|
||||
return [[NSMutableData alloc] initWithCapacity:capacity];
|
||||
}
|
||||
|
||||
|
||||
void OOALMutableDataAppendBytes(OOALMutableDataRef data, const void *bytes, size_t length)
|
||||
{
|
||||
[data appendBytes:bytes length:length];
|
||||
}
|
||||
|
||||
|
||||
const void *OOALDataGetBytePtr(OOALDataRef data)
|
||||
{
|
||||
return [data bytes];
|
||||
}
|
||||
|
||||
|
||||
size_t OOALDataGetLength(OOALDataRef data)
|
||||
{
|
||||
return [data length];
|
||||
}
|
||||
|
||||
|
||||
OOALAutoreleasePoolRef OOALCreateAutoreleasePool(void)
|
||||
{
|
||||
return [[NSAutoreleasePool alloc] init];
|
||||
}
|
||||
|
||||
|
||||
OOALObjectRef OOALPropertyListFromData(OOALMutableDataRef data, OOALStringRef *errStr)
|
||||
{
|
||||
id result = [NSPropertyListSerialization propertyListFromData:data
|
||||
mutabilityOption:NSPropertyListImmutable
|
||||
format:NULL
|
||||
errorDescription:errStr];
|
||||
[result retain];
|
||||
|
||||
#if !OOLITE_RELEASE_PLIST_ERROR_STRINGS
|
||||
[*errStr retain];
|
||||
#endif
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
#endif /* OO_EXCLUDE_DEBUG_SUPPORT */
|
|
@ -0,0 +1,45 @@
|
|||
/*
|
||||
|
||||
DustEntity.h
|
||||
|
||||
Entity representing a number of dust particles.
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
*/
|
||||
|
||||
#import "OOSelfDrawingEntity.h"
|
||||
|
||||
#define DUST_SCALE 2000
|
||||
#define DUST_N_PARTICLES 600
|
||||
|
||||
@class OOColor;
|
||||
|
||||
@interface DustEntity: Entity
|
||||
{
|
||||
OOColor *dust_color;
|
||||
Vector vertices[DUST_N_PARTICLES];
|
||||
GLfloat color_fv[4];
|
||||
GLuint displayListName;
|
||||
}
|
||||
|
||||
- (void) setDustColor:(OOColor *) color;
|
||||
- (OOColor *) dust_color;
|
||||
|
||||
@end
|
|
@ -0,0 +1,214 @@
|
|||
/*
|
||||
|
||||
DustEntity.m
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
*/
|
||||
|
||||
#import "DustEntity.h"
|
||||
|
||||
#import "OOMaths.h"
|
||||
#import "Universe.h"
|
||||
#import "MyOpenGLView.h"
|
||||
#import "OOGraphicsResetManager.h"
|
||||
|
||||
#import "PlayerEntity.h"
|
||||
|
||||
|
||||
// Declare protocol conformance
|
||||
@interface DustEntity (OOGraphicsResetClient) <OOGraphicsResetClient>
|
||||
@end
|
||||
|
||||
|
||||
@implementation DustEntity
|
||||
|
||||
- (id) init
|
||||
{
|
||||
int vi;
|
||||
|
||||
ranrot_srand([[NSDate date] timeIntervalSince1970]); // seed randomiser by time
|
||||
|
||||
self = [super init];
|
||||
|
||||
for (vi = 0; vi < DUST_N_PARTICLES; vi++)
|
||||
{
|
||||
vertices[vi].x = (ranrot_rand() % DUST_SCALE) - DUST_SCALE / 2;
|
||||
vertices[vi].y = (ranrot_rand() % DUST_SCALE) - DUST_SCALE / 2;
|
||||
vertices[vi].z = (ranrot_rand() % DUST_SCALE) - DUST_SCALE / 2;
|
||||
}
|
||||
|
||||
dust_color = [[OOColor colorWithCalibratedRed:0.5 green:1.0 blue:1.0 alpha:1.0] retain];
|
||||
displayListName = 0;
|
||||
[self setStatus:STATUS_ACTIVE];
|
||||
|
||||
[[OOGraphicsResetManager sharedManager] registerClient:self];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
- (void) dealloc
|
||||
{
|
||||
[dust_color release];
|
||||
[[OOGraphicsResetManager sharedManager] unregisterClient:self];
|
||||
glDeleteLists(displayListName, 1);
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
|
||||
- (void) setDustColor:(OOColor *) color
|
||||
{
|
||||
if (dust_color) [dust_color release];
|
||||
dust_color = [color retain];
|
||||
[dust_color getGLRed:&color_fv[0] green:&color_fv[1] blue:&color_fv[2] alpha:&color_fv[3]];
|
||||
}
|
||||
|
||||
|
||||
- (OOColor *) dust_color
|
||||
{
|
||||
return dust_color;
|
||||
}
|
||||
|
||||
|
||||
- (BOOL) canCollide
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
- (void) update:(OOTimeDelta) delta_t
|
||||
{
|
||||
PlayerEntity* player = [PlayerEntity sharedPlayer];
|
||||
assert(player != nil);
|
||||
|
||||
zero_distance = 0.0;
|
||||
|
||||
Vector offset = player->position;
|
||||
GLfloat half_scale = DUST_SCALE * 0.50;
|
||||
int vi;
|
||||
for (vi = 0; vi < DUST_N_PARTICLES; vi++)
|
||||
{
|
||||
while (vertices[vi].x - offset.x < -half_scale)
|
||||
vertices[vi].x += DUST_SCALE;
|
||||
while (vertices[vi].x - offset.x > half_scale)
|
||||
vertices[vi].x -= DUST_SCALE;
|
||||
|
||||
while (vertices[vi].y - offset.y < -half_scale)
|
||||
vertices[vi].y += DUST_SCALE;
|
||||
while (vertices[vi].y - offset.y > half_scale)
|
||||
vertices[vi].y -= DUST_SCALE;
|
||||
|
||||
while (vertices[vi].z - offset.z < -half_scale)
|
||||
vertices[vi].z += DUST_SCALE;
|
||||
while (vertices[vi].z - offset.z > half_scale)
|
||||
vertices[vi].z -= DUST_SCALE;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
- (void) drawEntity:(BOOL) immediate :(BOOL) translucent
|
||||
{
|
||||
PlayerEntity* player = [PlayerEntity sharedPlayer];
|
||||
assert(player != nil);
|
||||
|
||||
#ifndef NDEBUG
|
||||
if (gDebugFlags & DEBUG_NO_DUST) return;
|
||||
#endif
|
||||
|
||||
int ct;
|
||||
int vi;
|
||||
|
||||
GLfloat *fogcolor = [UNIVERSE skyClearColor];
|
||||
int dust_size = floor([[UNIVERSE gameView] viewSize].width / 480.0);
|
||||
if (dust_size < 1.0)
|
||||
dust_size = 1.0;
|
||||
int line_size = dust_size / 2;
|
||||
if (line_size < 1.0)
|
||||
line_size = 1.0;
|
||||
GLfloat half_scale = DUST_SCALE * 0.50;
|
||||
GLfloat quarter_scale = DUST_SCALE * 0.25;
|
||||
|
||||
if ([UNIVERSE breakPatternHide]) return; // DON'T DRAW
|
||||
|
||||
BOOL warp_stars = [player atHyperspeed];
|
||||
Vector warp_vector = vector_multiply_scalar([player velocityVector], 1.0f / HYPERSPEED_FACTOR);
|
||||
|
||||
if (translucent)
|
||||
{
|
||||
glEnable(GL_FOG);
|
||||
glFogi(GL_FOG_MODE, GL_LINEAR);
|
||||
glFogfv(GL_FOG_COLOR, fogcolor);
|
||||
glHint(GL_FOG_HINT, GL_NICEST);
|
||||
glFogf(GL_FOG_START, quarter_scale);
|
||||
glFogf(GL_FOG_END, half_scale);
|
||||
//
|
||||
// disapply lighting and texture
|
||||
glDisable(GL_TEXTURE_2D);
|
||||
//
|
||||
if (player->isSunlit)
|
||||
glColor4fv(color_fv);
|
||||
else
|
||||
glColor4fv(UNIVERSE->stars_ambient);
|
||||
//
|
||||
ct = 0;
|
||||
|
||||
GLenum dustMode;
|
||||
|
||||
if (!warp_stars)
|
||||
{
|
||||
glEnable(GL_POINT_SMOOTH);
|
||||
glPointSize(dust_size);
|
||||
dustMode = GL_POINTS;
|
||||
}
|
||||
else
|
||||
{
|
||||
glEnable(GL_LINE_SMOOTH);
|
||||
glLineWidth(line_size);
|
||||
dustMode = GL_LINES;
|
||||
}
|
||||
|
||||
glBegin(dustMode);
|
||||
|
||||
for (vi = 0; vi < DUST_N_PARTICLES; vi++)
|
||||
{
|
||||
GLVertexOOVector(vertices[vi]);
|
||||
if (warp_stars) GLVertexOOVector(vector_subtract(vertices[vi], warp_vector));
|
||||
}
|
||||
glEnd();
|
||||
// reapply normal conditions
|
||||
glDisable(GL_FOG);
|
||||
}
|
||||
|
||||
CheckOpenGLErrors(@"DustEntity after drawing %@", self);
|
||||
}
|
||||
|
||||
|
||||
- (void)resetGraphicsState
|
||||
{
|
||||
if (displayListName != 0)
|
||||
{
|
||||
glDeleteLists(displayListName, 1);
|
||||
displayListName = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
|
@ -0,0 +1,278 @@
|
|||
/*
|
||||
|
||||
Entity.h
|
||||
|
||||
Base class for entities, i.e. drawable world objects.
|
||||
|
||||
Oolite
|
||||
Copyright (C) 2004-2008 Giles C Williams and contributors
|
||||
|
||||
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
|
||||
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, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
MA 02110-1301, USA.
|
||||
|
||||
*/
|
||||
|
||||
|
||||
#import "OOCocoa.h"
|
||||
#import "OOMaths.h"
|
||||
#import "OOCacheManager.h"
|
||||
#import "OOTypes.h"
|
||||
#import "OOWeakReference.h"
|
||||
|
||||
@class Universe, Geometry, CollisionRegion, ShipEntity;
|
||||
|
||||
|
||||
#ifndef NDEBUG
|
||||
|
||||
#define DEBUG_ALL 0xffffffff
|
||||
#define DEBUG_LINKED_LISTS 0x00000001
|
||||
#define DEBUG_ENTITIES 0x00000002
|
||||
#define DEBUG_COLLISIONS 0x00000004
|
||||
#define DEBUG_DOCKING 0x00000008
|
||||
#define DEBUG_OCTREE 0x00000010
|
||||
#define DEBUG_OCTREE_TEXT 0x00000020
|
||||
#define DEBUG_BOUNDING_BOXES 0x00000040
|
||||
#define DEBUG_OCTREE_DRAW 0x00000080
|
||||
#define DEBUG_DRAW_NORMALS 0x00000100
|
||||
#define DEBUG_HIDE_HUD 0x00000200
|
||||
#define DEBUG_NO_DUST 0x00000400
|
||||
#define DEBUG_MISC 0x10000000
|
||||
|
||||
|
||||
extern uint32_t gDebugFlags;
|
||||
|
||||
#endif
|
||||
|
||||
#define NO_DRAW_DISTANCE_FACTOR 512.0
|
||||
#define ABSOLUTE_NO_DRAW_DISTANCE2 (2500.0 * 2500.0 * NO_DRAW_DISTANCE_FACTOR * NO_DRAW_DISTANCE_FACTOR)
|
||||
// ie. the furthest away thing we can draw is at 1280km (a 2.5km wide object would disappear at that range)
|
||||
|
||||
|
||||
#define SCANNER_MAX_RANGE 25600.0
|
||||
#define SCANNER_MAX_RANGE2 655360000.0
|
||||
|
||||
#define CLOSE_COLLISION_CHECK_MAX_RANGE2 1000000000.0
|
||||
|
||||
|
||||
typedef struct
|
||||
{
|
||||
double timeframe; // universal time for this frame
|
||||
Vector position; // position
|
||||
Quaternion orientation; // rotation
|
||||
Vector k; // direction vectors
|
||||
} Frame;
|
||||
|
||||
|
||||
@interface Entity: OOWeakRefObject
|
||||
{
|
||||
// the base object for ships/stations/anything actually
|
||||
//////////////////////////////////////////////////////
|
||||
//
|
||||
// @public variables:
|
||||
//
|
||||
// we forego encapsulation for some variables in order to
|
||||
// lose the overheads of Obj-C accessor methods...
|
||||
//
|
||||
@public
|
||||
OOUniversalID universalID; // used to reference the entity
|
||||
|
||||
unsigned isParticle: 1,
|
||||
isRing: 1,
|
||||
isShip: 1,
|
||||
isStation: 1,
|
||||
isPlanet: 1,
|
||||
isPlayer: 1,
|
||||
isSky: 1,
|
||||
isWormhole: 1,
|
||||
isSubEntity: 1,
|
||||
hasMoved: 1,
|
||||
hasRotated: 1,
|
||||
hasCollided: 1,
|
||||
isSunlit: 1,
|
||||
collisionTestFilter: 1,
|
||||
throw_sparks: 1,
|
||||
isImmuneToBreakPatternHide: 1,
|
||||
isExplicitlyNotMainStation: 1;
|
||||
|
||||
OOScanClass scanClass;
|
||||
|
||||
GLfloat zero_distance;
|
||||
GLfloat no_draw_distance; // 10 km initially
|
||||
GLfloat collision_radius;
|
||||
Vector position;
|
||||
Quaternion orientation;
|
||||
|
||||
int zero_index;
|
||||
|
||||
// Linked lists of entites, sorted by position on each (world) axis
|
||||
Entity *x_previous, *x_next;
|
||||
Entity *y_previous, *y_next;
|
||||
Entity *z_previous, *z_next;
|
||||
|
||||
Entity *collision_chain;
|
||||
|
||||
OOUniversalID shadingEntityID;
|
||||
|
||||
Vector relativePosition;
|
||||
|
||||
Entity *collider;
|
||||
|
||||
CollisionRegion *collisionRegion; // initially nil - then maintained
|
||||
|
||||
@protected
|
||||
Vector lastPosition;
|
||||
Quaternion lastOrientation;
|
||||
|
||||
GLfloat distanceTravelled; // set to zero initially
|
||||
|
||||
OOMatrix rotMatrix;
|
||||
|
||||
Vector velocity;
|
||||
|
||||
// positions+rotations for trails and trackbacks
|
||||
// TODO: Can these be moved into a subclass? -- Ahruman
|
||||
Frame track[256];
|
||||
int trackIndex;
|
||||
OOTimeAbsolute trackTime;
|
||||
|
||||
GLfloat energy;
|
||||
GLfloat maxEnergy;
|
||||
|
||||
BoundingBox boundingBox;
|
||||
GLfloat mass;
|
||||
|
||||
NSMutableArray *collidingEntities;
|
||||
|
||||
OOTimeAbsolute spawnTime;
|
||||
|
||||
struct JSObject *jsSelf;
|
||||
|
||||
@private
|
||||
OOWeakReference *_owner;
|
||||
OOEntityStatus _status;
|
||||
}
|
||||
|
||||
- (BOOL) isShip;
|
||||
- (BOOL) isStation;
|
||||
- (BOOL) isSubEntity;
|
||||
- (BOOL) isPlayer;
|
||||
- (BOOL) isPlanet;
|
||||
- (BOOL) isSun;
|
||||
- (BOOL) isSky;
|
||||
- (BOOL) isWormhole;
|
||||
|
||||
- (BOOL) validForAddToUniverse;
|
||||
- (void) addToLinkedLists;
|
||||
- (void) removeFromLinkedLists;
|
||||
|
||||
- (void) updateLinkedLists;
|
||||
|
||||
- (void) wasAddedToUniverse;
|
||||
- (void) wasRemovedFromUniverse;
|
||||
|
||||
- (void) warnAboutHostiles;
|
||||
|
||||
- (CollisionRegion*) collisionRegion;
|
||||
- (void) setCollisionRegion:(CollisionRegion*)region;
|
||||
|
||||
- (void) setUniversalID:(OOUniversalID)uid;
|
||||
- (OOUniversalID) universalID;
|
||||
|
||||
- (BOOL) throwingSparks;
|
||||
- (void) setThrowSparks:(BOOL)value;
|
||||
- (void) throwSparks;
|
||||
|
||||
- (void) setOwner:(Entity *)ent;
|
||||
- (id)owner;
|
||||
- (ShipEntity *)parentEntity; // owner if self is subentity of owner, otherwise nil.
|
||||
- (ShipEntity *)rootShipEntity; // like parentEntity, but recursive.
|
||||
|
||||
- (void) setPosition:(Vector)posn;
|
||||
- (void) setPositionX:(GLfloat)x y:(GLfloat)y z:(GLfloat)z;
|
||||
- (Vector) position;
|
||||
|
||||
- (double) zeroDistance;
|
||||
- (Vector) relativePosition;
|
||||
- (NSComparisonResult) compareZeroDistance:(Entity *)otherEntity;
|
||||
|
||||
- (BoundingBox) boundingBox;
|
||||
|
||||
- (GLfloat) mass;
|
||||
|
||||
- (Quaternion) orientation;
|
||||
- (void) setOrientation:(Quaternion) quat;
|
||||
- (Quaternion) normalOrientation; // Historical wart: orientation.w is reversed for player; -normalOrientation corrects this.
|
||||
- (void) setNormalOrientation:(Quaternion) quat;
|
||||
- (void) orientationChanged;
|
||||
|
||||
- (void) setVelocity:(Vector)vel;
|
||||
- (Vector) velocity;
|
||||
- (double) speed;
|
||||
|
||||
- (GLfloat) distanceTravelled;
|
||||
- (void) setDistanceTravelled:(GLfloat)value;
|
||||
|
||||
|
||||
- (void) setStatus:(OOEntityStatus)stat;
|
||||
- (OOEntityStatus) status;
|
||||
|
||||
- (void) setScanClass:(OOScanClass)sClass;
|
||||
- (OOScanClass) scanClass;
|
||||
|
||||
- (void) setEnergy:(GLfloat)amount;
|
||||
- (GLfloat) energy;
|
||||
|
||||
- (void) setMaxEnergy:(GLfloat)amount;
|
||||
- (GLfloat) maxEnergy;
|
||||
|
||||
- (void) applyRoll:(GLfloat)roll andClimb:(GLfloat)climb;
|
||||
- (void) applyRoll:(GLfloat)roll climb:(GLfloat) climb andYaw:(GLfloat)yaw;
|
||||
- (void) moveForward:(double)amount;
|
||||
|
||||
- (OOMatrix) rotationMatrix;
|
||||
- (OOMatrix) drawRotationMatrix;
|
||||
|
||||
- (BOOL) canCollide;
|
||||
- (GLfloat) collisionRadius;
|
||||
- (void) setCollisionRadius:(GLfloat)amount;
|
||||
- (NSMutableArray *)collisionArray;
|
||||
|
||||
- (void) update:(OOTimeDelta) delta_t;
|
||||
- (void) saveToLastFrame;
|
||||
- (void) savePosition:(Vector)pos atTime:(double)t_time atIndex:(int)t_index;
|
||||
- (void) saveFrame:(Frame)frame atIndex:(int)t_index;
|
||||
- (void) resetFramesFromFrame:(Frame) resetFrame withVelocity:(Vector) vel1;
|
||||
- (BOOL) resetToTime:(double) t_frame;
|
||||
- (Frame) frameAtTime:(double) t_frame; // timeframe is relative to now ie. -0.5 = half a second ago.
|
||||
- (Frame) frameAtTime:(double) t_frame fromFrame:(Frame) frame_zero; // t_frame is relative to now ie. -0.5 = half a second ago.
|
||||
|
||||
- (BOOL) checkCloseCollisionWith:(Entity *)other;
|
||||
|
||||
- (void) takeEnergyDamage:(double) amount from:(Entity *) ent becauseOf:(Entity *) other;
|
||||
|
||||
- (void) dumpState; // General "describe situtation verbosely in log" command.
|
||||
- (void) dumpSelfState; // Subclasses should override this, not -dumpState, and call throught to super first.
|
||||
|
||||
// Subclass repsonsibilities
|
||||
- (double) findCollisionRadius;
|
||||
- (Geometry*) geometry;
|
||||
- (void) drawEntity:(BOOL)immediate :(BOOL)translucent;
|
||||
|
||||
// For shader bindings.
|
||||
- (GLfloat) universalTime;
|
||||
- (GLfloat) spawnTime;
|
||||
- (GLfloat) timeElapsedSinceSpawn;
|
||||
|
||||
@end
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue