-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathUnityJS.mm
More file actions
1343 lines (974 loc) · 36.4 KB
/
UnityJS.mm
File metadata and controls
1343 lines (974 loc) · 36.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2011 Keijiro Takahashi
* Copyright (C) 2012 GREE, Inc.
* Copyright (C) 2017 by Don Hopkins, Ground Up Software.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
////////////////////////////////////////////////////////////////////////
// UnityJS.mm for OSX and iOS
////////////////////////////////////////////////////////////////////////
// Includes
#if TARGET_OS_OSX
// OSX
#if false
// Old but buggy.
#define UNITYJS_WEBVIEW 1
#define UNITYJS_WKWEBVIEW 0
#else
// New but no image.
#define UNITYJS_WEBVIEW 0
#define UNITYJS_WKWEBVIEW 1
#endif
#import <Carbon/Carbon.h>
#import <AppKit/AppKit.h>
#import <WebKit/WebKit.h>
#import <OpenGL/gl.h>
#import <Metal/Metal.h>
#if UNITY_JS_WKWEBVIEW
#import <WebKit/WKWebsiteDataStore.h>
#import <WebKit/WKSnapshotConfiguration.h>
#endif
#else
// iOS
#define UNITYJS_WEBVIEW 0
#define UNITYJS_WKWEBVIEW 1
#import <OpenGLES/ES2/gl.h>
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
#endif
#include "IUnityGraphics.h"
#include "IUnityGraphicsMetal.h"
////////////////////////////////////////////////////////////////////////
// Declarations
@class CUnityJSPlugin;
typedef void (*UnityRenderEventFunc)(int eventId);
extern "C" {
void _CUnityJSPlugin_SetUnitySendMessageCallback(void *unitySendMessageCallback);
void *_CUnityJSPlugin_Init(BOOL transparent);
void _CUnityJSPlugin_Destroy(void *instance);
void _CUnityJSPlugin_SetRect(void *instance, int width, int height);
void _CUnityJSPlugin_SetVisibility(void *instance, BOOL visibility);
void _CUnityJSPlugin_LoadURL(void *instance, const char *url);
void _CUnityJSPlugin_EvaluateJS(void *instance, const char *js);
void _CUnityJSPlugin_EvaluateJSReturnResult(void *instance, const char *js);
BOOL _CUnityJSPlugin_CanGoBack(void *instance);
BOOL _CUnityJSPlugin_CanGoForward(void *instance);
void _CUnityJSPlugin_GoBack(void *instance);
void _CUnityJSPlugin_GoForward(void *instance);
const char *_CUnityJSPlugin_GetPluginID(void *instance);
void _CUnityJSPlugin_RenderIntoTextureSetup(void *instance, int width, int height);
long _CUnityJSPlugin_GetRenderTextureHandle(void *instance);
int _CUnityJSPlugin_GetRenderTextureWidth(void *instance);
int _CUnityJSPlugin_GetRenderTextureHeight(void *instance);
UnityRenderEventFunc _CUnityJSPlugin_GetRenderEventFunc();
void _CUnityJSPlugin_UnityRenderEvent(int eventId);
void _CUnityJSPlugin_FlushCaches(void *instance);
#if TARGET_OS_OSX
void _CUnityJSPlugin_Update(void *instance, int x, int y, float deltaY, BOOL buttonDown, BOOL buttonPress, BOOL buttonRelease, BOOL keyPress, unsigned char keyCode, const char *keyChars);
#else
UIViewController *UnityGetGLViewController();
void UnitySendMessage(const char *, const char *, const char *);
#endif
}
////////////////////////////////////////////////////////////////////////
// CUnityJSPlugin
@interface CUnityJSPlugin :
#if UNITYJS_WEBVIEW
NSObject
#endif
#if UNITYJS_WKWEBVIEW
NSObject<WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler>
#endif
{
#if UNITYJS_WEBVIEW
WebView *webView;
#endif
#if UNITYJS_WKWEBVIEW
WKWebView *webView;
#endif
NSString *pluginID;
bool renderIntoTexture;
GLuint renderTextureHandle;
int renderTextureWidth;
int renderTextureHeight;
BOOL confirmPanelResult;
NSString *textInputPanelResult;
#if TARGET_OS_OSX
NSBitmapImageRep *renderTextureBitmap;
#endif
}
@end
////////////////////////////////////////////////////////////////////////
// Globals
static void UNITY_INTERFACE_API OnGraphicsDeviceEvent(UnityGfxDeviceEventType eventType);
static IUnityInterfaces *unityInterfaces;
static IUnityGraphics *unityGraphics;
static IUnityGraphicsMetal *unityGraphicsMetal;
static UnityGfxRenderer unityRendererType = kUnityGfxRendererNull;
typedef void (*UnitySendMessageCallback)(const char *target, const char *method, const char *message);
static UnitySendMessageCallback unitySendMessageCallback;
static int currentPluginID = 0;
static NSMutableDictionary *plugins = nil;
////////////////////////////////////////////////////////////////////////
// Unity Extension Interface
// These are called by Unity when the plugin loads and unloads.
// Called by Unity when the plugin loads.
// Caches interface pointers, hooks up the other Unity callbacks and initializes.
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginLoad(
IUnityInterfaces *unityInterfaces0)
{
unityInterfaces = unityInterfaces0;
//NSLog(@"CUnityJSPlugin: UnityPluginLoad: unityInterfaces: %ld", (long)unityInterfaces);
unityGraphics = unityInterfaces->Get<IUnityGraphics>();
//NSLog(@"CUnityJSPlugin: UnityPluginLoad: unityGraphics: %ld", (long)unityGraphics);
unityGraphicsMetal = unityInterfaces->Get<IUnityGraphicsMetal>();
//NSLog(@"CUnityJSPlugin: UnityPluginLoad: unityGraphicsMetal: %ld", (long)unityGraphicsMetal);
unityGraphics->RegisterDeviceEventCallback(OnGraphicsDeviceEvent);
OnGraphicsDeviceEvent(kUnityGfxDeviceEventInitialize);
}
// Called by Unity when the plugin unloads.
// Unregisters Unity callbacks.
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginUnload()
{
//NSLog(@"CUnityJSPlugin: UnityPluginUnload");
unityGraphics->UnregisterDeviceEventCallback(OnGraphicsDeviceEvent);
}
// Called by Unity to track graphics device state.
// Caches and clears the renderer type.
static void UNITY_INTERFACE_API OnGraphicsDeviceEvent(
UnityGfxDeviceEventType eventType)
{
//NSLog(@"CUnityJSPlugin: OnGraphicsDeviceEvent: eventType: %d", (int)eventType);
switch (eventType) {
case kUnityGfxDeviceEventInitialize: {
currentPluginID = 0;
unityRendererType = unityGraphics->GetRenderer();
//NSLog(@"CUnityJSPlugin: OnGraphicsDeviceEvent: kUnityGfxDeviceEventInitialize: unityRendererType: %d", (int)unityRendererType);
// TODO: user initialization code
break;
}
case kUnityGfxDeviceEventShutdown: {
unityRendererType = kUnityGfxRendererNull;
//NSLog(@"CUnityJSPlugin: OnGraphicsDeviceEvent: kUnityGfxDeviceEventShutdown: unityRendererType: %d", (int)unityRendererType);
for (NSString *key in [plugins allKeys]) {
[plugins removeObjectForKey:key];
}
break;
}
case kUnityGfxDeviceEventBeforeReset: {
// TODO: user Direct3D 9 code
break;
}
case kUnityGfxDeviceEventAfterReset: {
// TODO: user Direct3D 9 code
break;
}
};
}
@implementation CUnityJSPlugin
- (id)init:(BOOL)transparent
{
self = [super init];
pluginID =
[NSString stringWithFormat:@"%i", ++currentPluginID]; // never 0
if (plugins == nil) {
plugins = [[NSMutableDictionary alloc] init];
}
@synchronized(plugins) {
plugins[pluginID] = self;
}
#if UNITYJS_WEBVIEW
#if TARGET_OS_OSX
// OSX WebView
webView =
[[WebView alloc]
initWithFrame:
NSMakeRect(0, 0, 256, 256)];
webView.hidden = YES;
[webView setDrawsBackground:!transparent];
[webView setFrameLoadDelegate:(id)self];
[webView setPolicyDelegate:(id)self];
//NSLog(@"CUnityJSPlugin: init: Created WebView: %@", webView);
#else
// iOS WebView: Depricated
#endif
#endif
#if UNITYJS_WKWEBVIEW
// OSX and iOS WkWebView
WKWebViewConfiguration *configuration =
[[WKWebViewConfiguration alloc] init];
WKUserContentController *userContentController =
[[WKUserContentController alloc] init];
[userContentController
addScriptMessageHandler:self
name:@"bridge"];
[userContentController
addScriptMessageHandler:self
name:@"log"];
NSString *source =
@"window.console.logOld = window.console.log; window.console.log = function(arg) { window.webkit.messageHandlers.log.postMessage(Array.prototype.slice.call(arguments).join(' ')); window.console.logOld.apply(this, arguments); };";
WKUserScript *userScript =
[[WKUserScript alloc]
initWithSource:source
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:YES];
[userContentController addUserScript:userScript];
configuration.userContentController = userContentController;
#if TARGET_OS_OSX
NSRect frame = NSMakeRect(0, 0, 256, 256);
#else
CGRect frame = CGRectMake(0, 0, 256, 256);
#endif
webView =
[[WKWebView alloc]
initWithFrame:frame
configuration:configuration];
webView.UIDelegate = self;
webView.navigationDelegate = self;
#if TARGET_OS_OSX
webView.hidden = NO;
[webView.configuration.preferences
setValue:@TRUE
forKey:@"allowFileAccessFromFileURLs"];
#else
webView.hidden = YES;
if (transparent) {
webView.opaque = NO;
webView.backgroundColor = [UIColor clearColor];
}
UIView *view = UnityGetGLViewController().view;
[view addSubview:webView];
#endif
#endif
return self;
}
- (void)dealloc
{
//NSLog(@"CUnityJSPlugin: dealloc pluginID %@ webView %@", pluginID, webView);
if (plugins != nil) {
@synchronized(plugins) {
[plugins removeObjectForKey:pluginID];
}
}
[webView removeFromSuperview];
webView = nil;
}
- (NSString *)URLDecode:(NSString *)stringToDecode
{
NSString *result = [stringToDecode stringByReplacingOccurrencesOfString:@"+" withString:@" "];
result = [result stringByRemovingPercentEncoding];
return result;
}
- (void)setVisibility:(BOOL)visibility
{
if (webView == nil) {
return;
}
//webView.hidden = visibility ? NO : YES;
}
- (void)setRect:(int)width height:(int)height
{
if (webView == nil) {
return;
}
//NSLog(@"CUnityJSPlugin: setRect: pluginID: %@, width: %d height: %d", pluginID, width, height);
webView.frame =
#if TARGET_OS_OSX
NSMakeRect(0, 0, width, height);
#else
CGRectMake(0, 0, width, height);
#endif
}
- (void)loadURL:(const char *)url
{
//NSLog(@"CUnityJSPlugin: loadURL: pluginID: %@ url: %s", pluginID, url);
if (webView == nil) {
return;
}
NSString *urlStr = [NSString stringWithUTF8String:url];
NSURL *nsurl = [NSURL URLWithString:urlStr];
#if UNITYJS_WEBVIEW
NSURLRequest *request = [NSURLRequest requestWithURL:nsurl];
[[webView mainFrame] loadRequest:request];
#endif
#if UNITYJS_WKWEBVIEW
if ([urlStr hasPrefix:@"file:"]) {
// Restricting access to the directory of the URL unfortunately doesn't enable following symlinks out of the sub-tree.
//NSURL *top = [NSURL URLWithString:[urlStr stringByDeletingLastPathComponent]];
// So we allow access to the entire file system, since this is a trusted web browser, and there are many legitimate reasons to access other files.
NSURL *top = [NSURL URLWithString:@"file://"];
[webView loadFileURL:nsurl allowingReadAccessToURL:top];
} else {
NSURLRequest *request = [NSURLRequest requestWithURL:nsurl];
[webView loadRequest:request];
}
#endif
}
- (void)evaluateJS:(const char *)js
{
//NSLog(@"CUnityJSPlugin: evaluateJS: pluginID: %@ js: %s", pluginID, js);
if (webView == nil) {
return;
}
NSString *jsStr = [NSString stringWithUTF8String:js];
#if UNITYJS_WEBVIEW
[webView stringByEvaluatingJavaScriptFromString:jsStr];
#endif
#if UNITYJS_WKWEBVIEW
[webView evaluateJavaScript:jsStr completionHandler:^(NSString *result, NSError *error) {
//NSLog(@"CUnityJSPlugin: evaluateJS: completion: result: %@ error: %@", result, error);
}];
#endif
}
- (void)evaluateJSReturnResult:(const char *)js
{
//NSLog(@"CUnityJSPlugin: evaluateJSReturnResult: pluginID: %@ js: %s", pluginID, js);
if (webView == nil) {
return;
}
NSString *jsStr = [NSString stringWithUTF8String:js];
#if UNITYJS_WEBVIEW
NSString *result = [webView stringByEvaluatingJavaScriptFromString:jsStr];
[self
unitySendMessage:@"ResultFromJS"
data:result];
#endif
#if UNITYJS_WKWEBVIEW
[webView evaluateJavaScript:jsStr completionHandler:^(NSString *result, NSError *error) {
//NSLog(@"CUnityJSPlugin: evaluateJSReturnResult: completion: result: %@ error: %@", result, error);
[self
unitySendMessage:@"ResultFromJS"
data:result];
}];
#endif
}
- (void)unitySendMessage:(NSString *)method
data:(NSString *)data
{
if (unitySendMessageCallback == nil) {
//NSLog(@"CUnityJSPlugin: unitySendMessage: called without unitySendMessageCallback");
return;
}
@autoreleasepool {
unitySendMessageCallback(
[pluginID UTF8String],
[method UTF8String],
[data UTF8String]);
}
}
- (BOOL)canGoBack
{
if (webView == nil) {
return false;
}
return [webView canGoBack];
}
- (BOOL)canGoForward
{
if (webView == nil) {
return false;
}
return [webView canGoForward];
}
- (void)goBack
{
if (webView == nil) {
return;
}
[webView goBack];
}
- (void)goForward
{
if (webView == nil) {
return;
}
[webView goForward];
}
- (NSString *)getPluginID
{
return pluginID;
}
- (void)renderIntoTextureSetup:(int)width height:(int)height
{
#if TARGET_OS_OSX
#if false
bool resetBitmap =
(bitmap == nil) ||
(renderTextureHandle == 0) ||
(renderTextureWidth != width) ||
(renderTextureHeight != height);
renderIntoTexture = true;
renderTextureWidth = width;
renderTextureHeight = height;
if (resetBitmap) {
bitmap = nil;
[self setRect:renderTextureWidth height:renderTextureHeight];
}
NSRect renderTextureRect =
NSMakeRect(0, 0, renderTextureWidth, renderTextureHeight);
if (bitmap == nil) {
bitmap =
[webView
bitmapImageRepForCachingDisplayInRect:renderTextureRect];
}
memset([bitmap bitmapData], 0, [bitmap bytesPerRow] * [bitmap pixelsHigh]);
[webView
cacheDisplayInRect:renderTextureRect
toBitmapImageRep:bitmap];
#else
renderTextureWidth = width;
renderTextureHeight = height;
renderTextureBitmap = nil;
if (![[webView class] respondsToSelector:@selector(takeSnapshotWithConfiguration:completionHandler:)]) {
//NSLog(@"CUnityJSPlugin: renderIntoTextureSetup: webView %@ does not respond to selector takeSnapshotWithConfiguration:completionHandler", webView);
} else {
[webView takeSnapshotWithConfiguration:nil
completionHandler:^(NSImage *snapshotImage, NSError *error) {
if (error) {
NSLog(@"CUnityJSPlugin: renderIntoTextureSetup: takeSnapshotWithConfiguration: ERROR: %@ renderTextureWidth: %d renderTextureHeight: %d unityRendererType: %d", error, self->renderTextureWidth, self->renderTextureHeight, (int)unityRendererType);
} else {
NSSize imageSize = [snapshotImage size];
[snapshotImage lockFocus];
self->renderTextureBitmap =
[[NSBitmapImageRep alloc]
initWithFocusedViewRect:
NSMakeRect(0.0, 0.0, imageSize.width, imageSize.height)];
[snapshotImage unlockFocus];
self->renderIntoTexture = true;
}
}];
}
#endif
//NSLog(@"CUnityJSPlugin: renderIntoTextureSetup: renderTextureWidth: %d renderTextureHeight: %d unityRendererType: %d", renderTextureWidth, renderTextureHeight, (int)unityRendererType);
#endif
}
- (long)getRenderTextureHandle
{
return (long)renderTextureHandle;
}
- (int)getRenderTextureWidth
{
return renderTextureWidth;
}
- (int)getRenderTextureHeight
{
return renderTextureHeight;
}
+ (void)renderUpdateWebViewPlugins
{
//NSLog(@"CUnityJSPlugin: renderUpdateWebViewPlugins");
if ((plugins == nil) ||
([plugins count] == 0)) {
return;
}
@synchronized(plugins) {
for (NSString *key in plugins) {
CUnityJSPlugin *plugin = (CUnityJSPlugin *)plugins[key];
[plugin renderUpdate];
}
}
}
- (void)renderUpdate
{
//NSLog(@"CUnityJSPlugin: renderUpdate: pluginID: %@ renderIntoTexture: %d unityRendererType: %d", pluginID, renderIntoTexture, unityRendererType);
if (!renderIntoTexture) {
return;
}
//NSLog(@"CUnityJSPlugin: renderUpdate: pluginID: %@ renderIntoTexture unityRendererType: %d", pluginID, unityRendererType);
renderIntoTexture = false;
switch (unityRendererType) {
case kUnityGfxRendererOpenGLCore:
[self renderUpdateOpenGLCore];
break;
case kUnityGfxRendererOpenGLES20:
[self renderUpdateOpenGLES20];
break;
case kUnityGfxRendererOpenGLES30:
[self renderUpdateOpenGLES30];
break;
case kUnityGfxRendererMetal:
[self renderUpdateMetal];
break;
default:
NSLog(@"CUnityJSPlugin: renderUpdate: pluginID: %@ unknown unityRendererType: %d", pluginID, unityRendererType);
break;
}
}
- (void)renderUpdateOpenGLCore
{
#if TARGET_OS_OSX
//NSLog(@"CUnityJSPlugin: renderUpdateOpenGLCore: pluginID: %@", pluginID);
if (renderTextureHandle == 0) {
glGenTextures(1, &renderTextureHandle);
glBindTexture(GL_TEXTURE_2D, renderTextureHandle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, renderTextureWidth, renderTextureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glBindTexture(GL_TEXTURE_2D, renderTextureHandle);
//NSLog(@"CUnityJSPlugin: renderUpdateOpenGLCore: pluginID: %@ created renderTextureHandle: %d width: %d height: %d", pluginID, renderTextureHandle, renderTextureWidth, renderTextureHeight);
}
int samplesPerPixel = (int)[renderTextureBitmap samplesPerPixel];
int rowLength = 0;
int unpackAlign = 0;
glGetIntegerv(GL_UNPACK_ROW_LENGTH, &rowLength);
glGetIntegerv(GL_UNPACK_ALIGNMENT, &unpackAlign);
glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint)[renderTextureBitmap bytesPerRow] / samplesPerPixel);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D, renderTextureHandle);
if (![renderTextureBitmap isPlanar] &&
((samplesPerPixel == 3) ||
(samplesPerPixel == 4))) {
//NSLog(@"CUnityJSPlugin: renderUpdateOpenGLCore: pluginID: %@ initializing image samplesPerPixel: %d w: %d h: %d", pluginID, samplesPerPixel, (int)[renderTextureBitmap pixelsWide], (int)[renderTextureBitmap pixelsHigh]);
glTexSubImage2D(
GL_TEXTURE_2D,
0,
0,
0,
(GLsizei)renderTextureWidth,
(GLsizei)renderTextureHeight,
samplesPerPixel == 4 ? GL_RGBA : GL_RGB,
GL_UNSIGNED_BYTE,
[renderTextureBitmap bitmapData]);
//NSLog(@"CUnityJSPlugin: renderUpdateOpenGLCore: pluginID: %@ initialized image", pluginID);
}
glBindTexture(GL_TEXTURE_2D, 0);
glPixelStorei(GL_UNPACK_ROW_LENGTH, rowLength);
glPixelStorei(GL_UNPACK_ALIGNMENT, unpackAlign);
//NSLog(@"CUnityJSPlugin: renderUpdateOpenGLCore: pluginID: %@ sending Texture", pluginID);
renderTextureBitmap = nil;
[self
unitySendMessage:@"Texture"
data:@""];
//NSLog(@"CUnityJSPlugin: renderUpdateOpenGLCore: pluginID: %@ sent Texture", pluginID);
#endif
}
- (void)renderUpdateOpenGLES20
{
//NSLog(@"CUnityJSPlugin: renderUpdateOpenGLES20: pluginID: %@", pluginID);
}
- (void)renderUpdateOpenGLES30
{
//NSLog(@"CUnityJSPlugin: renderUpdateOpenGLES30: pluginID: %@", pluginID);
}
- (void)renderUpdateMetal
{
//NSLog(@"CUnityJSPlugin: renderUpdateMetal: pluginID: %@", pluginID);
#if TARGET_OS_OSX
if (renderTextureHandle == 0) {
glGenTextures(1, &renderTextureHandle);
glBindTexture(GL_TEXTURE_2D, renderTextureHandle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, renderTextureWidth, renderTextureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glBindTexture(GL_TEXTURE_2D, renderTextureHandle);
//NSLog(@"CUnityJSPlugin: renderUpdateMetal: pluginID: %@ created renderTextureHandle: %d width: %d height: %d", pluginID, renderTextureHandle, renderTextureWidth, renderTextureHeight);
}
int samplesPerPixel = (int)[renderTextureBitmap samplesPerPixel];
int rowLength = 0;
int unpackAlign = 0;
glGetIntegerv(GL_UNPACK_ROW_LENGTH, &rowLength);
glGetIntegerv(GL_UNPACK_ALIGNMENT, &unpackAlign);
glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint)[renderTextureBitmap bytesPerRow] / samplesPerPixel);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D, renderTextureHandle);
if (![renderTextureBitmap isPlanar] &&
((samplesPerPixel == 3) ||
(samplesPerPixel == 4))) {
//NSLog(@"CUnityJSPlugin: renderUpdateMetal: pluginID: %@ initializing image samplesPerPixel: %d w: %d h: %d", pluginID, samplesPerPixel, (int)[renderTextureBitmap pixelsWide], (int)[renderTextureBitmap pixelsHigh]);
glTexSubImage2D(
GL_TEXTURE_2D,
0,
0,
0,
(GLsizei)renderTextureWidth,
(GLsizei)renderTextureHeight,
samplesPerPixel == 4 ? GL_RGBA : GL_RGB,
GL_UNSIGNED_BYTE,
[renderTextureBitmap bitmapData]);
//NSLog(@"CUnityJSPlugin: renderUpdateMetal: pluginID: %@ initialized image", pluginID);
}
glBindTexture(GL_TEXTURE_2D, 0);
glPixelStorei(GL_UNPACK_ROW_LENGTH, rowLength);
glPixelStorei(GL_UNPACK_ALIGNMENT, unpackAlign);
//NSLog(@"CUnityJSPlugin: renderUpdateMetal: pluginID: %@ sending CallOnTexture", pluginID);
renderTextureBitmap = nil;
[self
unitySendMessage:@"Texture"
data:@""];
//NSLog(@"CUnityJSPlugin: renderUpdateMetal: pluginID: %@ sent CallOnTexture", pluginID);
#endif
}
#if UNITYJS_WEBVIEW
- (void)flushCaches
{
// TODO: OSX WebView flushCaches
}
// WebFrameLoadDelegate
// https://developer.apple.com/documentation/webkit/webframeloaddelegate?language=objc
// Called if an error occurs when starting to load data for a page.
// The frame continues to display the committed data source if there is one.
- (void)webView:(WebView *)sender
didFailProvisionalLoadWithError:(NSError *)error
forFrame:(WebFrame *)frame
{
[self
unitySendMessage:@"Error"
data:[error description]];
}
// Called when an error occurs loading a committed data source.
// This method is called after the data source has been committed
// but resulted in an error.
- (void)webView:(WebView *)sender
didFailLoadWithError:(NSError *)error
forFrame:(WebFrame *)frame
{
[self
unitySendMessage:@"Error"
data:[error description]];
}
// Called when a page load completes.
// This method is invoked when a location request for frame has
// completed; that is, when all the resources are done loading.
// Additional information about the request can be obtained from the
// data source of frame.
- (void)webView:(WebView *)sender
didFinishLoadForFrame:(WebFrame *)frame
{
[self
unitySendMessage:@"Loaded"
data:[[[[frame dataSource] request] URL] absoluteString]];
}
// WebPolicyDelegate
// https://developer.apple.com/documentation/webkit/webpolicydelegate?language=objc
- (void)webView:(WebView *)sender
decidePolicyForNavigationAction:(NSDictionary *)actionInformation
request:(NSURLRequest *)request
frame:(WebFrame *)frame
decisionListener:(id<WebPolicyDecisionListener>)listener
{
NSString *url = [[request URL] absoluteString];
//NSLog(@"CUnityJSPlugin: decidePolicyForNavigationAction: url: %@", url);
if ([url hasPrefix:@"unity:"]) {
NSString *message = [url substringFromIndex:6];
//NSLog(@"CUnityJSPlugin: decidePolicyForNavigationAction: hasPrefix unity: message: %@", message);
[self
unitySendMessage:@"CallFromJS"
data:[self URLDecode: message]];
[listener ignore];
return;
}
NSString *fragment = [[request URL] fragment];
if ([fragment hasPrefix:@"unity:"]) {
NSString *message = [fragment substringFromIndex:6];
//NSLog(@"CUnityJSPlugin: decidePolicyForNavigationAction: hasPrefix unity: message: %@", message);
[self
unitySendMessage:@"CallFromJS"
data:[self URLDecode:message]];
[listener ignore];
return;
}
[listener use];
}
#endif
#if UNITYJS_WKWEBVIEW
- (void)flushCaches
{
NSSet *websiteDataTypes =
[WKWebsiteDataStore allWebsiteDataTypes];
NSDate *dateFrom =
[NSDate dateWithTimeIntervalSince1970:0];
[[WKWebsiteDataStore defaultDataStore]
removeDataOfTypes:websiteDataTypes
modifiedSince:dateFrom
completionHandler:^{
// Done
}];
}
// WkUIDelegate
// https://developer.apple.com/documentation/webkit/wkuidelegate?language=objc
- (void)webView:(WKWebView *)webView
runJavaScriptAlertPanelWithMessage:(NSString *)message
initiatedByFrame:(WKFrameInfo *)frame
completionHandler:(void (^)(void))completionHandler
{
completionHandler();
}
- (void)webView:(WKWebView *)webView
runJavaScriptConfirmPanelWithMessage:(NSString *)message
initiatedByFrame:(WKFrameInfo *)frame
completionHandler:(void (^)(BOOL result))completionHandler
{
completionHandler(confirmPanelResult);
}
- (void)webView:(WKWebView *)webView
runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt
defaultText:(NSString *)defaultText
initiatedByFrame:(WKFrameInfo *)frame
completionHandler:(void (^)(NSString *result))completionHandler