Compare commits

..

5 Commits

Author SHA1 Message Date
gem
8e7a2b0060 no message 2025-02-21 14:40:56 +08:00
gem
40409fd882 no message 2025-02-21 14:40:32 +08:00
gem
d7699c93cd no message 2025-02-07 18:05:26 +08:00
gem
e5f1398bc3 Merge commit 'f3e0de51226a3d322ae1b6ddd0d7c40b1ad1d44d' 2025-02-07 10:40:39 +08:00
cpdl
f3e0de5122 no message 2025-02-07 10:38:54 +08:00
22 changed files with 938 additions and 207 deletions

49
example/ios/Podfile Normal file
View File

@@ -0,0 +1,49 @@
# Uncomment this line to define a global platform for your project
# platform :ios, '12.0'
platform :ios, '14.5'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
source 'https://gitea.sdws.shop/xim/open-im-sdk-repo.git' # 替换为实际的私有源 URL
source 'https://cdn.cocoapods.org/' # 默认的公共源
pod 'cocos_view_pod', '0.1.23'
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
flutter_ios_podfile_setup
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
target 'RunnerTests' do
inherit! :search_paths
end
end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
end
end

View File

@@ -106,7 +106,6 @@
181E7CAB9BFA90CDBBC625FE /* Pods-RunnerTests.release.xcconfig */,
26E556676FA54FF74E61CC9C /* Pods-RunnerTests.profile.xcconfig */,
);
name = Pods;
path = Pods;
sourceTree = "<group>";
};
@@ -198,7 +197,7 @@
97C146EC1CF9000F007C117D /* Resources */,
9705A1C41CF9048500538489 /* Embed Frameworks */,
3B06AD1E1E4923F5004D2608 /* Thin Binary */,
C22789791D91DA87B0800321 /* [CP] Embed Pods Frameworks */,
129AC22480F1A498B12D0823 /* [CP] Copy Pods Resources */,
);
buildRules = (
);
@@ -270,6 +269,23 @@
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
129AC22480F1A498B12D0823 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Copy Pods Resources";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh\"\n";
showEnvVarsInLog = 0;
};
3B06AD1E1E4923F5004D2608 /* Thin Binary */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
@@ -345,23 +361,6 @@
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build";
};
C22789791D91DA87B0800321 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
@@ -457,6 +456,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = NO;
OTHER_LIBTOOLFLAGS = "$(inherited)";
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
@@ -471,12 +471,14 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = U4K6R29373;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
OTHER_LIBTOOLFLAGS = "";
PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterCocosViewExample;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
@@ -587,6 +589,7 @@
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
OTHER_LIBTOOLFLAGS = "$(inherited)";
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
};
@@ -637,6 +640,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = NO;
OTHER_LIBTOOLFLAGS = "$(inherited)";
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
@@ -653,12 +657,15 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = U4K6R29373;
ENABLE_BITCODE = NO;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = arm64;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
OTHER_LIBTOOLFLAGS = "";
PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterCocosViewExample;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
@@ -675,12 +682,16 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = U4K6R29373;
ENABLE_BITCODE = NO;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = arm64;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
ONLY_ACTIVE_ARCH = YES;
OTHER_LIBTOOLFLAGS = "";
PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterCocosViewExample;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";

View File

@@ -7,7 +7,28 @@ import UIKit
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
///InitCocosIntegrationWithOptions(argc: CommandLine.argc, argv: CommandLine.unsafeArgv, launchOptions)
let flutterEngine = FlutterEngine(name: "io.flutter", project: nil)
flutterEngine.run()
let controller = FlutterViewControllerWithTransition(engine: flutterEngine, nibName: nil, bundle: nil)
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = controller
self.window?.makeKeyAndVisible()
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
class FlutterViewControllerWithTransition: FlutterViewController {
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
NotificationCenter.default.post(name: NSNotification.Name("ViewWillTransition"), object: nil, userInfo: ["size": size, "coordinator": coordinator])
}
}

View File

@@ -1,63 +1,37 @@
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter_cocos_view_example/screens/no_interaction_screen.dart';
import 'package:flutter_cocos_view_example/screens/orientation_screen.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cocos_view/flutter_cocos_view.dart';
import 'menu_screen.dart';
import 'screens/api_screen.dart';
import 'screens/loader_screen.dart';
import 'screens/simple_screen.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
final _flutterCocosViewPlugin = FlutterCocosView();
@override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
// We also handle the message potentially returning null.
try {
platformVersion =
await _flutterCocosViewPlugin.getPlatformVersion() ?? 'Unknown platform version';
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Text('Running on: $_platformVersion\n'),
),
title: 'Flutter Cocos Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
initialRoute: '/',
routes: {
'/': (context) => const MenuScreen(),
'/simple': (context) => const SimpleScreen(),
'/loader': (context) => const LoaderScreen(),
'/orientation': (context) => const OrientationScreen(),
'/api': (context) => const ApiScreen(),
'/none': (context) => const NoInteractionScreen(),
},
);
}
}

View File

@@ -0,0 +1,76 @@
import 'package:flutter/material.dart';
class MenuScreen extends StatefulWidget {
const MenuScreen({Key? key}) : super(key: key);
@override
State<MenuScreen> createState() => _MenuScreenState();
}
class _MenuScreenState extends State<MenuScreen> {
List<_MenuListItem> menus = [
_MenuListItem(
description: 'Simple demonstration of cocos flutter library',
route: '/simple',
title: 'Simple Cocos Demo',
),
_MenuListItem(
description: 'No interaction of cocos flutter library',
route: '/none',
title: 'No Interaction Cocos Demo',
),
_MenuListItem(
description: 'Cocos load and unload cocos demo',
route: '/loader',
title: 'Safe mode Demo',
),
_MenuListItem(
description:
'This example shows various native API exposed by the library',
route: '/api',
title: 'Native exposed API demo',
),
_MenuListItem(
title: 'Test Orientation',
route: '/orientation',
description: 'test orientation change',
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Menu List'),
),
body: Center(
child: ListView.builder(
itemCount: menus.length,
itemBuilder: (BuildContext context, int i) {
return ListTile(
title: Text(menus[i].title),
subtitle: Text(menus[i].description),
onTap: () {
Navigator.of(context).pushNamed(
menus[i].route,
);
},
);
},
),
),
);
}
}
class _MenuListItem {
final String title;
final String description;
final String route;
_MenuListItem({
required this.title,
required this.description,
required this.route,
});
}

View File

@@ -0,0 +1,168 @@
// ignore_for_file: avoid_print
import 'package:flutter/material.dart';
import "package:flutter_cocos_view/flutter_cocos_view.dart";
import 'package:pointer_interceptor/pointer_interceptor.dart';
class ApiScreen extends StatefulWidget {
const ApiScreen({Key? key}) : super(key: key);
@override
State<ApiScreen> createState() => _ApiScreenState();
}
class _ApiScreenState extends State<ApiScreen> {
CocosWidgetController? _cocosWidgetController;
double _sliderValue = 0.0;
@override
void initState() {
super.initState();
}
@override
void dispose() {
_cocosWidgetController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('API Screen'),
),
body: Card(
margin: const EdgeInsets.all(8),
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Stack(
children: [
CocosWidget(
onCocosCreated: onCocosCreated,
onCocosMessage: onCocosMessage,
onCocosSceneLoaded: onCocosSceneLoaded,
fullscreen: false,
useAndroidViewSurface: false,
),
Positioned(
bottom: 20,
left: 20,
right: 20,
child: PointerInterceptor(
child: Card(
elevation: 10,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Padding(
padding: EdgeInsets.only(top: 20),
child: Text("Rotation speed:"),
),
Slider(
onChanged: (value) {
setState(() {
_sliderValue = value;
});
setRotationSpeed(value.toString());
},
value: _sliderValue,
min: 0,
max: 20,
),
FittedBox(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
MaterialButton(
onPressed: () {
_cocosWidgetController?.quit();
},
child: const Text("Quit"),
),
MaterialButton(
onPressed: () {
_cocosWidgetController?.create();
},
child: const Text("Create"),
),
MaterialButton(
onPressed: () {
_cocosWidgetController?.pause();
},
child: const Text("Pause"),
),
MaterialButton(
onPressed: () {
_cocosWidgetController?.resume();
},
child: const Text("Resume"),
),
],
),
),
FittedBox(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
MaterialButton(
onPressed: () async {
await _cocosWidgetController
?.openInNativeProcess();
},
child: const Text("Open Native"),
),
MaterialButton(
onPressed: () {
_cocosWidgetController?.unload();
},
child: const Text("Unload"),
),
MaterialButton(
onPressed: () {
_cocosWidgetController?.quit();
},
child: const Text("Silent Quit"),
),
],
),
),
],
),
),
),
),
],
),
),
);
}
void setRotationSpeed(String speed) {
_cocosWidgetController?.postMessage(
'Cube',
'SetRotationSpeed',
speed,
);
}
void onCocosMessage(message) {
print('Received message from cocos: ${message.toString()}');
}
void onCocosSceneLoaded(SceneLoaded? scene) {
if (scene != null) {
print('Received scene loaded from cocos: ${scene.name}');
print('Received scene loaded from cocos buildIndex: ${scene.buildIndex}');
} else {
print('Received scene loaded from cocos: null');
}
}
// Callback that connects the created controller to the cocos controller
void onCocosCreated(controller) {
_cocosWidgetController = controller;
}
}

View File

@@ -0,0 +1,93 @@
// ignore_for_file: avoid_print
import 'package:flutter/material.dart';
import 'package:flutter_cocos_view/flutter_cocos_view.dart';
import 'package:pointer_interceptor/pointer_interceptor.dart';
class LoaderScreen extends StatefulWidget {
const LoaderScreen({Key? key}) : super(key: key);
@override
State<LoaderScreen> createState() => _LoaderScreenState();
}
class _LoaderScreenState extends State<LoaderScreen> {
CocosWidgetController? _cocosWidgetController;
double _sliderValue = 0.0;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Safe Mode Screen'),
),
body: Card(
margin: const EdgeInsets.all(8),
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Stack(
children: <Widget>[
CocosWidget(
onCocosCreated: onCocosCreated,
onCocosMessage: onCocosMessage,
useAndroidViewSurface: true,
),
Positioned(
bottom: 20,
left: 20,
right: 20,
child: PointerInterceptor(
child: Card(
elevation: 10,
child: Column(
children: <Widget>[
const Padding(
padding: EdgeInsets.only(top: 20),
child: Text("Rotation speed:"),
),
Slider(
onChanged: (value) {
setState(() {
_sliderValue = value;
});
setRotationSpeed(value.toString());
},
value: _sliderValue,
min: 0,
max: 20,
),
],
),
),
),
),
],
),
),
);
}
void setRotationSpeed(String speed) {
_cocosWidgetController?.postMessage(
'Cube',
'SetRotationSpeed',
speed,
);
}
void onCocosMessage(message) {
print('Received message from cocos: ${message.toString()}');
}
// Callback that connects the created controller to the cocos controller
void onCocosCreated(controller) {
_cocosWidgetController = controller;
}
}

View File

@@ -0,0 +1,96 @@
import 'package:flutter/material.dart';
import 'package:flutter_cocos_view/flutter_cocos_view.dart';
import 'package:pointer_interceptor/pointer_interceptor.dart';
class NoInteractionScreen extends StatefulWidget {
const NoInteractionScreen({Key? key}) : super(key: key);
@override
State<NoInteractionScreen> createState() => _NoInteractionScreenState();
}
class _NoInteractionScreenState extends State<NoInteractionScreen> {
static final GlobalKey<ScaffoldState> _scaffoldKey =
GlobalKey<ScaffoldState>();
CocosWidgetController? _cocosWidgetController;
@override
void initState() {
super.initState();
}
@override
void dispose() {
_cocosWidgetController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: const Text('No Interaction Screen'),
),
body: Card(
margin: const EdgeInsets.all(8),
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Stack(
children: [
CocosWidget(
onCocosCreated: _onCocosCreated,
onCocosMessage: onCocosMessage,
onCocosSceneLoaded: onCocosSceneLoaded,
useAndroidViewSurface: true,
borderRadius: const BorderRadius.all(Radius.circular(70)),
),
Positioned(
bottom: 20,
left: 20,
right: 20,
child: PointerInterceptor(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).pushNamed('/simple');
},
child: const Text('Switch Flutter Screen'),
),
),
),
],
),
),
);
}
void setRotationSpeed(String speed) {
_cocosWidgetController?.postMessage(
'Cube',
'SetRotationSpeed',
speed,
);
}
void onCocosMessage(message) {
print('Received message from cocos: ${message.toString()}');
}
void onCocosSceneLoaded(SceneLoaded? scene) {
if (scene != null) {
print('Received scene loaded from cocos: ${scene.name}');
print('Received scene loaded from cocos buildIndex: ${scene.buildIndex}');
} else {
print('Received scene loaded from cocos: null');
}
}
// Callback that connects the created controller to the cocos controller
void _onCocosCreated(controller) {
controller.resume();
_cocosWidgetController = controller;
}
}

View File

@@ -0,0 +1,108 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cocos_view/flutter_cocos_view.dart';
import 'package:pointer_interceptor/pointer_interceptor.dart';
class OrientationScreen extends StatefulWidget {
const OrientationScreen({Key? key}) : super(key: key);
@override
State<OrientationScreen> createState() => _OrientationScreenState();
}
class _OrientationScreenState extends State<OrientationScreen> {
CocosWidgetController? _cocosWidgetController;
double _sliderValue = 0.0;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Orientation Screen'),
),
body: Card(
margin: const EdgeInsets.all(8),
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Stack(
children: <Widget>[
CocosWidget(
onCocosCreated: onCocosCreated,
onCocosMessage: onCocosMessage,
useAndroidViewSurface: true,
),
Positioned(
bottom: 20,
left: 20,
right: 20,
child: PointerInterceptor(
child: Card(
elevation: 10,
child: Column(
children: <Widget>[
ElevatedButton(
onPressed: () {
if (MediaQuery.of(context).orientation ==
Orientation.portrait) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight
]);
} else if (MediaQuery.of(context).orientation ==
Orientation.landscape) {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp]);
}
},
child: const Text("Change Orientation"),
),
const Padding(
padding: EdgeInsets.only(top: 20),
child: Text("Rotation speed:"),
),
Slider(
onChanged: (value) {
setState(() {
_sliderValue = value;
});
setRotationSpeed(value.toString());
},
value: _sliderValue,
min: 0,
max: 20,
),
],
),
),
),
),
],
),
),
);
}
void setRotationSpeed(String speed) {
_cocosWidgetController?.postMessage(
'Cube',
'SetRotationSpeed',
speed,
);
}
void onCocosMessage(message) {
print('Received message from cocos: ${message.toString()}');
}
// Callback that connects the created controller to the cocos controller
void onCocosCreated(controller) {
_cocosWidgetController = controller;
}
}

View File

@@ -0,0 +1,113 @@
import 'package:flutter/material.dart';
import 'package:flutter_cocos_view/flutter_cocos_view.dart';
import 'package:pointer_interceptor/pointer_interceptor.dart';
class SimpleScreen extends StatefulWidget {
const SimpleScreen({Key? key}) : super(key: key);
@override
State<SimpleScreen> createState() => _SimpleScreenState();
}
class _SimpleScreenState extends State<SimpleScreen> {
static final GlobalKey<ScaffoldState> _scaffoldKey =
GlobalKey<ScaffoldState>();
CocosWidgetController? _cocosWidgetController;
double _sliderValue = 0.0;
@override
void initState() {
super.initState();
}
@override
void dispose() {
_cocosWidgetController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: const Text('Simple Screen'),
),
body: Card(
margin: const EdgeInsets.all(0),
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Stack(
children: [
CocosWidget(
onCocosCreated: _onCocosCreated,
onCocosMessage: onCocosMessage,
onCocosSceneLoaded: onCocosSceneLoaded,
useAndroidViewSurface: false,
borderRadius: const BorderRadius.all(Radius.circular(70)),
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: PointerInterceptor(
child: Card(
elevation: 10,
child: Column(
children: <Widget>[
const Padding(
padding: EdgeInsets.only(top: 20),
child: Text("Rotation speed:"),
),
Slider(
onChanged: (value) {
setState(() {
_sliderValue = value;
});
setRotationSpeed(value.toString());
},
value: _sliderValue,
min: 0.0,
max: 1.0,
),
],
),
),
),
),
],
)),
);
}
void setRotationSpeed(String speed) {
_cocosWidgetController?.postMessage(
'Cube',
'SetRotationSpeed',
speed,
);
}
void onCocosMessage(message) {
print('Received message from cocos: ${message.toString()}');
}
void onCocosSceneLoaded(SceneLoaded? scene) {
if (scene != null) {
print('Received scene loaded from cocos: ${scene.name}');
print('Received scene loaded from cocos buildIndex: ${scene.buildIndex}');
} else {
print('Received scene loaded from cocos: null');
}
}
// Callback that connects the created controller to the cocos controller
void _onCocosCreated(controller) {
print('Received _onCocosCreated: null');
controller.resume();
_cocosWidgetController = controller;
}
}

View File

@@ -57,14 +57,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.3.1"
file:
dependency: transitive
description:
name: file
sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c"
url: "https://pub.dev"
source: hosted
version: "7.0.0"
flutter:
dependency: "direct main"
description: flutter
@@ -77,11 +69,6 @@ packages:
relative: true
source: path
version: "0.0.1"
flutter_driver:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
flutter_lints:
dependency: "direct dev"
description:
@@ -95,16 +82,6 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
fuchsia_remote_debug_protocol:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
integration_test:
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
leak_tracker:
dependency: transitive
description:
@@ -169,14 +146,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.9.0"
platform:
dependency: transitive
description:
name: platform
sha256: "9b71283fc13df574056616011fb138fd3b793ea47cc509c189a6c3fa5f8a1a65"
url: "https://pub.dev"
source: hosted
version: "3.1.5"
plugin_platform_interface:
dependency: transitive
description:
@@ -185,14 +154,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.8"
process:
dependency: transitive
pointer_interceptor:
dependency: "direct main"
description:
name: process
sha256: "21e54fd2faf1b5bdd5102afd25012184a6793927648ea81eea80552ac9405b32"
name: pointer_interceptor
sha256: adf7a637f97c077041d36801b43be08559fd4322d2127b3f20bb7be1b9eebc22
url: "https://pub.dev"
source: hosted
version: "5.0.2"
version: "0.9.3+7"
sky_engine:
dependency: transitive
description: flutter
@@ -238,14 +207,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.2.0"
sync_http:
dependency: transitive
description:
name: sync_http
sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961"
url: "https://pub.dev"
source: hosted
version: "0.3.1"
term_glyph:
dependency: transitive
description:
@@ -278,14 +239,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "14.2.5"
webdriver:
dependency: transitive
description:
name: webdriver
sha256: "003d7da9519e1e5f329422b36c4dcdf18d7d2978d1ba099ea4e45ba490ed845e"
url: "https://pub.dev"
source: hosted
version: "3.0.3"
sdks:
dart: ">=3.4.4 <4.0.0"
flutter: ">=3.18.0-18.0.pre.54"

View File

@@ -28,10 +28,8 @@ dependencies:
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.8
pointer_interceptor: ^0.9.3+2
dev_dependencies:
integration_test:
sdk: flutter
flutter_test:
sdk: flutter

View File

@@ -36,17 +36,10 @@ public func InitCocosIntegrationWithOptions(
/***********************************PLUGIN_ENTRY END**************************************/
// Load cocos framework for fisrt run
func CocosFrameworkLoad() -> CocosFramework? {
var bundlePath: String? = nil
bundlePath = Bundle.main.bundlePath
bundlePath = (bundlePath ?? "") + "/Frameworks/CocosFramework.framework"
func CocosFrameworkLoad() -> dcocos_bridge? {
let bundle = Bundle(path: bundlePath ?? "")
if bundle?.isLoaded == false {
bundle?.load()
}
return bundle?.principalClass?.getInstance()
return dcocos_bridge.instance()
}
/*********************************** GLOBAL FUNCS & VARS START**************************************/
@@ -64,7 +57,7 @@ func GetCocosPlayerUtils() -> CocosPlayerUtils {
/*********************************** GLOBAL FUNCS & VARS END****************************************/
var controller: CocosAppController?
//var controller: CocosAppController?
var sharedApplication: UIApplication?
@objc protocol CocosEventListener: AnyObject {
@@ -73,31 +66,74 @@ var sharedApplication: UIApplication?
}
@objc public class CocosPlayerUtils: UIResponder, UIApplicationDelegate, CocosFrameworkListener {
var ufw: CocosFramework!
@objc public class CocosPlayerUtils: UIResponder, UIApplicationDelegate {
var ufw: dcocos_bridge!
private var _isCocosPaused = false
private var _isCocosReady = false
private var _isCocosLoaded = false
func initCocos() {
if (self.cocosIsInitiallized()) {
self.ufw?.showCocosWindow()
override init() {
super.init()
//
NotificationCenter.default.addObserver(self, selector: #selector(handleViewWillTransition), name: NSNotification.Name("ViewWillTransition"), object: nil)
}
deinit {
//
NotificationCenter.default.removeObserver(self)
}
@objc func handleViewWillTransition(notification: Notification) {
guard let size = notification.userInfo?["size"] as? CGSize,
let coordinator = notification.userInfo?["coordinator"] as? UIViewControllerTransitionCoordinator else {
return
}
//
print("CocosPlayerUtils will transition to size: \(size)")
//
let selector = NSSelectorFromString("viewWillTransitionToSize:withTransitionCoordinator:")
if self.ufw.responds(to: selector) {
self.ufw.perform(selector, with: size, with: coordinator)
}
}
func initCocos() {
if (self.cocosIsInitiallized()) {
//todo
//self.ufw?.showCocosWindow()
return
}
//
//UIDevice.current.beginGeneratingDeviceOrientationNotifications()
self.ufw = CocosFrameworkLoad()
self.ufw?.setDataBundleId("com.cocos3d.framework")
// PodBundle
let bundle = Bundle(for: dcocos_bridge.self)
// `YourPodResources.bundle`
if let bundleURL = bundle.url(forResource: "cocos_main_bundle", withExtension: "bundle") {
let bundlePath = bundleURL.path
print("Bundle absolute path: \(bundlePath)")
self.ufw.configureCocos2dSearchPaths(bundlePath)
} else {
print("Could not find the bundle.")
}
//self.ufw?.setDataBundleId("com.cocos3d.framework")
self.ufw.initPlatform()
let application = UIApplication.shared
self.ufw.application(application, didFinishLaunchingWithOptions: appLaunchOpts )
registerCocosListener()
self.ufw?.runEmbedded(withArgc: gArgc, argv: gArgv, appLaunchOpts: appLaunchOpts)
// self.ufw?.runEmbedded(withArgc: gArgc, argv: gArgv, appLaunchOpts: appLaunchOpts)
if self.ufw?.appController() != nil {
controller = self.ufw?.appController()
controller?.cocosMessageHandler = self.cocosMessageHandlers
controller?.cocosSceneLoadedHandler = self.cocosSceneLoadedHandlers
self.ufw?.appController()?.window?.windowLevel = UIWindow.Level(UIWindow.Level.normal.rawValue - 1)
}
// if self.ufw?.appController() != nil {
// controller = self.ufw?.appController()
// controller?.cocosMessageHandler = self.cocosMessageHandlers
// controller?.cocosSceneLoadedHandler = self.cocosSceneLoadedHandlers
// self.ufw?.appController()?.window?.windowLevel = UIWindow.Level(UIWindow.Level.normal.rawValue - 1)
// }
_isCocosLoaded = true
}
@@ -113,13 +149,18 @@ var sharedApplication: UIApplication?
// Create new cocos player
func createPlayer(completed: @escaping (_ view: UIView?) -> Void) {
if self.cocosIsInitiallized() && self._isCocosReady {
completed(controller?.rootView)
//todo
//completed(controller?.rootView)
completed(nil)
return
}
NotificationCenter.default.addObserver(forName: NSNotification.Name("CocosReady"), object: nil, queue: OperationQueue.main, using: { note in
self._isCocosReady = true
completed(controller?.rootView)
//todo
//completed(controller?.rootView)
completed(nil)
})
DispatchQueue.main.async {
@@ -140,20 +181,22 @@ var sharedApplication: UIApplication?
self.listenAppState()
completed(controller?.rootView)
//todo
//completed(controller?.rootView)
completed(nil)
}
}
func registerCocosListener() {
if self.cocosIsInitiallized() {
self.ufw?.register(self)
// self.ufw?.register(self)
}
}
func unregisterCocosListener() {
if self.cocosIsInitiallized() {
self.ufw?.unregisterFrameworkListener(self)
// self.ufw?.unregisterFrameworkListener(self)
}
}
@@ -169,29 +212,30 @@ var sharedApplication: UIApplication?
if !self._isCocosReady {
return
}
let cocosAppController = self.ufw?.appController() as? CocosAppController
//todo
//let cocosAppController = self.ufw?.appController() as? CocosAppController
// let cocosAppController = nil
let application = UIApplication.shared
if notification?.name == UIApplication.willResignActiveNotification {
cocosAppController?.applicationWillResignActive(application)
self.ufw?.applicationWillResignActive(application)
} else if notification?.name == UIApplication.didEnterBackgroundNotification {
cocosAppController?.applicationDidEnterBackground(application)
// self.ufw?.applicationDidEnterBackground(application)
} else if notification?.name == UIApplication.willEnterForegroundNotification {
cocosAppController?.applicationWillEnterForeground(application)
// self.ufw?.applicationWillEnterForeground(application)
} else if notification?.name == UIApplication.didBecomeActiveNotification {
cocosAppController?.applicationDidBecomeActive(application)
self.ufw?.applicationDidBecomeActive(application)
} else if notification?.name == UIApplication.willTerminateNotification {
cocosAppController?.applicationWillTerminate(application)
self.ufw?.applicationWillTerminate(application)
} else if notification?.name == UIApplication.didReceiveMemoryWarningNotification {
cocosAppController?.applicationDidReceiveMemoryWarning(application)
}
// self.ufw?.applicationDidReceiveMemoryWarning(application)
}
}
// Listener for app lifecycle eventa
func listenAppState() {
for name in [
UIApplication.didBecomeActiveNotification,
UIApplication.didEnterBackgroundNotification,
UIApplication.willTerminateNotification,
@@ -208,19 +252,22 @@ var sharedApplication: UIApplication?
}
// Pause cocos player
func pause() {
self.ufw?.pause(true)
//todo
// self.ufw?.pause(true)
self._isCocosPaused = true
}
// Resume cocos player
func resume() {
self.ufw?.pause(false)
//todo
//self.ufw?.pause(false)
self._isCocosPaused = false
}
// Unoad cocos player
func unload() {
self.ufw?.unloadApplication()
//todo
//self.ufw?.unloadApplication()
}
func isCocosLoaded() -> Bool {
@@ -233,14 +280,16 @@ var sharedApplication: UIApplication?
// Quit cocos player application
func quit() {
self.ufw?.quitApplication(0)
//todo
//self.ufw?.quitApplication(0)
self._isCocosLoaded = false
}
// Post message to cocos
func postMessageToCocos(gameObject: String?, cocosMethodName: String?, cocosMessage: String?) {
if self.cocosIsInitiallized() {
self.ufw?.sendMessageToGO(withName: gameObject, functionName: cocosMethodName, message: cocosMessage)
//todo
//self.ufw?.sendMessageToGO(withName: gameObject, functionName: cocosMethodName, message: cocosMessage)
}
}

View File

@@ -13,7 +13,8 @@ class FLTCocosView: UIView {
override func layoutSubviews() {
super.layoutSubviews()
if (!self.bounds.isEmpty) {
GetCocosPlayerUtils().ufw?.appController()?.rootView.frame = self.bounds
//todo
GetCocosPlayerUtils().ufw?.getCocosView()?.frame = self.bounds
}
}
}

View File

@@ -6,7 +6,7 @@
//
import Foundation
import CocosFramework
// Defines cocos controllable from Flutter.
public class FLTCocosWidgetController: NSObject, FLTCocosOptionsSink, FlutterPlatformView {
@@ -23,14 +23,16 @@ public class FLTCocosWidgetController: NSObject, FLTCocosOptionsSink, FlutterPla
arguments args: Any?,
registrar: NSObjectProtocol & FlutterPluginRegistrar
) {
//CGRect(x: 0, y: 0, width: 700, height: 700)
self._rootView = FLTCocosView(frame: frame)
super.init()
globalControllers.append(self)
self.viewId = viewId
let channelName = String(format: "plugin.xraph.com/cocos_view_%lld", viewId)
let channelName = String(format: "plugin.gem.com/cocos_view_%lld", viewId)
self.channel = FlutterMethodChannel(name: channelName, binaryMessenger: registrar.messenger())
self.channel?.setMethodCallHandler(self.methodHandler)
@@ -38,6 +40,8 @@ public class FLTCocosWidgetController: NSObject, FLTCocosOptionsSink, FlutterPla
}
func methodHandler(_ call: FlutterMethodCall, result: FlutterResult) {
NSLog("call : \(call.method)")
if call.method == "cocos#dispose" {
self.dispose()
result(nil)
@@ -87,33 +91,35 @@ public class FLTCocosWidgetController: NSObject, FLTCocosOptionsSink, FlutterPla
private func startCocosIfNeeded() {
GetCocosPlayerUtils().createPlayer(completed: { [self] (view: UIView?) in
})
}
func attachView() {
startCocosIfNeeded()
//GetCocosPlayerUtils().ufw?.setCocosView(_rootView)
// self.channel?.invokeMethod("events#onViewReattached", arguments: "")
let cocosView = GetCocosPlayerUtils().ufw?.getCocosView()
if let superview = cocosView?.superview {
cocosView?.removeFromSuperview()
superview.layoutIfNeeded()
}
let cocosView = GetCocosPlayerUtils().ufw?.appController()?.rootView
if let superview = cocosView?.superview {
cocosView?.removeFromSuperview()
superview.layoutIfNeeded()
}
if let cocosView = cocosView {
_rootView.addSubview(cocosView)
_rootView.layoutIfNeeded()
self.channel?.invokeMethod("events#onViewReattached", arguments: "")
}
if let cocosView = cocosView {
_rootView.addSubview(cocosView)
_rootView.layoutIfNeeded()
self.channel?.invokeMethod("events#onViewReattached", arguments: "")
}
GetCocosPlayerUtils().resume()
}
func reattachView() {
let cocosView = GetCocosPlayerUtils().ufw?.appController()?.rootView
//todo
let cocosView = GetCocosPlayerUtils().ufw?.getCocosView()
let superview = cocosView?.superview
if superview != _rootView {
attachView()
}
}
GetCocosPlayerUtils().resume()
}
@@ -123,7 +129,7 @@ public class FLTCocosWidgetController: NSObject, FLTCocosOptionsSink, FlutterPla
return
}
let cocosView = GetCocosPlayerUtils().ufw?.appController()?.rootView
let cocosView = GetCocosPlayerUtils().ufw?.getCocosView()
if _rootView == cocosView?.superview {
if globalControllers.isEmpty {
cocosView?.removeFromSuperview()

View File

@@ -1,11 +1,10 @@
import Flutter
import UIKit
public class FlutterCocosViewPlugin: NSObject, FlutterPlugin {
public class SwiftFlutterCocosViewPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "flutter_cocos_view", binaryMessenger: registrar.messenger())
let instance = FlutterCocosViewPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
print("FlutterCocosViewPlugin registered~~~~~~~~~~~~~~") //
let fuwFactory = FLTCocosWidgetFactory(registrar: registrar)
registrar.register(fuwFactory, withId: "plugin.gem.com/cocos_view", gestureRecognizersBlockingPolicy: FlutterPlatformViewGestureRecognizersBlockingPolicyWaitUntilTouchesEnded)

View File

@@ -1,22 +1,22 @@
#import FlutterCocosWidgetPlugin.h
#import "FlutterCocosWidgetPlugin.h"
#import <Foundation/Foundation.h>
#if __has_include(<flutter_unity_widget/flutter_unity_widget-Swift.h>)
#import <flutter_unity_widget/flutter_unity_widget-Swift.h>
#if __has_include(<flutter_cocos_view/flutter_cocos_-Swift.h>)
#import <flutter_cocos_view/flutter_cocos_view-Swift.h>
#else
// Support project import fallback if the generated compatibility header
// is not copied when this plugin is created as a library.
// https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816
#import "flutter_unity_widget-Swift.h"
#import <flutter_cocos_view/flutter_cocos_view-Swift.h>
#endif
@implementation FlutterCocosWidgetPlugin {
NSObject<FlutterPluginRegistrar>* _registrar;
FlutterMethodChannel* _channel;
NSMutableDictionary* _unityControllers;
NSMutableDictionary* _cocosControllers;
}
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
[SwiftFlutterCocosWidgetPlugin registerWithRegistrar:registrar];
[SwiftFlutterCocosViewPlugin registerWithRegistrar:registrar];
}
@end

View File

@@ -0,0 +1,8 @@
#ifndef your_plugin_Bridging_Header_h
#define your_plugin_Bridging_Header_h
#import <cocos_view_pod/dcocos_bridge.h>
#endif /* your_plugin_Bridging_Header_h */

View File

@@ -15,11 +15,17 @@ A new Flutter plugin project.
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.dependency 'Flutter'
s.dependency 'cocos_view_pod','0.1.23'
s.platform = :ios, '14.5'
s.dependency 'cocos_view_pod','0.1.7'
#s.public_header_files = 'Classes/**/*.h'
#s.vendored_libraries = 'Libs/**/*.a'
#s.libraries = 'dcocos'
#s.private_header_files = 'Classes/flutter_cocos_view-Bridging-Header.h'
s.static_framework = true
# Flutter.framework does not contain a i386 slice.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES'}
s.user_target_xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES' }
s.swift_version = '5.0'
# If your plugin requires a privacy manifest, for example if it uses any

View File

@@ -5,7 +5,7 @@
// platforms in the `pubspec.yaml` at
// https://flutter.dev/to/pubspec-plugin-platforms.
library flutter_Cocos_widget;
library flutter_cocos_view;
export 'src/facade_controller.dart';
export 'src/facade_widget.dart'

View File

@@ -40,7 +40,7 @@ class MethodChannelCocosWidget extends CocosWidgetPlatform {
MethodChannel ensureChannelInitialized(int cocosId) {
MethodChannel? channel = _channels[cocosId];
if (channel == null) {
channel = MethodChannel('plugin.xraph.com/cocos_view_$cocosId');
channel = MethodChannel('plugin.gem.com/cocos_view_$cocosId');
channel.setMethodCallHandler(
(MethodCall call) => _handleMethodCall(call, cocosId));
@@ -158,7 +158,7 @@ class MethodChannelCocosWidget extends CocosWidgetPlatform {
bool? cocosWebSource,
String? cocosSrcUrl,
}) {
final String _viewType = 'plugin.xraph.com/cocos_view';
final String _viewType = 'plugin.gem.com/cocos_view';
if (useAndroidViewSurf != null) useAndroidViewSurface = useAndroidViewSurf;

View File

@@ -1,11 +1,12 @@
name: flutter_cocos_view
description: "A new Flutter plugin project."
version: 0.0.1
homepage:
homepage: https://www.openim.io
environment:
sdk: ^3.4.4
flutter: '>=3.3.0'
sdk: ">=3.0.0 <4.0.0"
flutter: ">=1.20.0"
dependencies:
flutter:
@@ -34,14 +35,15 @@ flutter:
# All these are used by the tooling to maintain consistency when
# adding or updating assets for this project.
plugin:
platforms:
# This plugin project was generated without specifying any
# platforms with the `--platform` argument. If you see the `some_platform` map below, remove it and
# then add platforms following the instruction here:
# https://flutter.dev/to/pubspec-plugin-platforms
# -------------------
some_platform:
pluginClass: somePluginClass
platforms:
ios:
pluginClass: FlutterCocosWidgetPlugin
# -------------------
# To add assets to your plugin package, add an assets section, like this: