18#if defined(WITH_COCOA) || defined(DOXYGEN_API)
132 Rect r = {left, top, left + width, top + height};
157 NSSize screen_size = [ [ NSScreen mainScreen ] frame ].size;
158 w = std::min(w, (
int)screen_size.width);
159 h = std::min(h, (
int)screen_size.height);
161 NSRect contentRect = NSMakeRect(0, 0, w, h);
162 [ this->
window setContentSize:contentRect.size ];
165 float content_height = [ this->
window contentRectForFrameRect:[ this->
window frame ] ].size.height;
166 contentRect.size.height =
Clamp(h, 0, (
int)content_height);
169 h = (int)contentRect.size.height;
170 [ this->
cocoaview setFrameSize:contentRect.size ];
188 if ([ this->
window respondsToSelector:
@selector(toggleFullScreen:) ]) {
189 [ this->
window performSelector:
@selector(toggleFullScreen:) withObject:this->
window ];
192 [ NSMenu setMenuBarVisible:!full_screen ];
210 [ this->
window refreshSystemSprites ];
230 [ [ this->
cocoaview inputContext ] performSelectorOnMainThread:
@selector(discardMarkedText) withObject:nil waitUntilDone:[ NSThread isMainThread ] ];
241 std::vector<int> rates{};
243 std::array<CGDirectDisplayID, 16> displays;
246 CGGetActiveDisplayList(displays.size(), displays.data(), &count);
248 for (uint32_t i = 0; i < count; i++) {
249 CGDisplayModeRef mode = CGDisplayCopyDisplayMode(displays[i]);
250 int rate =
static_cast<int>(CGDisplayModeGetRefreshRate(mode));
251 if (rate > 0) rates.push_back(rate);
252 CGDisplayModeRelease(mode);
264 NSRect frame = [ [ NSScreen mainScreen ] frame ];
265 return {
static_cast<uint
>(NSWidth(frame)),
static_cast<uint
>(NSHeight(frame)) };
278 assert(_screen.dst_ptr !=
nullptr);
286 if (_screen.dst_ptr !=
nullptr) {
289 _screen.dst_ptr =
nullptr;
301 return this->
window != nil && ([ this->
window styleMask ] & NSWindowStyleMaskFullScreen) != 0;
312 _fullscreen = fullscreen;
333 NSSize screen = [ [ this->
window screen ] frame ].size;
334 _resolutions.emplace_back((uint)screen.width, (uint)screen.height);
338 NSSize maxSize = [ [ NSScreen mainScreen] visibleFrame ].size;
340 if (d.width < maxSize.width && d.height < maxSize.height)
_resolutions.push_back(d);
342 _resolutions.emplace_back((uint)maxSize.width, (uint)maxSize.height);
357 NSSize screen_size = [ [ NSScreen mainScreen ] frame ].size;
358 if (width > screen_size.width) width = screen_size.width;
359 if (height > screen_size.height) height = screen_size.height;
361 NSRect contentRect = NSMakeRect(0, 0, width, height);
364 unsigned int style = NSWindowStyleMaskTitled | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskClosable;
365 this->
window = [ [
OTTD_CocoaWindow alloc ] initWithContentRect:contentRect styleMask:style backing:NSBackingStoreBuffered defer:NO driver:this ];
366 if (this->
window == nil) {
375 if ([ this->
window respondsToSelector:
@selector(toggleFullScreen:) ]) {
376 NSWindowCollectionBehavior behavior = [ this->
window collectionBehavior ];
377 behavior |= NSWindowCollectionBehaviorFullScreenPrimary;
378 [ this->
window setCollectionBehavior:behavior ];
380 NSButton *fullscreenButton = [ this->
window standardWindowButton:NSWindowZoomButton ];
381 [ fullscreenButton setAction:
@selector(toggleFullScreen:) ];
382 [ fullscreenButton setTarget:this->
window ];
389 [ this->
window makeKeyAndOrderFront:nil ];
392 NSRect view_frame = [ this->
window contentRectForFrameRect:[ this->
window frame ] ];
399 [ this->
cocoaview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable ];
403 if (draw_view == nil) {
408 [ draw_view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable ];
412 [ this->
cocoaview addSubview:draw_view ];
414 [ draw_view release ];
416 [ this->
window setColorSpace:[ NSColorSpace sRGBColorSpace ] ];
418 this->
colour_space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
420 if (this->
colour_space ==
nullptr) FatalError(
"Could not get a valid colour space for drawing.");
434 NSEventMask mask = NSEventMaskAny;
435 NSEvent *
event = [ NSApp nextEventMatchingMask:mask untilDate:[ NSDate distantPast ] inMode:NSDefaultRunLoopMode dequeue:YES ];
437 if (event == nil)
return false;
439 [ NSApp sendEvent:event ];
446 NSUInteger cur_mods = [ NSEvent modifierFlags ];
497 if (self = [ super initWithFrame:frameRect ]) {
501 self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawOnSetNeedsDisplay;
502 self.wantsLayer = YES;
504 self.layer.magnificationFilter = kCAFilterNearest;
505 self.layer.opaque = YES;
540 if (
driver->cgcontext ==
nullptr)
return;
543 CGImageRef fullImage = CGBitmapContextCreateImage(
driver->cgcontext);
544 self.layer.contents = (__bridge id)fullImage;
545 CGImageRelease(fullImage);
551 [
super viewDidChangeBackingProperties ];
553 self.layer.contentsScale = [
driver->cocoaview getContentsScale ];
569 uint32_t fill = Colour(0, 0, 0).data;
570 for (uint32_t y = 0; y < height; y++) {
571 for (uint32_t x = 0; x < pitch; x++) {
572 buffer[y * pitch + x] = fill;
577VideoDriver_CocoaQuartz::VideoDriver_CocoaQuartz()
581 this->window_pitch = 0;
595 if (bpp != 8 && bpp != 32) {
597 return "The cocoa quartz subdriver only supports 8 and 32 bpp.";
600 bool fullscreen = _fullscreen;
603 return "Could not create window";
631 return [ [
OTTD_QuartzView alloc ] initWithFrame:[
this->cocoaview bounds ] andDriver:this ];
640 NSRect newframe = [
this->cocoaview getRealRect:[
this->cocoaview frame ] ];
658 this->window_pitch * 4,
660 kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host
664 CGContextSetShouldAntialias(this->
cgcontext, FALSE);
665 CGContextSetAllowsAntialiasing(this->
cgcontext, FALSE);
666 CGContextSetInterpolationQuality(this->
cgcontext, kCGInterpolationNone);
676 _screen.height = this->window_height;
681 this->
MakeDirty(0, 0, _screen.width, _screen.height);
695 const uint32_t *pal = this->
palette;
699 uint pitch = this->window_pitch;
701 for (
int y = top; y < bottom; y++) {
702 for (
int x = left; x < right; x++) {
703 dst[
y * pitch + x] = pal[
src[
y * width + x]];
717 for (uint i = first_colour; i < first_colour + num_colours; i++) {
718 uint32_t clr = 0xff000000;
725 this->
MakeDirty(0, 0, _screen.width, _screen.height);
763 this->dirty_rect.top,
764 this->dirty_rect.right,
765 this->dirty_rect.bottom
776 [
this->cocoaview setNeedsDisplayInRect:[
this->cocoaview getVirtualRect:dirtyrect ] ];
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
How all blitters should look like.
virtual uint8_t GetScreenDepth()=0
Get the screen depth this blitter works for.
virtual Blitter::PaletteAnimation UsePaletteAnimation()=0
Check if the blitter uses palette animation at all.
virtual void PaletteAnimate(const Palette &palette)=0
Called when the 8bpp palette is changed; you should redraw all pixels on the screen that are equal to...
@ None
No palette animation.
@ Blitter
The blitter takes care of the palette animation.
@ VideoBackend
Palette animation should be done by video backend (8bpp only!).
virtual void PostResize()
Post resize event.
std::optional< std::string_view > Start(const StringList ¶m) override
Start this driver.
CGContextRef cgcontext
Context reference for Quartz subdriver.
uint32_t palette[256]
Colour Palette.
int buffer_depth
Colour depth of used frame buffer.
int window_width
Current window width in pixel.
void CheckPaletteAnim() override
Process any pending palette animation.
std::unique_ptr< uint32_t[]> window_buffer
Colour translation from palette to screen.
NSView * AllocateDrawView() override
Allocate the view to show the game on.
void AllocateBackingStore(bool force=false) override
Resize the window.
void BlitIndexedToView32(int left, int top, int right, int bottom)
This function copies 8bpp pixels from the screen buffer in 32bpp windowed mode.
std::unique_ptr< uint8_t[]> pixel_buffer
used for direct pixel access
void UpdatePalette(uint first_colour, uint num_colours)
Update the palette.
void Stop() override
Stop Cocoa video driver.
void Paint() override
Draw window.
void * GetVideoPointer() override
Get a pointer to the video buffer.
int window_height
Current window height in pixel.
void GameSizeChanged()
Handle a change of the display area.
bool ToggleFullscreen(bool fullscreen) override
Toggle between windowed and full screen mode for cocoa display driver.
void UpdateVideoModes()
Update the video mode.
std::vector< int > GetListOfMonitorRefreshRates() override
Get refresh rates of all connected monitors.
Dimension GetScreenSize() const override
Get the resolution of the main screen.
std::optional< std::string_view > Initialize()
Common driver initialization.
bool refresh_sys_sprites
System sprites need refreshing.
void MainLoop() override
Start the main programme loop when using a cocoa video driver.
OTTD_CocoaWindow * window
Pointer to window object.
OTTD_CocoaView * cocoaview
Pointer to view object.
virtual void ReleaseVideoPointer()
Hand video buffer back to the drawing backend.
VideoDriver_Cocoa(bool uses_hardware_acceleration=false, bool supports_animation_buffer=false)
Create the video driver.
virtual void * GetVideoPointer()=0
Get a pointer to the video buffer.
OTTD_CocoaWindowDelegate * delegate
Window delegate object.
bool IsFullscreen()
Are we in fullscreen mode?
void InputLoop() override
Handle input logic, is CTRL pressed, should we fast-forward, etc.
bool MakeWindow(int width, int height)
Build window and view with a given size.
bool PollEvent() override
Poll and handle a single event from the OS.
void MakeDirty(int left, int top, int width, int height) override
Set dirty a rectangle managed by a cocoa video subdriver.
void PopulateSystemSprites() override
Populate all sprites in cache.
virtual NSView * AllocateDrawView()=0
Allocate the view to show the game on.
bool LockVideoBuffer() override
Lock video buffer for drawing if it isn't already mapped.
void EditBoxLostFocus() override
An edit box lost the input focus.
void ClearSystemSprites() override
Clear all cached sprites.
Rect dirty_rect
Region of the screen that needs redrawing.
void UnlockVideoBuffer() override
Unlock video buffer.
void Stop() override
Stop Cocoa video driver.
bool buffer_locked
Video buffer was locked by the main thread.
virtual void AllocateBackingStore(bool force=false)=0
Resize the window.
Dimension orig_res
Saved window size for non-fullscreen mode.
bool setup
Window is currently being created.
bool ChangeResolution(int w, int h) override
Change the resolution when using a cocoa video driver.
bool AfterBlitterChange() override
Callback invoked after the blitter was changed.
CGColorSpaceRef colour_space
Window colour space.
void MainLoopReal()
Main game loop.
bool fast_forward_key_pressed
The fast-forward key is being pressed.
void Tick()
Give the video-driver a tick.
const bool supports_animation_buffer
Whether this driver supports hardware accelerated animation.
void SleepTillNextTick()
Sleep till the next tick is about to happen.
void StartGameThread()
Start the loop for game-tick.
void StopGameThread()
Stop the loop for the game-tick.
VideoDriver(bool uses_hardware_acceleration=false, bool supports_animation_buffer=false)
Create the video driver.
void UpdateAutoResolution()
Apply resolution auto-detection and clamp to sensible defaults.
const bool uses_hardware_acceleration
Whether hardware acceleration is used or not.
bool is_game_threaded
Whether the game is allowed to use threads; cleared in the driver implementation constructors if requ...
static Palette _local_palette
Current palette to use for drawing.
bool _cocoa_video_started
Is the Cocoa video driver running.
static FVideoDriver_CocoaQuartz iFVideoDriver_CocoaQuartz
Register the cocoa video driver.
static const Dimension _default_resolutions[]
List of common display/window sizes.
static void ClearWindowBuffer(uint32_t *buffer, uint32_t pitch, uint32_t height)
Clear buffer to opaque black.
bool _tab_is_down
Is tab button pressed.
OS interface for the cocoa video driver.
bool CocoaSetupApplication()
Startup the application.
void CocoaExitApplication()
Deregister app delegate.
NSString * OTTDMainLaunchGameEngine
Name of notification observer used to restart the game loop if necessary.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
@ Driver
Driver message facility.
@ Critical
Critical, user should know about this.
bool GetDriverParamBool(const StringList &parm, std::string_view name)
Get a boolean parameter the list of parameters.
std::vector< Dimension > _resolutions
List of resolutions.
Dimension _cur_resolution
The current resolution.
Error reporting related functions.
Factory to 'query' all available blitters.
Types for recording game performance data.
@ Video
Speed of painting drawn video buffer.
Rect BoundingRect(const Rect &r1, const Rect &r2)
Compute the bounding rectangle around two rectangles.
bool IsEmptyRect(const Rect &r)
Check if a rectangle is empty.
ControlInputs _input_pressed
Control inputs that are currently pressed.
Functions related to the gfx engine.
void HandleCtrlChanged()
State of CONTROL key has changed.
bool IsCtrlPressed()
Test if the ctrl key is pressed.
void HandleTextInput(std::string_view str, bool marked=false, std::optional< size_t > caret=std::nullopt, std::optional< size_t > insert_location=std::nullopt, std::optional< size_t > replacement_end=std::nullopt)
Handle text input.
@ Ctrl
Ctrl modifier is pressed.
@ Shift
Shift modifier is pressed.
Subclass of NSView to support mouse awareness and text input.
Delegate for our NSWindow to send ask for quit on close.
Subclass of NSWindow to cater our special needs.
Subclass of OTTD_CocoaView to fix Quartz rendering.
BOOL isOpaque()
Specifies whether the view is opaque.
void updateLayer()
Updates the layer based on driver data.
BOOL wantsUpdateLayer()
Specifies whether the view wants updates for layer.
BOOL acceptsFirstResponder()
Specifies whether the view accepts first responder.
VideoDriver_CocoaQuartz * driver
The driver to fix rendering for.
void viewDidChangeBackingProperties()
Updates members with new values after changes in driver.
Functions related to MacOS support.
Includes of mac os specific headers which contain objective c.
constexpr T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
bool CopyPalette(Palette &local_palette, bool force_copy)
Copy the current palette if the palette was updated.
Functions related to modal progress.
Pseudo random number generator.
ClientSettings _settings_client
The current settings for this game.
Types related to global configuration settings.
Definition of base types and functions in a cross-platform compatible way.
std::vector< std::string > StringList
Type for a list of strings.
Dimensions (a width and height) of a rectangle in 2D.
int first_dirty
The first dirty element.
Specification of a rectangle with absolute coordinates of all edges.
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.