카테고리 없음

[FdF] MiniLibX mlx_init

man 에서 본것처럼 init함수를 써보자

drwxr-xr-x@ 26 kyoulee  staff      832  6 10 11:21 minilibx_macos
drwxr-xr-x@ 13 kyoulee  staff      416 10 26  2019 minilibx_mms_20191025_beta

이 2파일을 make 해준다

(venv) kyoulee@kyouleeui-MacBookAir minilibx_mms_20191025_beta % make
swiftc -I. -parse-as-library -c mlx_image.swift -o mlx_image.swiftmodule -emit-module -module-name mlx_image -module-link-name mlx_image
swiftc -I. -parse-as-library -c mlx_window.swift -o mlx_window.swiftmodule -emit-module -module-name mlx_window -module-link-name mlx_window
mlx_window.swift:25:26: warning: initialization of 'UnsafeMutableRawPointer' results in a dangling pointer
      eventParams.append(UnsafeMutableRawPointer(&keyrepeat)) /// dummy address here, null not needed
                         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
mlx_window.swift:25:50: note: implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'
      eventParams.append(UnsafeMutableRawPointer(&keyrepeat)) /// dummy address here, null not needed
                                                 ^~~~~~~~~~
mlx_window.swift:25:50: note: use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope
      eventParams.append(UnsafeMutableRawPointer(&keyrepeat)) /// dummy address here, null not needed
                                                 ^
swiftc -I. -parse-as-library -c mlx_init.swift -o mlx_init.swiftmodule -emit-module -module-name mlx_init -module-link-name mlx_init
mlx_init.swift:43:14: warning: initialization of 'UnsafeMutableRawPointer' results in a dangling pointer
        loopParam = UnsafeMutableRawPointer(&inLoop)  /// dummy addr init
                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
mlx_init.swift:43:38: note: implicit argument conversion from 'Bool' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'
        loopParam = UnsafeMutableRawPointer(&inLoop)  /// dummy addr init
                                            ^~~~~~~
mlx_init.swift:43:38: note: use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope
        loopParam = UnsafeMutableRawPointer(&inLoop)  /// dummy addr init
                                            ^
swiftc -I. -parse-as-library -c interface.swift -o interface.o
interface.swift:248:41: error: cannot convert value of type 'UInt32' to expected argument type 'boolean_t' (aka 'Int32')
        CGAssociateMouseAndMouseCursorPosition(UInt32(1))
                                               ^
                                               boolean_t( )

에러가 낫다 mac m1 쓰는데 abi 에 Unt32가 읍나?

들어가 수정해준다

(venv) kyoulee@kyouleeui-MacBookAir minilibx_mms_20191025_beta % vi interface.swift


.... 위에 생략 ....
237 @_cdecl("mlx_mouse_move")
238 public func mlx_mouse_move_swift(_ winptr:UnsafeRawPointer, _ x:Int32, _ y:Int32) -> Int32
239 {
240     let win:MlxWin = _mlx_bridge(ptr:winptr)
241     let frame = win.getWinEFrame()
242 /// let sframe = win.getScreenFrame()
243     var pt = CGPoint()
244     pt.x = frame.origin.x + CGFloat(x)
245 /// pt.y = sframe.size.y - frame.size.y - frame.origin.y + 1 + y
246     pt.y = frame.origin.y + frame.size.height - 1.0 - CGFloat(y)
247     CGWarpMouseCursorPosition(pt)
248     CGAssociateMouseAndMouseCursorPosition(boolean_t(1)) ///<-- 요기 수정
249     return Int32(0);
250 }
251
.... 이하 생략 ....

(venv) kyoulee@kyouleeui-MacBookAir minilibx_mms_20191025_beta % make

잘된다

# libmlx.a

(venv) kyoulee@kyouleeui-MacBookAir run % ar -t ./libmlx.a
__.SYMDEF SORTED
mlx_shaders.o
mlx_new_window.o
mlx_init_loop.o
mlx_new_image.o
mlx_xpm.o
mlx_int_str_to_wordtab.o

(venv) kyoulee@kyouleeui-MacBookAir run % nm -g ./libmlx.a

./win_os/libmlx.a(mlx_shaders.o):
                 U ___stderrp
0000000000000000 T _display_log
                 U _fputs
                 U _free
                 U _fwrite
                 U _glAttachShader
                 U _glCompileShader
                 U _glCreateProgram
                 U _glCreateShader
                 U _glFlush
                 U _glGetProgramInfoLog
                 U _glGetProgramiv
                 U _glGetShaderInfoLog
                 U _glGetShaderiv
                 U _glLinkProgram
                 U _glShaderSource
                 U _malloc
0000000000000824 T _mlx_shaders
0000000000000598 T _mlx_shaders_font
000000000000030c T _mlx_shaders_image
0000000000000080 T _mlx_shaders_pixel
                 U _strdup
                 U _strlen

./win_os/libmlx.a(mlx_new_window.o):
0000000000001ea0 S _OBJC_CLASS_$_MlxWin
                 U _OBJC_CLASS_$_NSNotificationCenter
                 U _OBJC_CLASS_$_NSOpenGLContext
                 U _OBJC_CLASS_$_NSOpenGLPixelFormat
                 U _OBJC_CLASS_$_NSOpenGLView
                 U _OBJC_CLASS_$_NSString
                 U _OBJC_CLASS_$_NSWindow
0000000000001e50 S _OBJC_CLASS_$_NSWindowEvent
00000000000024e8 S _OBJC_IVAR_$_MlxWin.ctx
00000000000024d4 S _OBJC_IVAR_$_MlxWin.glsl
00000000000024ec S _OBJC_IVAR_$_MlxWin.openglwin
00000000000024e4 S _OBJC_IVAR_$_MlxWin.pixel_nb
00000000000024dc S _OBJC_IVAR_$_MlxWin.pixel_texture
00000000000024d8 S _OBJC_IVAR_$_MlxWin.pixel_vbuffer
00000000000024e0 S _OBJC_IVAR_$_MlxWin.pixtexbuff
00000000000024cc S _OBJC_IVAR_$_MlxWin.size_x
00000000000024d0 S _OBJC_IVAR_$_MlxWin.size_y
00000000000024c8 S _OBJC_IVAR_$_MlxWin.win
00000000000024b0 S _OBJC_IVAR_$_NSWindowEvent.event_funct
00000000000024b4 S _OBJC_IVAR_$_NSWindowEvent.event_param
00000000000024bc S _OBJC_IVAR_$_NSWindowEvent.keyflag
00000000000024b8 S _OBJC_IVAR_$_NSWindowEvent.keyrepeat
00000000000024c0 S _OBJC_IVAR_$_NSWindowEvent.size_x
00000000000024c4 S _OBJC_IVAR_$_NSWindowEvent.size_y
0000000000001ec8 S _OBJC_METACLASS_$_MlxWin
                 U _OBJC_METACLASS_$_NSObject
                 U _OBJC_METACLASS_$_NSOpenGLView
                 U _OBJC_METACLASS_$_NSWindow
0000000000001e78 S _OBJC_METACLASS_$_NSWindowEvent
                 U ___CFConstantStringClassReference
                 U ___stack_chk_fail
                 U ___stack_chk_guard
                 U __objc_empty_cache
                 U _free
0000000000000000 T _get_mouse_button
                 U _glActiveTexture
                 U _glBindBuffer
                 U _glBindTexture
                 U _glBlendEquation
                 U _glBlendFunc
                 U _glBufferData
                 U _glClear
                 U _glClearColor
                 U _glDeleteBuffers
                 U _glDeleteProgram
                 U _glDeleteShader
                 U _glDeleteTextures
                 U _glDisable
                 U _glDisableVertexAttribArray
                 U _glDrawArrays
                 U _glEnable
                 U _glEnableVertexAttribArray
                 U _glFlush
                 U _glGenBuffers
                 U _glGenTextures
                 U _glGetAttribLocation
                 U _glGetUniformLocation
                 U _glTexImage2D
                 U _glTexParameteri
                 U _glTexSubImage2D
                 U _glUniform1i
                 U _glUniform2f
                 U _glUniform4fv
                 U _glUseProgram
                 U _glVertexAttribPointer
                 U _malloc
0000000000001c00 T _mlx_clear_window
0000000000001d38 T _mlx_destroy_window
0000000000001cb0 T _mlx_do_key_autorepeatoff
0000000000001cf4 T _mlx_do_key_autorepeaton
                 U _mlx_do_sync
0000000000001c48 T _mlx_expose_hook
0000000000001c9c T _mlx_hook
0000000000001c64 T _mlx_key_hook
0000000000001c80 T _mlx_mouse_hook
0000000000001af8 T _mlx_new_window
                 U _mlx_shaders
                 U _objc_alloc
                 U _objc_msgSend
                 U _objc_msgSendSuper2
                 U _objc_release
0000000000001e38 D _pfa_attrs

./win_os/libmlx.a(mlx_init_loop.o):
                 U _CFRunLoopAddObserver
                 U _CFRunLoopAddTimer
                 U _CFRunLoopGetMain
                 U _CFRunLoopObserverCreate
                 U _CFRunLoopTimerCreate
                 U _CFRunLoopTimerInvalidate
                 U _NSApp
                 U _NSDefaultRunLoopMode
                 U _OBJC_CLASS_$_NSApplication
                 U _OBJC_CLASS_$_NSDate
                 U _OBJC_CLASS_$_NSRunningApplication
                 U _TransformProcessType
                 U ___CFConstantStringClassReference
                 U ___stack_chk_fail
                 U ___stack_chk_guard
0000000000000008 T _do_loop_flush
0000000000000000 T _do_loop_hook2
                 U _glFlush
                 U _kCFAllocatorDefault
                 U _kCFRunLoopCommonModes
                 U _malloc
0000000000000450 T _mlx_do_sync
0000000000000084 T _mlx_init
0000000000000370 T _mlx_int_loop_once
0000000000000274 T _mlx_loop
00000000000005b0 T _mlx_loop_hook
                 U _mlx_new_image
0000000000000300 T _mlx_pixel_put
                 U _objc_msgSend
                 U _objc_release
                 U _usleep

./win_os/libmlx.a(mlx_new_image.o):
0000000000000098 T _add_img_to_ctx
                 U _bzero
                 U _free
                 U _glBindBuffer
                 U _glBindTexture
                 U _glBufferData
                 U _glDeleteBuffers
                 U _glDeleteTextures
                 U _glGenBuffers
                 U _glGenTextures
                 U _glTexImage2D
                 U _glTexParameteri
                 U _malloc
0000000000000398 T _mlx_destroy_image
0000000000000294 T _mlx_get_color_value
0000000000000274 T _mlx_get_data_addr
0000000000000000 T _mlx_new_image
00000000000001ac T _mlx_put_image_to_window
000000000000029c T _mlx_string_put
                 U _objc_msgSend

./win_os/libmlx.a(mlx_xpm.o):
                 U ___stack_chk_fail
                 U ___stack_chk_guard
                 U _atoi
                 U _close
                 U _free
                 U _lseek
                 U _malloc
                 U _memset
0000000000002540 D _mlx_col_name
                 U _mlx_destroy_image
00000000000006bc T _mlx_int_file_get_rid_comment
0000000000000168 T _mlx_int_get_col_name
0000000000000000 T _mlx_int_get_line
0000000000000188 T _mlx_int_get_text_rgb
000000000000026c T _mlx_int_parse_xpm
00000000000000cc T _mlx_int_static_line
                 U _mlx_int_str_str
                 U _mlx_int_str_str_cote
                 U _mlx_int_str_to_wordtab
0000000000000264 T _mlx_int_xpm_set_pixel
                 U _mlx_new_image
00000000000007cc T _mlx_xpm_file_to_image
00000000000008cc T _mlx_xpm_to_image
                 U _mmap
                 U _munmap
                 U _open
                 U _snprintf
                 U _strcasecmp
                 U _strcmp
                 U _strlcpy
                 U _strlen
                 U _strtol

./win_os/libmlx.a(mlx_int_str_to_wordtab.o):
                 U _malloc
0000000000000000 T _mlx_int_str_str
000000000000009c T _mlx_int_str_str_cote
000000000000014c T _mlx_int_str_to_wordtab
                 U _strlen

# libmlx.dylib

(venv) kyoulee@kyouleeui-MacBookAir run % nm -g ./libmlx.dylib
.... 위에 생략 ....
00000000000032a4 T _mlx_clear_window
0000000000040360 D _mlx_col_name
0000000000003ea8 T _mlx_destroy_image
0000000000003e20 T _mlx_destroy_window
0000000000002e38 T _mlx_do_key_autorepeatoff
000000000000314c T _mlx_do_key_autorepeaton
0000000000003b10 T _mlx_do_sync
0000000000002cf0 T _mlx_expose_hook
00000000000033dc T _mlx_get_color_value
0000000000003648 T _mlx_get_data_addr
0000000000002b8c T _mlx_hook
00000000000024b4 T _mlx_init
0000000000018084 T _mlx_int_file_get_rid_comment
00000000000195f8 T _mlx_int_fill
00000000000176f8 T _mlx_int_get_col_name
000000000001749c T _mlx_int_get_line
000000000001774c T _mlx_int_get_text_rgb
0000000000019304 T _mlx_int_parse_png
00000000000178d8 T _mlx_int_parse_xpm
00000000000175f4 T _mlx_int_static_line
0000000000016f78 T _mlx_int_str_str
000000000001707c T _mlx_int_str_str_cote
00000000000171bc T _mlx_int_str_to_wordtab
00000000000178a4 T _mlx_int_xpm_set_pixel
0000000000002a3c T _mlx_key_hook
0000000000002534 T _mlx_loop
0000000000002d98 T _mlx_loop_hook
0000000000004288 T _mlx_mouse_get_pos
0000000000003f04 T _mlx_mouse_hide
0000000000002ae4 T _mlx_mouse_hook
0000000000003f84 T _mlx_mouse_move
0000000000003f44 T _mlx_mouse_show
0000000000003414 T _mlx_new_image
00000000000026b0 T _mlx_new_window
0000000000003328 T _mlx_pixel_put
00000000000194c8 T _mlx_png_file_to_image
0000000000003890 T _mlx_put_image_to_window
0000000000003974 T _mlx_put_image_to_window_scale
00000000000197cc T _mlx_string_put
00000000000181ac T _mlx_xpm_file_to_image
00000000000182bc T _mlx_xpm_to_image
.... 밑에 생략 ....

메인파일을 만들어 보자 

# main.c

#include <stdio.h>  // printf()
#include <stdlib.h> // exit()
#include <mlx.h>

int main(void)
{
	void *mlx_ptr;

	mlx_ptr = mlx_init();

	return (0);
}

파일 정리는 이렇게 해준다

(venv) kyoulee@kyouleeui-MacBookAir run % tree
.
├── include
│   └── mlx.h
├── libmlx.a
├── libmlx.dylib
└── main.c

실행 파일 만들기!

(venv) kyoulee@kyouleeui-MacBookAir run % cc main.c -L ./ -lmlx -framework OpenGL -framework AppKit -I include

<-- 이상한점 -->

왜인진 모르겟지만 실행파일과 dylib를 정해진 위치 3곳에 두어야 한다 (실행파일 위치, /usr/lib/ , /usr/local/lib/, )

지정 위치를 선언하는 방법을 모르겟다(cc 에 있는 무언가가 있을듯 한데)

(venv) kyoulee@kyouleeui-MacBookAir run % ./a.out
dyld[34318]: Library not loaded: libmlx.dylib
  Referenced from: /Users/kyoulee/Documents/FdF/run/a.out
  Reason: tried: 'libmlx.dylib' (no such file), '/usr/local/lib/libmlx.dylib' (no such file), '/usr/lib/libmlx.dylib' (no such file), '/Users/kyoulee/Documents/FdF/run/libmlx.dylib' (no such file), '/usr/local/lib/libmlx.dylib' (no such file), '/usr/lib/libmlx.dylib' (no such file)

실행 해보면 잘된다!

하지만 아무것도 보이지않는것이 함정!

 

 

<bonus>

코드 분석 필요한 거만

# mlx_int.h

#define FONT_WIDTH	10
#define	FONT_HEIGHT	20

typedef struct	mlx_img_list_s
{
  int			width;
  int			height;
  char			*buffer;
  GLfloat		vertexes[8];
  struct mlx_img_list_s	*next;
} mlx_img_list_t;

typedef struct	mlx_win_list_s
{
  void			*winid;
  mlx_img_ctx_t		*img_list;
  int			nb_flush;
  int			pixmgt;
  struct mlx_win_list_s	*next;
} mlx_win_list_t;

typedef struct		mlx_ptr_s
{
  void			*appid;
  mlx_win_list_t	*win_list;
  mlx_img_list_t	*img_list;
  void			(*loop_hook)(void *);
  void			*loop_hook_data;
  void			*loop_timer;
  mlx_img_list_t	*font;
  int			main_loop_active;
} mlx_ptr_t;

 

# mlx_init_loop.m

 

void *mlx_init()
{
  mlx_ptr_t	*new_mlx;
  int		bidon;
  int		i;

  if ((new_mlx = malloc(sizeof(*new_mlx))) == NULL)
    return ((void *)0);
  new_mlx->win_list = NULL;
  new_mlx->img_list = NULL;
  new_mlx->loop_hook = NULL;
  new_mlx->loop_hook_data = NULL;
  new_mlx->main_loop_active = 0;

  new_mlx->appid = [NSApplication sharedApplication];

  // super magic trick to detach app from terminal, get menubar & key input events
  for (NSRunningApplication * app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.finder"])
    {
      [app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
      break;
    }
  usleep(100000);
  ProcessSerialNumber psn = { 0, kCurrentProcess };
  (void) TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  usleep(100000);
  [[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateIgnoringOtherApps];

  // load font
  new_mlx->font = mlx_new_image(new_mlx, (FONT_WIDTH+2)*95, FONT_HEIGHT);
  i = 0;
  while (i < 4*(FONT_WIDTH+2)*95*FONT_HEIGHT)
    {
      new_mlx->font->buffer[i+0] = font_atlas.pixel_data[i+2];
      new_mlx->font->buffer[i+1] = font_atlas.pixel_data[i+1];
      new_mlx->font->buffer[i+2] = font_atlas.pixel_data[i+0];
      ((unsigned char *)new_mlx->font->buffer)[i+3] = 0xFF-font_atlas.pixel_data[i+3];
      i += 4;
    }

  new_mlx->font->vertexes[2] = FONT_WIDTH;
  new_mlx->font->vertexes[4] = FONT_WIDTH;
  new_mlx->font->vertexes[5] = -FONT_HEIGHT-1;
  new_mlx->font->vertexes[7] = -FONT_HEIGHT-1;

  return ((void *)new_mlx);
}

 

코드를 분석해보자

일단 코코아다 그 코코아 치면 코코아톡 노마드꺼(웹코딩)만 나와 정보를 구하기가 힘들다

https://en.wikibooks.org/wiki/Programming_Mac_OS_X_with_Cocoa_for_Beginners_2nd_Edition

 

Programming Mac OS X with Cocoa for Beginners 2nd Edition - Wikibooks, open books for an open world

This book aims to provide beginners with an introduction to the programming of Mac OS X Apps using Cocoa, and XCode, the free developer tools provided by Apple, Inc. Examples of Mac apps are: iTunes, Safari, Mail, iCal, Address Book, Microsoft Word, Micros

en.wikibooks.org

https://www.youtube.com/watch?v=X_MJd8wqTBM&list=PLE83F832121568D36&index=1 

코코아 코딩을 공부하기 좋은거 같다