open source

This commit is contained in:
lvfulong
2020-11-11 16:17:13 +08:00
parent 4d989f3ecb
commit bc4ca748de
2441 changed files with 623057 additions and 2 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:LayaBox.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,14 @@
#import <UIKit/UIKit.h>
#import "LaunchView.h"
@class NavViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
@public
UIBackgroundTaskIdentifier m_kBackgroundTask;
}
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) LaunchView *launchView;
@property (strong, nonatomic) NavViewController* navigationController;
@end
@@ -0,0 +1,60 @@
#import "AppDelegate.h"
#import "ViewController.h"
#import "conchRuntime.h"
#import "NavViewController.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
_window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] ;
ViewController* pViewController = [[ViewController alloc] init];
//_window.rootViewController = pViewController;
[_window makeKeyAndVisible];
_launchView = [[LaunchView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[_window.rootViewController.view addSubview:_launchView.view];
self.navigationController = [[NavViewController alloc] init];
[self.navigationController pushViewController:pViewController animated:YES];
_window.rootViewController = self.navigationController;
[_window.rootViewController.view addSubview:_launchView.view];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
m_kBackgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{
if(m_kBackgroundTask != UIBackgroundTaskInvalid )
{
NSLog(@">>>>>backgroundTask end");
[application endBackgroundTask:m_kBackgroundTask];
m_kBackgroundTask = UIBackgroundTaskInvalid;
}
}];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

@@ -0,0 +1,110 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "58.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "87.png",
"scale" : "3x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "80.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "120.png",
"scale" : "3x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "120-1.png",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "180.png",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "29.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "58-1.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "40.png",
"scale" : "1x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "80-1.png",
"scale" : "2x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "76.png",
"scale" : "1x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "152.png",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"scale" : "2x"
},
{
"idiom" : "ios-marketing",
"size" : "1024x1024",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -0,0 +1,23 @@
{
"images" : [
{
"idiom" : "universal",
"filename" : "layabox.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "layabox-1.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "layabox-2.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

@@ -0,0 +1,23 @@
{
"images" : [
{
"idiom" : "universal",
"filename" : "close-2.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "close.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "close-1.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,23 @@
{
"images" : [
{
"idiom" : "universal",
"filename" : "line.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "line-2.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "line-1.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

@@ -0,0 +1,23 @@
{
"images" : [
{
"idiom" : "universal",
"filename" : "pick_bg.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "pick_bg-1.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "pick_bg-2.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14113" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController storyboardIdentifier="LaunchScreen" id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Llm-lL-Icb"/>
<viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="Launch" highlighted="YES" translatesAutoresizingMaskIntoConstraints="NO" id="map-GD-PNR">
<rect key="frame" x="93" y="294" width="188" height="78"/>
<color key="backgroundColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</imageView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="E2Q-uj-XYa">
<rect key="frame" x="187" y="567" width="0.0" height="0.0"/>
<fontDescription key="fontDescription" name=".AppleSystemUIFont" family=".AppleSystemUIFont" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<color key="tintColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<constraints>
<constraint firstAttribute="bottom" secondItem="E2Q-uj-XYa" secondAttribute="bottom" constant="100" id="8T1-jD-1Th"/>
<constraint firstItem="map-GD-PNR" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="DEr-N7-3nu"/>
<constraint firstItem="map-GD-PNR" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="U73-tZ-TAg"/>
<constraint firstItem="E2Q-uj-XYa" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="VGz-jI-kNC"/>
</constraints>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="52" y="374.66266866566718"/>
</scene>
</scenes>
<resources>
<image name="Launch" width="188" height="78"/>
</resources>
</document>
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15E65" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>
@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>LayaBox2.0</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>NSCameraUsageDescription</key>
<string></string>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UIRequiresFullScreen</key>
<true/>
<key>UIStatusBarHidden</key>
<true/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
@@ -0,0 +1,6 @@
#import <Foundation/NSObject.h>
@interface JSBridge: NSObject
+(void)onScanResult:(NSString*)result;
@end
@@ -0,0 +1,87 @@
#import "JSBridge.h"
#import "AppDelegate.h"
#import "ViewController.h"
#import "UIFloatPanel.h"
#import "ScanViewController.h"
#import <UIKit/UINavigationController.h>
#import "NavViewController.h"
@implementation JSBridge
+(void)hideSplash
{
dispatch_async(dispatch_get_main_queue(), ^{
AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
[appDelegate.launchView hide];
});
}
+(void)setTips:(NSArray*)tips
{
dispatch_async(dispatch_get_main_queue(), ^{
AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
appDelegate.launchView.tips = tips;
});
}
+(void)setFontColor:(NSString*)color
{
dispatch_async(dispatch_get_main_queue(), ^{
AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
[appDelegate.launchView setFontColor:color];
});
}
+(void)bgColor:(NSString*)color
{
dispatch_async(dispatch_get_main_queue(), ^{
AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
[appDelegate.launchView setBackgroundColor:color];
});
}
+(void)loading:(NSNumber*)percent
{
dispatch_async(dispatch_get_main_queue(), ^{
AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
[appDelegate.launchView setPercent:percent.integerValue];
});
}
+(void)showTextInfo:(NSNumber*)show
{
dispatch_async(dispatch_get_main_queue(), ^{
AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
[appDelegate.launchView showTextInfo:show.intValue > 0];
});
}
+(void)showScanner:(NSNumber*)show
{
dispatch_async(dispatch_get_main_queue(), ^{
AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
if (show.intValue > 0)
{
[appDelegate.navigationController presentViewController:[[ScanViewController alloc] init] animated:NO completion:nil];
}
else
{
}
});
}
+(void)onScanResult:(NSString*)result
{
NSString* js = [[NSString alloc] initWithFormat:@"script.UIController.instance.onScanResult('%@')", result];
[[conchRuntime GetIOSConchRuntime] runJS:js];
}
+(void)showFloatPanel:(NSNumber*)show
{
dispatch_async(dispatch_get_main_queue(), ^{
if (show.intValue > 0)
{
[ViewController GetIOSViewController]->m_floatPanel.hidden = false;
}
else
{
[ViewController GetIOSViewController]->m_floatPanel.hidden = true;
}
});
}
@end
@@ -0,0 +1,13 @@
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface LaunchView : NSObject
-(id)initWithFrame:(CGRect)frame;
-(void)hide;
-(void)setFontColor:(NSString*)color;
-(void)setBackgroundColor:(NSString*)color;
-(void)showTextInfo:(Boolean)show;
@property (strong, nonatomic) UIView* view;
@property (strong, nonatomic) NSArray* tips;
@property (assign, nonatomic) NSInteger percent;
@end
@@ -0,0 +1,146 @@
#import "LaunchView.h"
static const NSTimeInterval REFRESH_INTERVAL = 1.0;
static const int LEAST_SHOW_TIME = 2;
@interface LaunchView()
@property (strong, nonatomic) UIViewController* viewController;
@property (assign, nonatomic) NSTimeInterval startTime;
@property (strong, nonatomic) dispatch_source_t timer;
@property (assign, nonatomic) NSInteger index;
@end
@implementation LaunchView
-(id)initWithFrame:(CGRect)frame
{
self = [super init];
if( self != nil )
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"LaunchScreen" bundle:nil];
_viewController = [storyboard instantiateViewControllerWithIdentifier:@"LaunchScreen"];
_view = _viewController.view;
_view.frame = frame;
_startTime = [[NSDate date] timeIntervalSince1970];
_percent = 0;
_index = 0;
__weak typeof(self) weakSelf = self;
dispatch_queue_t queue = dispatch_get_main_queue();
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), REFRESH_INTERVAL * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(_timer, ^{
NSInteger length = weakSelf.tips != nil ? weakSelf.tips.count : 0;
if (length > 0) {
if (weakSelf.index >= length) {
weakSelf.index = 0;
}
for (UIView* subView in weakSelf.view.subviews) {
if ([subView isKindOfClass:[UILabel class]]) {
UILabel* label = (UILabel*)subView;
label.text = [NSString stringWithFormat:@"%@(%%%ld)", [weakSelf.tips objectAtIndex:weakSelf.index], (long)weakSelf.percent];
}
}
weakSelf.index++;
}
});
dispatch_resume(_timer);
return self;
}
return nil;
}
-(void)hide
{
NSTimeInterval showTime = [[NSDate date] timeIntervalSince1970] - _startTime;
if (showTime >= LEAST_SHOW_TIME)
{
[_viewController.view removeFromSuperview];
dispatch_source_cancel(_timer);
}
else
{
NSTimeInterval timeLeft = LEAST_SHOW_TIME - showTime;
__weak typeof(self) weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeLeft * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[weakSelf.viewController.view removeFromSuperview];
dispatch_source_cancel(weakSelf.timer);
});
}
}
+ (UIColor *)colorWithHexString:(NSString*)color
{
NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
if ([cString length] < 6) {
return [UIColor clearColor];
}
if ([cString hasPrefix:@"0X"])
cString = [cString substringFromIndex:2];
if ([cString hasPrefix:@"#"])
cString = [cString substringFromIndex:1];
if ([cString length] != 6)
return [UIColor clearColor];
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
-(void)setFontColor:(NSString*)color
{
for (UIView* subView in self.view.subviews) {
if ([subView isKindOfClass:[UILabel class]]) {
UILabel* label = (UILabel*)subView;
label.textColor = [LaunchView colorWithHexString:color];
}
}
}
-(void)setPercent:(NSInteger)percent
{
_percent = percent;
if (_percent > 100) {
_percent = 100;
}
if (_percent < 0) {
_percent = 0;
}
NSInteger length = self.tips != nil ? self.tips.count : 0;
if (length > 0) {
if (self.index >= length) {
self.index = 0;
}
for (UIView* subView in self.view.subviews) {
if ([subView isKindOfClass:[UILabel class]]) {
UILabel* label = (UILabel*)subView;
label.text = [NSString stringWithFormat:@"%@(%ld%%)", [self.tips objectAtIndex:self.index], (long)self.percent];
}
}
}
if (_percent == 100) {
[self hide];
}
}
-(void)setBackgroundColor:(NSString*)color
{
_view.backgroundColor = [LaunchView colorWithHexString:color];
}
-(void)showTextInfo:(Boolean)show
{
for (UIView* subView in self.view.subviews) {
if ([subView isKindOfClass:[UILabel class]]) {
UILabel* label = (UILabel*)subView;
label.hidden = !show;
}
}
}
@end
@@ -0,0 +1,11 @@
#import <UIKit/UIKit.h>
#import <GLKit/GLKit.h>
#import <conchRuntime.h>
@interface NavViewController : UINavigationController
{
}
@end
@@ -0,0 +1,19 @@
#import "NavViewController.h"
@implementation NavViewController
- (void)viewDidLoad{
[super viewDidLoad];
self.navigationBar.hidden = TRUE;
}
- (BOOL)shouldAutorotate{
return [[self.viewControllers lastObject]shouldAutorotate];
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
return [[self.viewControllers lastObject]supportedInterfaceOrientations];
//return [conchConfig GetInstance]->m_nOrientationType;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
return [[self.viewControllers lastObject] preferredInterfaceOrientationForPresentation];
}
@end
@@ -0,0 +1,8 @@
#import <UIKit/UIKit.h>
@interface ScanViewController : UIViewController
@end
@@ -0,0 +1,220 @@
#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ViewController.h"
#import "JSBridge.h"
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_BOUNDS [UIScreen mainScreen].bounds
#define TOP (SCREEN_HEIGHT-220)/2
#define LEFT (SCREEN_WIDTH-220)/2
#define kScanRect CGRectMake(LEFT, TOP, 220, 220)
@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>{
int num;
BOOL upOrdown;
NSTimer * timer;
CAShapeLayer *cropLayer;
}
@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;
@property (strong,nonatomic)UIImageView * line;
@end
@implementation ScanViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)configView{
UIImageView * imageView = [[UIImageView alloc]initWithFrame:kScanRect];
imageView.image = [UIImage imageNamed:@"pick_bg"];
[self.view addSubview:imageView];
upOrdown = NO;
num =0;
_line = [[UIImageView alloc] initWithFrame:CGRectMake(LEFT, TOP+10, 220, 2)];
_line.image = [UIImage imageNamed:@"line.png"];
[self.view addSubview:_line];
timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
UIImage* pImageButtonBack = [UIImage imageNamed:@"close.png"];
float offset = 30;
float width = pImageButtonBack.size.width;
float height = pImageButtonBack.size.height;
UIButton* pButtonBack = [[UIButton alloc] initWithFrame:CGRectMake(0,0,width,height)];
pButtonBack.titleEdgeInsets = UIEdgeInsetsMake(44.0f, 0.0f, 0.0f, 0.0f);
//[pButtonBack setTitle:@"后退" forState:UIControlStateNormal];
[pButtonBack setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
pButtonBack.titleLabel.font = [UIFont systemFontOfSize:13.0];
[pButtonBack setBackgroundImage:pImageButtonBack forState:UIControlStateNormal];
pButtonBack.center = CGPointMake(offset,offset);
[pButtonBack addTarget:self action:@selector(buttonClickBack:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:pButtonBack];
}
-(void)buttonClickBack:(id)sender
{
[self dismissViewControllerAnimated:NO completion:nil];
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear: animated];
[self configView];
//[self setCropRect:kScanRect];
[self performSelector:@selector(setupCamera) withObject:nil afterDelay:0.3];
}
-(void)animation1
{
if (upOrdown == NO) {
num ++;
_line.frame = CGRectMake(LEFT, TOP+10+2*num, 220, 2);
if (2*num == 200) {
upOrdown = YES;
}
}
else {
num --;
_line.frame = CGRectMake(LEFT, TOP+10+2*num, 220, 2);
if (num == 0) {
upOrdown = NO;
}
}
}
- (void)setCropRect:(CGRect)cropRect{
cropLayer = [[CAShapeLayer alloc] init];
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, nil, cropRect);
CGPathAddRect(path, nil, self.view.bounds);
[cropLayer setFillRule:kCAFillRuleEvenOdd];
[cropLayer setPath:path];
[cropLayer setFillColor:[UIColor blackColor].CGColor];
[cropLayer setOpacity:0.6];
[cropLayer setNeedsDisplay];
[self.view.layer addSublayer:cropLayer];
}
- (void)setupCamera
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (device==nil) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
[self presentViewController:alert animated:YES completion:nil];
return;
}
// Device
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// Input
_input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
// Output
_output = [[AVCaptureMetadataOutput alloc]init];
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//设置扫描区域
CGFloat top = TOP/SCREEN_HEIGHT;
CGFloat left = LEFT/SCREEN_WIDTH;
CGFloat width = 220/SCREEN_WIDTH;
CGFloat height = 220/SCREEN_HEIGHT;
///top 与 left 互换 width 与 height 互换
[_output setRectOfInterest:CGRectMake(top,left, height, width)];
// Session
_session = [[AVCaptureSession alloc]init];
[_session setSessionPreset:AVCaptureSessionPresetHigh];
if ([_session canAddInput:self.input])
{
[_session addInput:self.input];
}
if ([_session canAddOutput:self.output])
{
[_session addOutput:self.output];
}
// 条码类型 AVMetadataObjectTypeQRCode
[_output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode, nil]];
// Preview
_preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
_preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
_preview.frame =self.view.layer.bounds;
[self.view.layer insertSublayer:_preview atIndex:0];
// Start
[_session startRunning];
}
#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
NSString *stringValue;
if ([metadataObjects count] >0)
{
//停止扫描
[_session stopRunning];
[timer setFireDate:[NSDate distantFuture]];
AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
stringValue = metadataObject.stringValue;
[JSBridge onScanResult:stringValue];
NSLog(@"scan result%@",stringValue);
[self dismissViewControllerAnimated:NO completion:nil];
} else {
NSLog(@"no scan result");
[self dismissViewControllerAnimated:NO completion:nil];
return;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)shouldAutorotate
{
return YES;//支持转屏
}
//-------------------------------------------------------------------------------
- (BOOL)prefersStatusBarHidden
{
return YES;//隐藏为YES,显示为NO
}
-(NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return UIInterfaceOrientationPortrait;
}
@end
@@ -0,0 +1,15 @@
#import <UIKit/UIKit.h>
#import <GLKit/GLKit.h>
@interface UIFloatPanel : UIImageView
{
GLKView* m_pGLView;
UIButton* m_pRefreshBtn;
UIButton* m_pBackBtn;
}
-(id)initWithParentView:(GLKView*)pGLView;
@end
@@ -0,0 +1,85 @@
#import "UIFloatPanel.h"
#import <objc/runtime.h>
#import "conchRuntime.h"
#import "conchConfig.h"
#import <UIKit/UIAlertController.h>
#import "AppDelegate.h"
#import "ScanViewController.h"
#import "NavViewController.h"
@implementation UIFloatPanel
-(id)initWithParentView:(GLKView*)pGLView
{
m_pGLView = pGLView;
UIImage* m_pImagePanel = [self imagesNamedFromCustomBundle:@"panel.png"];
self = [super initWithFrame:CGRectMake(0,0,m_pImagePanel.size.width,m_pImagePanel.size.height)];
if( self != nil )
{
self.userInteractionEnabled = TRUE;
[self setImage:m_pImagePanel];
[m_pGLView addSubview:self];
[self resetPosition];
UIImage* pImage = [self imagesNamedFromCustomBundle:@"btn_refresh_normal.png"];
float offset = m_pImagePanel.size.width * 0.15f;
float distance = (m_pImagePanel.size.width - 2 * offset) * 0.5f;
m_pRefreshBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, pImage.size.width, pImage.size.height)];
[m_pRefreshBtn setImage:[self imagesNamedFromCustomBundle:@"btn_refresh_normal.png"] forState:UIControlStateNormal];
[m_pRefreshBtn setImage:[self imagesNamedFromCustomBundle:@"btn_refresh_focused.png"] forState:UIControlStateHighlighted];
[m_pRefreshBtn setImage:[self imagesNamedFromCustomBundle:@"btn_refresh_pressed.png"] forState:UIControlStateSelected];
m_pRefreshBtn.center = CGPointMake(offset + distance * 0.5f,m_pImagePanel.size.height * 0.5f);
[m_pRefreshBtn addTarget:self action:@selector(buttonClickRefresh:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:m_pRefreshBtn];
pImage = [self imagesNamedFromCustomBundle:@"btn_back_normal.png"];
m_pBackBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, pImage.size.width, pImage.size.height)];
[m_pBackBtn setImage:[self imagesNamedFromCustomBundle:@"btn_back_normal.png"] forState:UIControlStateNormal];
[m_pBackBtn setImage:[self imagesNamedFromCustomBundle:@"btn_back_focused.png"] forState:UIControlStateHighlighted];
[m_pBackBtn setImage:[self imagesNamedFromCustomBundle:@"btn_back_pressed.png"] forState:UIControlStateSelected];
[m_pBackBtn addTarget:self action:@selector(buttonClickBack:) forControlEvents:UIControlEventTouchUpInside];
m_pBackBtn.center = CGPointMake(offset + distance * 1.5f, m_pImagePanel.size.height * 0.5f);
[self addSubview:m_pBackBtn];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(orientChange:)
name:UIDeviceOrientationDidChangeNotification
object:nil];
}
return self;
}
-(void)buttonClickBack:(id)sender
{
[[conchRuntime GetIOSConchRuntime] runJS:@"history.back()"];
}
-(void)buttonClickRefresh:(id)sender
{
[[conchRuntime GetIOSConchRuntime] runJS:@"reloadJS(true)"];
}
- (UIImage *)imagesNamedFromCustomBundle:(NSString *)imgName
{
NSString *bundlePath = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"libconchRuntime.bundle"];
NSString *img_path = [bundlePath stringByAppendingPathComponent:imgName];
return [UIImage imageWithContentsOfFile:img_path];
}
-(void)resetPosition
{
self.center = CGPointMake([[UIScreen mainScreen] bounds].size.width - 0.5f * self.bounds.size.width - 10, 30);
}
-(void)orientChange:(NSNotification *)aNotification
{
[self resetPosition];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}
@end
@@ -0,0 +1,24 @@
#import <UIKit/UIKit.h>
#import <GLKit/GLKit.h>
#import <conchRuntime.h>
@class UIFloatPanel;
@interface ViewController : GLKViewController
{
@public
GLKView* m_pGLKView;
EAGLContext* m_pGLContext;
conchRuntime* m_pConchRuntime;
CADisplayLink* m_displayLink;
UIFloatPanel* m_floatPanel;
}
+(ViewController*)GetIOSViewController;
-(id)init;
- (void)startDisplayLink;
- (void)handleDisplayLink:(CADisplayLink *)displayLink;
- (void)stopDisplayLink;
@end
@@ -0,0 +1,170 @@
#import "ViewController.h"
#import "UIFloatPanel.h"
@implementation ViewController
static ViewController* g_pIOSMainViewController = nil;
//------------------------------------------------------------------------------
+(ViewController*)GetIOSViewController
{
return g_pIOSMainViewController;
}
//------------------------------------------------------------------------------
-(id)init
{
self = [super init];
if( self != nil )
{
g_pIOSMainViewController = self;
return self;
}
return Nil;
}
//------------------------------------------------------------------------------
- (void)viewDidLoad
{
[super viewDidLoad];
//保持屏幕常亮,可以通过脚本设置
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
self->m_pGLContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];
if (self->m_pGLContext)
{
NSLog(@"iOS OpenGL ES 3.0 context created");
}
else
{
self->m_pGLContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
if (self->m_pGLContext)
{
NSLog(@"iOS OpenGL ES 2.0 context created");
}
else
{
NSLog(@"iOS OpenGL ES 2.0 context created failed");
}
}
m_pGLKView = (GLKView *)self.view;
m_pGLKView.context = self->m_pGLContext;
m_pGLKView.drawableDepthFormat = GLKViewDrawableDepthFormat24;
m_pGLKView.drawableStencilFormat = GLKViewDrawableStencilFormat8;
[EAGLContext setCurrentContext:self->m_pGLContext];
self.preferredFramesPerSecond = 10000;
//conchRuntime 初始化ConchRuntime引擎
m_pConchRuntime = [[conchRuntime alloc]initWithView:m_pGLKView EAGLContext:m_pGLContext downloadThreadNum:3];
[self prefersStatusBarHidden];
[self setNeedsStatusBarAppearanceUpdate];
//在主线程开这个DisplayLink会导致卡死。因为gl等待会导致事件函数无法调到。
m_displayLink=nullptr;
//[self startDisplayLink];
m_floatPanel = [[UIFloatPanel alloc] initWithParentView:m_pGLKView];
m_floatPanel.hidden = true;
}
- (void)startDisplayLink
{
m_displayLink = [CADisplayLink displayLinkWithTarget:self
selector:@selector(handleDisplayLink:)];
[m_displayLink addToRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
}
- (void)handleDisplayLink:(CADisplayLink *)displayLink
{
if( m_pConchRuntime){
[m_pConchRuntime onVsync:displayLink.timestamp*1000.0];
}
}
- (void)stopDisplayLink
{
if(m_displayLink)
[m_displayLink invalidate];
m_displayLink = nil;
}
//------------------------------------------------------------------------------
- (void)dealloc
{
[m_pConchRuntime destory];
[self tearDownGL];
if ( [EAGLContext currentContext] == self->m_pGLContext )
{
[EAGLContext setCurrentContext:nil];
}
[self stopDisplayLink];
m_floatPanel = nil;
}
//------------------------------------------------------------------------------
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
//conchRuntime 内存警告的时候的处理
[m_pConchRuntime didReceiveMemoryWarning];
}
//------------------------------------------------------------------------------
- (void)tearDownGL
{
[EAGLContext setCurrentContext:self->m_pGLContext];
}
//------------------------------------------------------------------------------
- (void)update
{
}
//------------------------------------------------------------------------------
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
//conchRuntime renderFrame
[m_pConchRuntime renderFrame];
}
//-------------------------------------------------------------------------------
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//conchRuntime touch
[m_pConchRuntime touchesBegan:touches withEvent:event];
}
//-------------------------------------------------------------------------------
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//conchRuntime touch
[m_pConchRuntime touchesMoved:touches withEvent:event];
}
//-------------------------------------------------------------------------------
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
//conchRuntime touch
[m_pConchRuntime touchesEnded:touches withEvent:event];
}
//-------------------------------------------------------------------------------
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
//conchRuntime touch
[m_pConchRuntime touchesCancelled:touches withEvent:event];
}
//-------------------------------------------------------------------------------
-(NSUInteger)supportedInterfaceOrientations
{
/*
UIInterfaceOrientationMaskPortrait, ===2
UIInterfaceOrientationMaskPortraitUpsideDown, ===4
UIInterfaceOrientationMaskLandscapeLeft, ===8
UIInterfaceOrientationMaskLandscapeRight, ===16
*/
return [conchConfig GetInstance]->m_nOrientationType;
}
//-------------------------------------------------------------------------------
- (BOOL)shouldAutorotate
{
return YES;//支持转屏
}
- (BOOL)prefersStatusBarHidden
{
return YES;//隐藏为YES,显示为NO
}
@end
@@ -0,0 +1,16 @@
#import <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>
@protocol JCIapProcessCtrlDelegate <NSObject>
@required
- (void)onSuccess:(NSString *)p_pProductionIdentifier quantity:(NSInteger)p_iNumber orderID:(NSString *)p_pszOrderID;
- (void)onFailed:(NSString *)p_pProductionIdentifier quantity:(NSInteger)p_iNumber orderID:(NSString *)p_pszOrderID;
@end
@interface IAPManager : NSObject<SKProductsRequestDelegate,SKPaymentTransactionObserver>
+ (IAPManager*) getInstance;
-(void)CZ:(NSString*) jsonParam;
- (id)initWithGameID:(NSString*)gameID andDelegate:(id<JCIapProcessCtrlDelegate>)delegate;
@end
@@ -0,0 +1,339 @@
#import "IAPManager.h"
#define __MAX_GAME_ID_SIZE 32
typedef void (^IAPProductsResponseBlock)(SKProductsRequest* request , SKProductsResponse* response);
typedef void (^IAPcheckReceiptCompleteResponseBlock)(NSString* response,NSError* error);
@interface IAPManager()<NSURLConnectionDataDelegate>
@property (nonatomic,copy) IAPProductsResponseBlock requestProductsBlock;
@property (nonatomic,copy) IAPcheckReceiptCompleteResponseBlock checkReceiptCompleteBlock;
@property (nonatomic,assign) id<JCIapProcessCtrlDelegate> delegate;
@property (nonatomic,strong) NSString* gameAppID;
@property (nonatomic,strong) SKProductsRequest *request;
@property (nonatomic,strong) NSString *strPlateform;
@property (nonatomic,assign) BOOL isProcessing;
@property (nonatomic,strong) NSMutableData* receiptRequestData;
@end
@implementation IAPManager
+ (IAPManager*) getInstance{
static IAPManager* iap = nil;
if (iap == nil){
iap = [IAPManager alloc];
}
return iap;
}
- (id)initWithGameID:(NSString*)gameID andDelegate:(id<JCIapProcessCtrlDelegate>)delegate{
if ((self = [super init])) {
NSAssert(gameID != nil,@"[IAP] gameID can not be nil");
NSAssert(gameID.length <= __MAX_GAME_ID_SIZE,@"gameID is too long");
self.gameAppID = [NSString stringWithString:gameID];
NSAssert(delegate != nil, @"[IAP] delegate can not be nil");
self.delegate = delegate;
self.strPlateform = [NSString stringWithFormat:@"%@,%@,%@", [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion]];
NSLog(@"[IAP]plateform info: %@\n", self.strPlateform);
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
self.isProcessing = NO;
}
return self;
}
- (void)dealloc
{
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
- (void)requestProducts:(NSSet *)productIdentifiers onCompletion:(IAPProductsResponseBlock)completion {
self.request = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
self.request.delegate = self;
self.requestProductsBlock = completion;
[self.request start];
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
self.request = nil;
if(self.requestProductsBlock) {
self.requestProductsBlock (request,response);
}
}
//-------------------------------------------------------------------------------
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
NSLog(@"[IAP] SKPaymentTransactionStatePurchased");
[self doVerifyTransaction:transaction];
}
- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
NSLog(@"[IAP] SKPaymentTransactionStateRestored");
[self doVerifyTransaction:transaction];
}
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
NSLog(@"[IAP] Transaction error: %@ %ld", transaction.error.localizedDescription,(long)transaction.error.code);
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
NSLog(@"[IAP] SKPaymentTransactionStateFailed");
NSMutableDictionary *paymentmulti =(NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:transaction.payment.requestData];
NSString* _order_id = [paymentmulti objectForKey:@"order_id"];
self.isProcessing = NO;
[self.delegate onFailed:transaction.payment.productIdentifier quantity:transaction.payment.quantity orderID:_order_id];
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
for (SKPaymentTransaction *transaction in transactions)
{
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchased:
[self completeTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
[self failedTransaction:transaction];
break;
case SKPaymentTransactionStateRestored:
[self restoreTransaction:transaction];
default:
break;
}
}
}
//-------------------------------------------------------------------------------
-(void)CZ:(NSString*) jsonParam
{
if (self.isProcessing == YES){
self.isProcessing = NO;
NSLog(@"[IAP] another payments is processing!\n");
return;
}
self.isProcessing = YES;
NSLog(@"[IAP] this is MarketAppStore method pay param=%@",jsonParam);
if(jsonParam==NULL)
{
self.isProcessing = NO;
NSLog(@"[IAP] recharge param is nil!\n");
[self.delegate onFailed:@"nill" quantity:0 orderID:@"nill"];
return;
}
NSData* pJsonData = [jsonParam dataUsingEncoding:NSUTF8StringEncoding];
NSError* pError;
NSDictionary* pJson = [NSJSONSerialization JSONObjectWithData:pJsonData options:kNilOptions error:&pError];
if( !pError )
{
NSString* sProductID = [pJson objectForKey:@"product_id"];
int nNum = [[pJson objectForKey:@"amount"] intValue];
NSString* sOrderID = [pJson objectForKey:@"order_id"];
NSString* sCallbackURL = [pJson objectForKey:@"callback_uri"];
NSLog(@"[IAP] buyProps: product_id=%@, amount=%d, order_id=%@,callbackurl=%@",sProductID, nNum, sOrderID,sCallbackURL );
if( nNum <= 0 || nil == sProductID || nil == sOrderID || nil == sCallbackURL)
{
self.isProcessing = NO;
NSLog(@"[IAP] param error!\n");
[self.delegate onFailed:sProductID quantity:nNum orderID:sOrderID];
return;
}
if([SKPaymentQueue canMakePayments] == NO)
{
self.isProcessing = NO;
NSLog(@"[IAP] can not make payments!\n");
[self.delegate onFailed:sProductID quantity:nNum orderID:sOrderID];
return;
}
NSArray* transactions = [SKPaymentQueue defaultQueue].transactions;
if (transactions.count > 0)
{
//检测是否有未完成的交易
SKPaymentTransaction* transaction = [transactions firstObject];
if (transaction.transactionState == SKPaymentTransactionStatePurchased)
{
NSLog(@"[IAP] process uncompleteed transaction");
[self doVerifyTransaction:transaction];
}
}
NSLog(@"[IAP] 开始向苹果请求产品信息");
[self requestProducts:[[NSSet alloc] initWithObjects:sProductID, nil] onCompletion:^(SKProductsRequest* request,SKProductsResponse* response)
{
NSLog(@"[IAP] 苹果返回产品信息。");
if(response.products.count > 0 ) {
SKProduct* product =response.products[0];
NSMutableString *resOutput = [[NSMutableString alloc] init];
[resOutput appendString:@"[IAP] IAP Response Info\n"];
[resOutput appendFormat:@"%@,%@,%@,%@,%@\n",
product.localizedTitle, // 本地化标题
product.localizedDescription, // 本地化描述
product.price, // 价格
product.priceLocale, // 地域
product.productIdentifier]; // 产品标识符
NSLog(@"%@",resOutput);
SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:product];
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject:sOrderID forKey:@"order_id"];
[dict setObject:sCallbackURL forKey:@"backurl"];
[dict setObject:self.gameAppID forKey:@"gameid"];
NSData* pData = [NSKeyedArchiver archivedDataWithRootObject:dict];
payment.requestData = pData;
payment.quantity = nNum;
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
else{
self.isProcessing = NO;
NSLog(@"[IAP] invalid product!\n");
[self.delegate onFailed:sProductID quantity:nNum orderID:sOrderID];
}
// 错误的产品 ID 回馈
NSMutableString *resOutput = [[NSMutableString alloc] init];
for( NSString *invalidProductId in response.invalidProductIdentifiers )
{
[resOutput appendFormat:@"[IAP] Invalid product id: %@\n",invalidProductId];
}
NSLog(@"%@",resOutput);
}];
}
else
{
self.isProcessing = NO;
NSLog(@"[IAP] buyProps:parser json error");
[self.delegate onFailed:@"nill" quantity:0 orderID:@"nill"];
}
}
// 向验证服务器发起验证请求
- (void)doVerifyTransaction: (SKPaymentTransaction *)transaction
{
if (transaction == nil)
return;
if(NULL==transaction.payment.requestData)
{
self.isProcessing = NO;
NSLog(@"[IAP] transDoVerifyTransaction requestData is null");
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
[self.delegate onFailed:@"nill" quantity:0 orderID:@"nill"];
return;
}
NSMutableDictionary *paymentmulti =(NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:transaction.payment.requestData];//
NSString* _order_id = [paymentmulti objectForKey:@"order_id"];
NSString* _backurl = [paymentmulti objectForKey:@"backurl"];
NSString* _gameid = [paymentmulti objectForKey:@"gameid"];
NSLog(@"[IAP] order:%@backurl:%@gameid:%@",_order_id,_backurl,_gameid);
NSString* pszBase64 = [transaction.transactionReceipt base64Encoding];
if(NULL==_order_id||NULL==_backurl||NULL==_gameid||NULL==self.strPlateform||NULL==transaction.payment.productIdentifier||NULL==transaction.transactionIdentifier)
{
self.isProcessing = NO;
NSLog(@"[IAP] doVerifyTransaction something is NULL");
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
[self.delegate onFailed:@"nill" quantity:0 orderID:@"nill"];
return;
}
NSMutableString *sendParam = [[NSMutableString alloc] init];
[sendParam appendFormat:@"plateform=%@",self.strPlateform];
[sendParam appendFormat:@"&order-id=%@",_order_id];
[sendParam appendFormat:@"&game-id=%@",_gameid];
[sendParam appendFormat:@"&production-id=%@",transaction.payment.productIdentifier];
[sendParam appendFormat:@"&transaction-id=%@",transaction.transactionIdentifier];
[sendParam appendFormat:@"&receipt-data=%@",pszBase64];
NSData* data = [sendParam dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"[IAP] pruchase backurl = %@",_backurl);
NSLog(@"[IAP] pruchase param = %@",sendParam);
NSInteger amount = transaction.payment.quantity;
[self checkReceipt:_backurl withData:data onCompletion:^(NSString* response,NSError* error){
if (error == nil){
NSLog(@"[IAP] web result = %@",response);
NSData* pJsonData = [response dataUsingEncoding:NSUTF8StringEncoding];
NSError* pError;
NSDictionary* pJson = [NSJSONSerialization JSONObjectWithData:pJsonData options:kNilOptions error:&pError];
if( !pError ){
NSString* resultCode = [pJson objectForKey:@"error-code"];
int nCode = [resultCode intValue];
if (nCode == 0){
NSLog(@"[IAP] verify success!");
self.isProcessing = NO;
[self.delegate onSuccess:transaction.payment.productIdentifier quantity:amount orderID:_order_id];
}
else{
NSLog(@"[IAP] verify err code = %@ info = %@",resultCode,[pJson objectForKey:@"error-info"]);
self.isProcessing = NO;
[self.delegate onFailed:transaction.payment.productIdentifier quantity:amount orderID:_order_id];
}
}
else{
self.isProcessing = NO;
NSLog(@"[IAP] An error happened while serializing the JSON data.");
[self.delegate onFailed:transaction.payment.productIdentifier quantity:amount orderID:_order_id];
}
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
else{
self.isProcessing = NO;
[self.delegate onFailed:transaction.payment.productIdentifier quantity:amount orderID:_order_id];
}
}];
}
- (void)checkReceipt:(NSString*)url withData:(NSData*)receiptData onCompletion:(IAPcheckReceiptCompleteResponseBlock)completion
{
self.checkReceiptCompleteBlock = completion;
NSURL* requestURL = [NSURL URLWithString:url];
NSMutableURLRequest* req = [[NSMutableURLRequest alloc] initWithURL:requestURL];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:receiptData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if(conn) {
self.receiptRequestData = [[NSMutableData alloc] init];
} else {
NSError* error = nil;
NSMutableDictionary* errorDetail = [[NSMutableDictionary alloc] init];
[errorDetail setValue:@"Can't create connection" forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:@"IAPManagerError" code:100 userInfo:errorDetail];
if(self.checkReceiptCompleteBlock) {
self.checkReceiptCompleteBlock(nil,error);
}
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"[IAP] Cannot transmit receipt data. %@",[error localizedDescription]);
if(self.checkReceiptCompleteBlock) {
self.checkReceiptCompleteBlock(nil,error);
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.receiptRequestData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.receiptRequestData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *response = [[NSString alloc] initWithData:self.receiptRequestData encoding:NSUTF8StringEncoding];
if(self.checkReceiptCompleteBlock) {
self.checkReceiptCompleteBlock(response,nil);
}
}
@end
+16
View File
@@ -0,0 +1,16 @@
//
// main.m
// LayaBox
//
// Created by LayaBox on 3/7/16.
// Copyright © 2016 LayaBox. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
@@ -0,0 +1,39 @@
//
// LayaBoxTests.m
// LayaBoxTests
//
// Created by LayaBox on 3/7/16.
// Copyright © 2016 LayaBox. All rights reserved.
//
#import <XCTest/XCTest.h>
@interface LayaBoxTests : XCTestCase
@end
@implementation LayaBoxTests
- (void)setUp {
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
}
- (void)tearDown {
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
}
- (void)testExample {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
- (void)testPerformanceExample {
// This is an example of a performance test case.
[self measureBlock:^{
// Put the code you want to measure the time of here.
}];
}
@end
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:../../webglPlus/proj.ios/webglPlus.xcodeproj">
</FileRef>
<FileRef
location = "group:../../common/proj.ios/common.xcodeproj">
</FileRef>
<FileRef
location = "group:../../render/proj.ios/render.xcodeproj">
</FileRef>
<FileRef
location = "group:../../conchRuntime/proj.ios/conchRuntime.xcodeproj">
</FileRef>
<FileRef
location = "container:LayaBox.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
{
"name":"layaApp",
"version":"1.0.0",
"devUpdateUrl":"",
"updateUrl":"http://localhost:8899/layaAppUpdate/layaApp/v2.1/",
"updateDelay":0,
"mainjs":"index.js"
}
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
LayaBox
@@ -0,0 +1,5 @@
gameID=layabox
checkNetwork=1
orientation=2
notification=0
ThreadMode=1
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 670 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 408 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 543 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 459 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 377 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 782 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 572 B

File diff suppressed because it is too large Load Diff
@@ -0,0 +1,93 @@
function async(gen) {
"use strict";
var log = console.log;
var g = gen();
let nr = null;
function cast(value) {
return value instanceof Promise && value.constructor === Promise ? value : new Promise(function () { });
}
function thennext(v) {
nr = g.next(v);
var p = nr.value;
nr.done ? (0) : cast(p).then(thennext, function (e) { console.log('async reject:' + e); thennext(null); }).catch(function (r) {
alert(`${r}
${r.stack}`);
});
}
thennext(void 0);
}
exports.async = async;
//延时
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
exports.delay = delay;
//下载图片
function loadImage(src) {
return new Promise((resolve, reject) => {
var img = new Image();
img.src = src;
img.onload = () => { resolve(img); };
img.onerror = () => {
//reject('file load err:' + src);
resolve(null);
};
});
}
exports.loadImage = loadImage;
//下载文本文件
function loadText(src) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', src);
xhr.onload = () => { resolve(xhr.responseText); };
xhr.onerror = (e) => {
//if (reject)
// reject('download xhr error:' + src + '. e=' + e);
resolve(null);
};
xhr.send();
});
}
exports.loadText = loadText;
function downloadSync(url, bin, onprog) {
return new Promise(function (resolve, reject) {
var f = new conch_File(url);
var fr = new conch_FileReader();
fr.setIgnoreError(true);
fr.onload = () => {
console.log('download end');
resolve(fr.result);
};
fr.onerror = (e) => { console.log('onerror ' + e);
//if (reject)
// reject(e);
resolve(null);
};
fr.onprogress = onprog;
if (bin)
fr.readAsArrayBuffer(f);
else
fr.readAsText(f);
});
}
exports.downloadSync = downloadSync;
//直到func返回true,tm是间隔
function check(func, tm) {
return new Promise(function (resolve, reject) {
function checkFunc() {
if (func()) {
clearInterval(chker);
resolve(1);
}
}
var chker = setInterval(checkFunc, tm);
});
}
function regGlobal(window) {
}
exports.regGlobal = regGlobal;
window['async'] = async;
window['delay'] = delay;
window['downloadSync'] = downloadSync;
window['asynccheck'] = check;
@@ -0,0 +1,109 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const test = require("./unitTest");
function AllTest() {
this.test_clone = function (test) {
try {
var b = document.createElement('audio');
var c = b.cloneNode(false);
c.addEventListener('', null);
}
catch (e) {
test.err(`
cloneNode之后,应该有 addEventListener 函数。
`);
}
};
this.testEventDispatch = function (test) {
var called = false;
var canv = document.createElement('canvas');
document.body.appendChild(canv);
canv.addEventListener('mmousemove', (evt) => {
called = true;
});
var evt = new MouseEvent('mmousemove');
evt.clientX = 100;
evt.clientY = 100;
canv.dispatchEvent(evt);
test.eq(called, true, '事件应该能正确发送给canvas');
document.removeChild(canv);
test.neq(window.document._topElement, canv, 'removeChild之后,应该维护_topElement');
};
this.testEvent_phase = function (test) {
var canv = document.createElement('canvas');
var result = [];
document.body.appendChild(canv);
document.addEventListener('mousedown', (evt) => {
result.push(1);
}, true);
document.body.addEventListener('mousedown', (evt) => {
result.push(2);
}, true);
canv.addEventListener('mousedown', (evt) => {
result.push(3);
});
document.body.addEventListener('mousedown', (evt) => {
result.push(4);
});
document.addEventListener('mousedown', (evt) => {
result.push(5);
});
window.addEventListener('mousedown', (evt) => {
result.push(6);
});
var evt = new MouseEvent('mousedown');
evt.clientX = 100;
evt.clientY = 100;
canv.dispatchEvent(evt);
document.removeChild(canv);
};
this.testRuntimeVersion = function (test) {
var rv = conchConfig.getRuntimeVersion();
var b = rv.indexOf('conch');
};
this.testABToC = function (test) {
};
this.testZip = function (test) {
var zf = new ZipFile();
zf.setSrc('');
zf.forEach((id, name, dir, sz) => {
var ab = zf.readFile(id);
});
zf.close();
};
this.testFile = function (test) {
var abv = new Uint32Array([1, 2, 3]);
fs_writeFileSync('d:/temp/ddd.d', abv.buffer);
var ab = fs_readFileSync('d:/temp/ddd.d');
var v1 = new Uint32Array(ab);
if (v1.byteLength != 12 || v1[0] != 1 || v1[1] != 2 || v1[2] != 3)
alert('error:' + arguments.callee.name);
alert(fs_readdirSync('d:/temp'));
};
this.testWebSocket = function (test) {
var ws = new WebSocket('');
};
this.testMD5 = function (test) {
var result = '2a1dd1e1e59d0a384c26951e316cd7e6';
test.eq(result, calcmd5(new Uint32Array([1, 2, 3]).buffer), 'md5计算不正确');
};
this.testPost = function (test) {
var ab = new Uint32Array([0, 1, 2]);
conch._postUrl('http://localhost:8888/testpost', 1, ab.buffer, null, (buf) => {
}, (e) => {
}, () => {
return 0;
});
};
this.testUrlEncode = function () {
};
this.testFileReader = function (test) {
var f = new File('file:///d:/temp/test.sh');
var fr = new FileReader();
fr.onload = function () {
alert('ok ' + fr.result);
};
fr.readAsText(f);
};
}
test.testall(new AllTest(), "");
@@ -0,0 +1,115 @@
class loadingView
{
constructor()
{
this.sOS = conchConfig.getOS();
if (this.sOS == "Conch-ios")
{
this.bridge = PlatformClass.createClass("JSBridge");
}
else if (this.sOS == "Conch-android")
{
this.bridge = PlatformClass.createClass("demo.JSBridge");
}
}
set loadingAutoClose(value)
{
this._loadingAutoClose = value;
}
get loadingAutoClose()
{
return this._loadingAutoClose;
}
set showTextInfo(value)
{
this._showTextInfo = value;
if(this.bridge)
{
if (this.sOS == "Conch-ios")
{
this.bridge.call("showTextInfo:",value);
}
else if(this.sOS == "Conch-android")
{
this.bridge.call("showTextInfo",value);
}
}
}
get showTextInfo()
{
return this._showTextInfo;
}
bgColor(value)
{
if(this.bridge)
{
if (this.sOS == "Conch-ios")
{
this.bridge.call("bgColor:",value);
}
else if(this.sOS == "Conch-android")
{
this.bridge.call("bgColor",value);
}
}
}
setFontColor(value)
{
if(this.bridge)
{
if (this.sOS == "Conch-ios")
{
this.bridge.call("setFontColor:",value);
}
else if(this.sOS == "Conch-android")
{
this.bridge.call("setFontColor",value);
}
}
}
setTips(value)
{
if(this.bridge)
{
if (this.sOS == "Conch-ios")
{
this.bridge.call("setTips:",value);
}
else if(this.sOS == "Conch-android")
{
this.bridge.call("setTips",value);
}
}
}
loading(value)
{
if(this.bridge)
{
if (this.sOS == "Conch-ios")
{
this.bridge.call("loading:",value);
}
else if(this.sOS == "Conch-android")
{
this.bridge.call("loading",value);
}
}
}
hideLoadingView()
{
this.bridge.call("hideSplash");
}
}
window.loadingView = new loadingView();
if(window.loadingView)
{
window.loadingView.loadingAutoClose=true;//true代表当动画播放完毕,自动进入游戏。false为开发者手动控制
window.loadingView.bgColor("#000000");//设置背景颜色
window.loadingView.setFontColor("#ffffff");//设置字体颜色
window.loadingView.setTips(["新世界的大门即将打开","敌军还有30秒抵达战场","妈妈说,心急吃不了热豆腐"]);//设置tips数组,会随机出现
}
window.onLayaInitError=function(e)
{
console.log("onLayaInitError error=" + e);
alert("加载游戏失败,可能由于您的网络不稳定,请退出重进");
}
@@ -0,0 +1,356 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
window._conchInfo = { version: '2.1.3.1' };
var _inline = !conchConfig.localizable;
console.log('====================================================== ');
console.log(' LAYA CONCH ');
console.log(' runtimeversion:' + conchConfig.getRuntimeVersion());
console.log(' jsversion:' + window._conchInfo.version);
console.log(' isplug:' + conchConfig.getIsPlug());
console.log('======================================================');
function log(m) {
console.log(m);
}
if (conchConfig.getOS() == "Conch-ios") {
require('promise');
}
function loadLib(url) {
var script = document.createElement("script");
if (url.indexOf("laya.physics3D.js") >= 0) {
url = url.replace("laya.physics3D.js", "laya.physics3D.runtime.js");
}
script.src = url;
script.onerror = function () {
if (window["onLayaInitError"]) {
window["onLayaInitError"]("Load script error");
}
};
document.head.appendChild(script);
}
window['loadLib'] = loadLib;
const asyncs = require("async");
function initFreeType() {
return __awaiter(this, void 0, void 0, function* () {
var sOS = conchConfig.getOS();
var bRet = false;
var sTempFontPath = conch.getCachePath() + "/runtimeFont/";
if (!fs_exists(sTempFontPath)) {
fs_mkdir(sTempFontPath);
}
sTempFontPath += "layabox.ttf";
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile(sTempFontPath);
if (bRet == false) {
var assetFontData = conch.readFileFromAsset('font/layabox.ttf', 'raw');
if (assetFontData) {
fs_writeFileSync(sTempFontPath, assetFontData);
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile(sTempFontPath);
}
}
if (!bRet) {
if (sOS == "Conch-window") {
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("C:/Windows/Fonts/simhei.ttf");
}
else if (sOS == "Conch-android") {
var fSystemVersion = navigator.sv;
if (fSystemVersion >= 2.0 && fSystemVersion < 5.0) {
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("/system/fonts/DFHEIA5A.ttf");
if (bRet == false) {
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("/system/fonts/DroidSansFallback.ttf");
}
}
else if (fSystemVersion >= 5.0 && fSystemVersion < 6.0) {
var vDefaultStrings = [];
vDefaultStrings.push("/system/fonts/NotoSansHans-Regular.otf");
vDefaultStrings.push("/system/fonts/Roboto-Regular.ttf");
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile(vDefaultStrings.join('|'));
}
else if (fSystemVersion >= 6.0 && fSystemVersion < 7.0) {
var vDefaultStrings = [];
vDefaultStrings.push("/system/fonts/NotoSansSC-Regular.otf");
vDefaultStrings.push("/system/fonts/Roboto-Regular.ttf");
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile(vDefaultStrings.join('|'));
}
else if (fSystemVersion >= 7.0 && fSystemVersion < 8.0) {
bRet = false;
}
}
else if (sOS == "Conch-ios") {
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("");
}
}
if (bRet == false) {
log('字体初始化失败,从网络下载字体...');
var data = (yield asyncs.downloadSync(location.fullpath + '/font/simhei.ttf', true, null));
if (!data) {
data = (yield asyncs.downloadSync('http://runtime.layabox.com/font/simhei.ttf', true, null));
}
if (!data) {
alert('下载字体失败。 ');
return;
}
fs_writeFileSync(sTempFontPath, data);
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile(sTempFontPath);
}
if (!bRet) {
log('字体初始化失败。');
}
});
}
function setOrientation(s) {
var nameToVal = {
landscape: 0, portrait: 1, user: 2, behind: 3, sensor: 4, nosensor: 5, sensor_landscape: 6, sensorLandscape: 6,
sensor_portrait: 7, sensorPortrait: 7, reverse_landscape: 8, reverseLandscape: 8, reverse_portrait: 9, reversePortrait: 9, full_sensor: 10, fullSensor: 10,
};
var nOri = (function (name) {
try {
var n = nameToVal[name];
return n || 0;
}
catch (e) {
return 0;
}
})(s);
conchConfig.setScreenOrientation(nOri);
;
}
Object.defineProperty(window, 'screenOrientation', {
get: function () {
return window.___screenOri;
},
set: function (v) {
window.___screenOri = v;
setOrientation(v);
}
});
function startApp(data) {
var jsonobj = null;
try {
jsonobj = JSON.parse(data);
}
catch (e) {
console.log("Error:start page parse error! \n " + data);
return;
}
jsonobj.scripts.forEach((v) => {
var t = document.createElement("script");
t["src"] = v;
t.onerror = function () {
if (window["onLayaInitError"]) {
window["onLayaInitError"]("Load script error");
}
};
document.head.appendChild(t);
});
if (jsonobj.screenOrientation)
setOrientation(jsonobj.screenOrientation);
else if (jsonobj.screenorientation)
setOrientation(jsonobj.screenorientation);
else
setOrientation("sensor_landscape");
document.createElement("script").text = "window.onload&&window.onload()";
}
function loadApp(url) {
return __awaiter(this, void 0, void 0, function* () {
var urllen = url.length;
if (urllen < 2)
return;
url = url.trim();
if (url.substring(urllen - 1) === '/')
url = url + 'runtime.json';
url = url.replace(/.html$/i, '.json');
if (url.indexOf('http://stand.alone.version') == 0)
_inline = false;
if (!_inline) {
url = 'http://stand.alone.version/index.js';
}
console.log("loadApp:" + url);
if (history.length <= 0) {
history._push(url);
}
if (url.length < 2)
return;
location.setHref(url);
var urlpath = location.fullpath + '/';
var cache = window.appcache = new AppCache(urlpath);
document.loadCookie();
yield initFreeType();
try {
require("config");
}
catch (e) {
}
var isDccOk = true;
function updateDcc() {
return __awaiter(this, void 0, void 0, function* () {
cache.setResourceID('appurl', urlpath);
var curassets = cache.getResourceID('netassetsid');
var assetsidStr = (yield asyncs.downloadSync(urlpath + 'update/assetsid.txt?rand=' + Math.random() * Date.now(), false, null));
console.log("assetsid old:" + curassets + " new:" + assetsidStr);
if (!assetsidStr) {
if (curassets && curassets != "") {
if (window["onLayaInitError"]) {
isDccOk = false;
window["onLayaInitError"]("Update DCC get assetsid error");
}
}
}
else {
if (curassets != assetsidStr) {
log('need update;');
var txtdcc = '';
var bindcc = yield asyncs.downloadSync(urlpath + 'update/filetable.bin?' + assetsidStr, true, null);
if (!bindcc || !(bindcc instanceof ArrayBuffer)) {
txtdcc = (yield asyncs.downloadSync(urlpath + 'update/filetable.txt?' + assetsidStr, false, null));
}
else {
if (bindcc.byteLength % 8 != 0) {
log('下载的的filetable.bin的长度不对。是不是错了。');
}
else {
var v = new Uint32Array(bindcc);
if (v[0] != 0xffeeddcc || v[1] != 1) {
log('dcc.bin file err!');
}
else {
if (v[2] == 0x00ffffff) {
var stp = (4 + 8) / 2;
var md5int = v.slice(4, 12);
var md5char = new Uint8Array(md5int.buffer);
var so = String.fromCharCode.apply(null, md5char);
console.log('--------------------------------------------');
console.log('so=' + so);
console.log('netid=' + assetsidStr);
if (so == assetsidStr) {
for (var ii = stp, isz = v.length / 2; ii < isz; ii++)
txtdcc += v[ii * 2].toString(16) + ' ' + v[ii * 2 + 1].toString(16) + '\n';
}
}
else {
console.log('----------------old format');
for (var ii = 1, isz = v.length / 2; ii < isz; ii++)
txtdcc += v[ii * 2].toString(16) + ' ' + v[ii * 2 + 1].toString(16) + '\n';
}
}
}
}
if (txtdcc && txtdcc.length > 0) {
cache.saveFileTable(txtdcc);
window.appcache = cache = new AppCache(urlpath);
cache.setResourceID('netassetsid', assetsidStr);
}
else {
if (window["onLayaInitError"]) {
isDccOk = false;
window["onLayaInitError"]("Update DCC get filetable error");
}
}
}
}
});
}
if (_inline) {
yield updateDcc();
if (!isDccOk) {
console.log("init dcc fail");
return;
}
}
var data = yield asyncs.loadText(url);
for (var n = 0; n < 3 && !data; n++) {
data = yield asyncs.loadText(url);
}
if (!data) {
if (window["loadingView"]) {
window["loadingView"].setFontColor("#FF0000");
window["loadingView"].setTips(['网络异常,请检查您的网络或与开发商联系。']);
}
data = cache.loadCachedURL(url);
if (!data || data.length <= 0)
if (window["onLayaInitError"]) {
window["onLayaInitError"]("Load start url error");
}
return;
}
console.log("");
var qpos = url.indexOf('?');
if (qpos < 0)
qpos = url.length;
if (url.substr(qpos - 3, 3) === '.js') {
window.eval(data + `
//@ sourceURL=${url}
`);
document.createElement("script").text = "window.onload&&window.onload()";
}
else {
startApp(data);
}
if (window["loadingView"] && window["loadingView"].loadingAutoClose) {
window["loadingView"].hideLoadingView();
}
});
}
window.document.addEventListener('keydown', function (e) {
switch (e.keyCode) {
case 116:
reloadJS(true);
break;
case 117:
history.back();
break;
case 118:
break;
case 119:
break;
case 120:
gc();
break;
}
});
window.loadConchUrl = loadApp;
window['updateByZip'] = function (url, onEvent, onEnd) {
let cachePath = conch.getCachePath();
let localfile = cachePath + url.substr(url.lastIndexOf('/'));
downloadBigFile(url, localfile, (total, now, speed) => {
onEvent('downloading', Math.floor((now / total) * 100), null);
return false;
}, (curlret, httpret) => {
if (curlret != 0 || httpret < 200 || httpret >= 300) {
onEvent('downloadError');
}
else {
onEvent('downloadOK');
let zip = new ZipFile();
if (zip.setSrc(localfile)) {
zip.forEach((id, name, dir, sz) => {
if (!dir) {
let buf = zip.readFile(id);
let fid = window.appcache.hashstr('/' + name);
if (window.appcache.updateFile(fid, 0, buf, false)) {
onEvent('updating', null, name);
}
else {
onEvent("updateError", null, name);
}
}
});
zip.close();
if (onEnd)
onEnd(localfile);
}
else {
console.log("set zip src error!");
onEvent('unknownError');
}
}
}, 10, 100000000);
};
loadApp(conch.presetUrl || "http://nativetest.layabox.com/layaplayer2.0.1/index.js");
@@ -0,0 +1,233 @@
(function (root) {
// Store setTimeout reference so promise-polyfill will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var setTimeoutFunc = setTimeout;
function noop() {}
// Polyfill for Function.prototype.bind
function bind(fn, thisArg) {
return function () {
fn.apply(thisArg, arguments);
};
}
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
if (typeof fn !== 'function') throw new TypeError('not a function');
this._state = 0;
this._handled = false;
this._value = undefined;
this._deferreds = [];
doResolve(fn, this);
}
function handle(self, deferred) {
while (self._state === 3) {
self = self._value;
}
if (self._state === 0) {
self._deferreds.push(deferred);
return;
}
self._handled = true;
Promise._immediateFn(function () {
var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
if (cb === null) {
(self._state === 1 ? resolve : reject)(deferred.promise, self._value);
return;
}
var ret;
try {
ret = cb(self._value);
} catch (e) {
reject(deferred.promise, e);
return;
}
resolve(deferred.promise, ret);
});
}
function resolve(self, newValue) {
try {
// Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.');
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then;
if (newValue instanceof Promise) {
self._state = 3;
self._value = newValue;
finale(self);
return;
} else if (typeof then === 'function') {
doResolve(bind(then, newValue), self);
return;
}
}
self._state = 1;
self._value = newValue;
finale(self);
} catch (e) {
reject(self, e);
}
}
function reject(self, newValue) {
self._state = 2;
self._value = newValue;
finale(self);
}
function finale(self) {
if (self._state === 2 && self._deferreds.length === 0) {
Promise._immediateFn(function() {
if (!self._handled) {
Promise._unhandledRejectionFn(self._value);
}
});
}
for (var i = 0, len = self._deferreds.length; i < len; i++) {
handle(self, self._deferreds[i]);
}
self._deferreds = null;
}
function Handler(onFulfilled, onRejected, promise) {
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.promise = promise;
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, self) {
var done = false;
try {
fn(function (value) {
if (done) return;
done = true;
resolve(self, value);
}, function (reason) {
if (done) return;
done = true;
reject(self, reason);
});
} catch (ex) {
if (done) return;
done = true;
reject(self, ex);
}
}
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
var prom = new (this.constructor)(noop);
handle(this, new Handler(onFulfilled, onRejected, prom));
return prom;
};
Promise.all = function (arr) {
var args = Array.prototype.slice.call(arr);
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([]);
var remaining = args.length;
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then;
if (typeof then === 'function') {
then.call(val, function (val) {
res(i, val);
}, reject);
return;
}
}
args[i] = val;
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex);
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i]);
}
});
};
Promise.resolve = function (value) {
if (value && typeof value === 'object' && value.constructor === Promise) {
return value;
}
return new Promise(function (resolve) {
resolve(value);
});
};
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
};
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
for (var i = 0, len = values.length; i < len; i++) {
values[i].then(resolve, reject);
}
});
};
// Use polyfill for setImmediate for performance gains
Promise._immediateFn = (typeof setImmediate === 'function' && function (fn) { setImmediate(fn); }) ||
function (fn) {
setTimeoutFunc(fn, 0);
};
Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
if (typeof console !== 'undefined' && console) {
console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
}
};
/**
* Set the immediate function to execute callbacks
* @param fn {function} Function to execute
* @deprecated
*/
Promise._setImmediateFn = function _setImmediateFn(fn) {
Promise._immediateFn = fn;
};
/**
* Change the function to execute on unhandled rejection
* @param {function} fn Function to execute on unhandled rejection
* @deprecated
*/
Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
Promise._unhandledRejectionFn = fn;
};
window.Promise = Promise;
/*if (typeof module !== 'undefined' && module.exports) {
module.exports = Promise;
} else if (!root.Promise) {
root.Promise = Promise;
}*/
})(this);
@@ -0,0 +1,64 @@
window = this;
window.conch_File=File;
window.conch_FileReader = FileReader;
(function () {
function file2path(p) {
if (!p) return null;
var lastpos = Math.max(p.lastIndexOf('/'),
p.lastIndexOf('\\'));
var ret = lastpos < 0 ? p : p.substr(0, lastpos);
return ret.replace(/\\/g, '/');
}
var mcache = {};
/*起始路径总是这里,如果需要改变的话,就在这里通过require跳转。*/
window.requireOrig = function (file) {
function evalreq(fc, fid) {/*return function*/
if (!fc || fc.length <= 0) return null;
/*注意:并不是window.eval所以脚本中不能假设当前是在window上下文*/
try {
//注意 fc后面要加\n来关掉行注释
var func = eval('(function(exports,global,require,__dirname,__filename){' + fc + ';\nreturn exports;})\n//@ sourceURL=' + fid);
mcache[fid] = func;
return func;
}
catch (e) {
_console.log(1,'require error:' + e);
return null;
}
}
var mod = { dir: this.dir, file: file };
if (file.substr(file.length - 3) != '.js')
file += '.js';
/*优先读取外部的*/
var extfile = null;
if (file.charAt(1) === ':' || file.charAt(0) === '/') { extfile = file; }
else extfile = this.dir ? (this.dir + '/' + file) : null;
var extfunc = null;
_console.log(3,'require(' + extfile + ')');
var reqresult = mcache[extfile] ||
(extfunc = evalreq(readFileSync(extfile, 'utf8'), extfile)) ||
mcache[file] ||
evalreq(readTextAsset('scripts/' + file), file);
if (extfunc) {
mod.dir = file2path(extfile);/*使用window的或者当前模块的*/
mod.file = extfile;
}
if (!reqresult) {
throw ('require failed' + file);
return null;
}
try {
var ret = reqresult({}, window, window.requireOrig.bind(mod), mod.dir, mod.file);
return ret;
}
catch (e) {
var err = 'eval script error in require:\n ' + file + '\n' + e.stack;
_console.log(1,err);
throw err;
}
return null;
}
var exepath = file2path(getExePath());
window.require = window.requireOrig.bind({ dir: exepath ? (exepath + '/scripts') : '/sdcard/layabox/scripts', file: null })
})();
@@ -0,0 +1,453 @@
var UNIFORM_TYPE;
(function (UNIFORM_TYPE) {
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM1F"] = 0] = "INTERIOR_UNIFORM1F";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM1FV"] = 1] = "INTERIOR_UNIFORM1FV";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM1I"] = 2] = "INTERIOR_UNIFORM1I";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM1IV"] = 3] = "INTERIOR_UNIFORM1IV";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM2F"] = 4] = "INTERIOR_UNIFORM2F";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM2FV"] = 5] = "INTERIOR_UNIFORM2FV";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM2I"] = 6] = "INTERIOR_UNIFORM2I";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM2IV"] = 7] = "INTERIOR_UNIFORM2IV";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM3F"] = 8] = "INTERIOR_UNIFORM3F";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM3FV"] = 9] = "INTERIOR_UNIFORM3FV";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM3I"] = 10] = "INTERIOR_UNIFORM3I";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM3IV"] = 11] = "INTERIOR_UNIFORM3IV";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM4F"] = 12] = "INTERIOR_UNIFORM4F";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM4FV"] = 13] = "INTERIOR_UNIFORM4FV";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM4I"] = 14] = "INTERIOR_UNIFORM4I";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORM4IV"] = 15] = "INTERIOR_UNIFORM4IV";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORMMATRIX2FV"] = 16] = "INTERIOR_UNIFORMMATRIX2FV";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORMMATRIX3FV"] = 17] = "INTERIOR_UNIFORMMATRIX3FV";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORMMATRIX4FV"] = 18] = "INTERIOR_UNIFORMMATRIX4FV";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORMSAMPLER_2D"] = 19] = "INTERIOR_UNIFORMSAMPLER_2D";
UNIFORM_TYPE[UNIFORM_TYPE["INTERIOR_UNIFORMSAMPLER_CUBE"] = 20] = "INTERIOR_UNIFORMSAMPLER_CUBE";
})(UNIFORM_TYPE || (UNIFORM_TYPE = {}));
var ARRAY_BUFFER_PARAM_TYPE;
(function (ARRAY_BUFFER_PARAM_TYPE) {
ARRAY_BUFFER_PARAM_TYPE[ARRAY_BUFFER_PARAM_TYPE["ARRAY_BUFFER_REF_REFERENCE"] = 0] = "ARRAY_BUFFER_REF_REFERENCE";
ARRAY_BUFFER_PARAM_TYPE[ARRAY_BUFFER_PARAM_TYPE["ARRAY_BUFFER_REF_COPY"] = 1] = "ARRAY_BUFFER_REF_COPY";
})(ARRAY_BUFFER_PARAM_TYPE || (ARRAY_BUFFER_PARAM_TYPE = {}));
var UPLOAD_SHADER_UNIFORM_TYPE;
(function (UPLOAD_SHADER_UNIFORM_TYPE) {
UPLOAD_SHADER_UNIFORM_TYPE[UPLOAD_SHADER_UNIFORM_TYPE["UPLOAD_SHADER_UNIFORM_TYPE_ID"] = 0] = "UPLOAD_SHADER_UNIFORM_TYPE_ID";
UPLOAD_SHADER_UNIFORM_TYPE[UPLOAD_SHADER_UNIFORM_TYPE["UPLOAD_SHADER_UNIFORM_TYPE_DATA"] = 1] = "UPLOAD_SHADER_UNIFORM_TYPE_DATA";
})(UPLOAD_SHADER_UNIFORM_TYPE || (UPLOAD_SHADER_UNIFORM_TYPE = {}));
var ARRAY_BUFFER_TYPE;
(function (ARRAY_BUFFER_TYPE) {
ARRAY_BUFFER_TYPE[ARRAY_BUFFER_TYPE["ARRAY_BUFFER_TYPE_DATA"] = 0] = "ARRAY_BUFFER_TYPE_DATA";
ARRAY_BUFFER_TYPE[ARRAY_BUFFER_TYPE["ARRAY_BUFFER_TYPE_CMD"] = 1] = "ARRAY_BUFFER_TYPE_CMD";
})(ARRAY_BUFFER_TYPE || (ARRAY_BUFFER_TYPE = {}));
class conchFloatArrayKeyframe {
constructor() {
this._nativeObj = new _conchFloatArrayKeyframe();
}
set time(value) {
this._nativeObj.setTime(value);
}
get time() {
return this._nativeObj.getTime();
}
set data(value) {
this._data = value;
this._nativeObj.setData(value);
}
get data() {
return this._data;
}
set inTangent(value) {
this._inTangent = value;
this._nativeObj.setInTangent(this._inTangent);
}
get inTangent() {
return this._inTangent;
}
set outTangent(value) {
this._outTangent = value;
this._nativeObj.setOutTangent(this._outTangent);
}
get outTangent() {
return this._outTangent;
}
set value(v) {
this._value = v;
this._nativeObj.setValue(this._value);
}
get value() {
return this._value;
}
clone() {
let pDestObj = new conchFloatArrayKeyframe();
this.cloneTo(pDestObj);
return pDestObj;
}
cloneTo(destObj) {
destObj.inTangent = this._inTangent.slice();
destObj.outTangent = this._outTangent.slice();
destObj.value = this._value.slice();
destObj.data = this._data.slice();
}
}
window["conchFloatArrayKeyframe"] = conchFloatArrayKeyframe;
class conchKeyframeNode {
constructor() {
this._keyFrameArray = [];
this._type = 0;
this._setKeyframeByIndex = function (index, keyframe) {
this._keyFrameArray[index] = keyframe;
if (keyframe instanceof (conchFloatArrayKeyframe)) {
this._nativeObj._setKeyframeByIndex1(index, keyframe._nativeObj);
}
else {
this._nativeObj._setKeyframeByIndex0(index, keyframe);
}
};
this._nativeObj = new _conchKeyframeNode();
}
set data(value) {
this._data = value;
this._nativeObj.setFloat32ArrayData(this._data.elements);
}
get data() {
return this._type == 0 ? this._nativeObj.getFloatData() : this._data;
}
get indexInList() {
return this._nativeObj._indexInList;
}
set indexInList(value) {
this._nativeObj._indexInList = value;
}
get type() {
return this._type;
}
set type(type) {
this._type = type;
this._nativeObj.type = type;
}
get fullPath() {
return this._nativeObj.fullPath;
}
set fullPath(path) {
this._nativeObj.fullPath = path;
}
get propertyOwner() {
return this._nativeObj.propertyOwner;
}
set propertyOwner(value) {
this._nativeObj.propertyOwner = value;
}
get ownerPathCount() {
return this._nativeObj.ownerPathCount;
}
set ownerPathCount(value) {
this._nativeObj.ownerPathCount = value;
}
get propertyCount() {
return this._nativeObj.propertyCount;
}
set propertyCount(value) {
this._nativeObj.propertyCount = value;
}
get keyFramesCount() {
return this._keyFrameArray.length;
}
set keyFramesCount(value) {
this._keyFrameArray.length = value;
this._nativeObj.keyFramesCount = value;
}
getOwnerPathCount() {
return this._nativeObj.getOwnerPathCount();
}
_setOwnerPathCount(value) {
this._nativeObj._setOwnerPathCount(value);
}
getPropertyCount() {
return this._nativeObj.getPropertyCount();
}
_setPropertyCount(value) {
this._nativeObj._setPropertyCount(value);
}
getKeyFramesCount() {
return this._keyFrameArray.length;
}
_setKeyframeCount(value) {
this._keyFrameArray.length = value;
this._nativeObj._setKeyframeCount(value);
}
getOwnerPathByIndex(index) {
return this._nativeObj.getOwnerPathByIndex(index);
}
_setOwnerPathByIndex(index, value) {
this._nativeObj._setOwnerPathByIndex(index, value);
}
getPropertyByIndex(index) {
return this._nativeObj.getPropertyByIndex(index);
}
_setPropertyByIndex(index, value) {
this._nativeObj._setPropertyByIndex(index, value);
}
getKeyframeByIndex(index) {
return this._nativeObj.getKeyframeByIndex(index);
}
_joinOwnerPath(sep) {
return this._nativeObj._joinOwnerPath(sep);
}
_joinProperty(sep) {
return this._nativeObj._joinProperty(sep);
}
}
window["conchKeyframeNode"] = conchKeyframeNode;
class conchKeyframeNodeList {
constructor() {
this._nodes = [];
this._nativeObj = new _conchKeyframeNodeList();
}
set count(value) {
this._nodes.length = value;
this._nativeObj.setCount(value);
}
get count() {
return this._nodes.length;
}
getNodeByIndex(index) {
return this._nodes[index];
}
setNodeByIndex(index, node) {
this._nodes[index] = node;
this._nativeObj.setNodeByIndex(index, node._nativeObj);
}
}
window["conchKeyframeNodeList"] = conchKeyframeNodeList;
class _GLCommandEncoder {
constructor(gl, reserveSize, adjustSize, isSyncToRenderThread) {
this._adjustSize = 0;
this._byteLen = 0;
this._isSyncToRenderThread = false;
this._isSyncToRenderThread = isSyncToRenderThread;
this._layagl = gl;
this._byteLen = reserveSize;
this._adjustSize = adjustSize;
this._init(isSyncToRenderThread);
}
_init(isSyncToRenderThread) {
this._buffer = new ArrayBuffer(this._byteLen);
this._idata = new Int32Array(this._buffer);
this._fdata = new Float32Array(this._buffer);
this._byteArray = new Uint8Array(this._buffer);
this._layagl.createArrayBufferRef(this._buffer, ARRAY_BUFFER_TYPE.ARRAY_BUFFER_TYPE_CMD, isSyncToRenderThread);
this._idata[0] = 1;
}
getAlignLength(data) {
var byteLength = data.byteLength;
return (byteLength + 3) & 0xfffffffc;
}
getPtrID() {
return this._buffer["_ptrID"];
}
clearEncoding() {
this._idata[0] = 1;
}
getCount() {
return this._idata[0];
}
_need(sz) {
if ((this._byteLen - (this._idata[0] << 2)) >= sz)
return;
this._byteLen += (sz > this._adjustSize) ? sz : this._adjustSize;
var pre = this._idata;
var preConchRef = this._buffer["conchRef"];
var prePtrID = this._buffer["_ptrID"];
this._buffer = new ArrayBuffer(this._byteLen);
this._idata = new Int32Array(this._buffer);
this._fdata = new Float32Array(this._buffer);
this._byteArray = new Uint8Array(this._buffer);
this._buffer["conchRef"] = preConchRef;
this._buffer["_ptrID"] = prePtrID;
pre && this._idata.set(pre, 0);
webglPlus.updateArrayBufferRef(this._buffer["_ptrID"], preConchRef.isSyncToRender(), this._buffer);
}
addShaderUniform(one) {
var funID = 0;
var isArray = one.isArray;
switch (one.type) {
case _GLCommandEncoder.INT:
funID = isArray ? UNIFORM_TYPE.INTERIOR_UNIFORM1IV : UNIFORM_TYPE.INTERIOR_UNIFORM1I;
break;
case _GLCommandEncoder.FLOAT:
funID = isArray ? UNIFORM_TYPE.INTERIOR_UNIFORM1FV : UNIFORM_TYPE.INTERIOR_UNIFORM1F;
break;
case _GLCommandEncoder.FLOAT_VEC2:
funID = isArray ? UNIFORM_TYPE.INTERIOR_UNIFORM2FV : UNIFORM_TYPE.INTERIOR_UNIFORM2F;
break;
case _GLCommandEncoder.FLOAT_VEC3:
funID = isArray ? UNIFORM_TYPE.INTERIOR_UNIFORM3FV : UNIFORM_TYPE.INTERIOR_UNIFORM3F;
break;
case _GLCommandEncoder.FLOAT_VEC4:
funID = isArray ? UNIFORM_TYPE.INTERIOR_UNIFORM4FV : UNIFORM_TYPE.INTERIOR_UNIFORM4F;
break;
case _GLCommandEncoder.SAMPLER_2D:
funID = UNIFORM_TYPE.INTERIOR_UNIFORMSAMPLER_2D;
break;
case _GLCommandEncoder.SAMPLER_CUBE:
funID = UNIFORM_TYPE.INTERIOR_UNIFORMSAMPLER_CUBE;
break;
case _GLCommandEncoder.FLOAT_MAT4:
funID = UNIFORM_TYPE.INTERIOR_UNIFORMMATRIX4FV;
break;
case _GLCommandEncoder.BOOL:
funID = UNIFORM_TYPE.INTERIOR_UNIFORM1I;
break;
case _GLCommandEncoder.FLOAT_MAT2:
funID = UNIFORM_TYPE.INTERIOR_UNIFORMMATRIX2FV;
break;
case _GLCommandEncoder.FLOAT_MAT3:
funID = UNIFORM_TYPE.INTERIOR_UNIFORMMATRIX3FV;
break;
default:
throw new Error("compile shader err!");
}
this._layagl.syncBufferToRenderThread(this._buffer);
this.add_iiiiii(3, funID, one.location.id, one.type, one.dataOffset, one.textureID);
}
add_iiiiii(a, b, c, d, e, f) {
this._need(24);
var idata = this._idata;
var i = idata[0];
idata[i++] = a;
idata[i++] = b;
idata[i++] = c;
idata[i++] = d;
idata[i++] = e;
idata[i++] = f;
idata[0] = i;
}
}
_GLCommandEncoder.INT = 0x1404;
_GLCommandEncoder.FLOAT = 0x1406;
_GLCommandEncoder.FLOAT_VEC2 = 0x8B50;
_GLCommandEncoder.FLOAT_VEC3 = 0x8B51;
_GLCommandEncoder.FLOAT_VEC4 = 0x8B52;
_GLCommandEncoder.INT_VEC2 = 0x8B53;
_GLCommandEncoder.INT_VEC3 = 0x8B54;
_GLCommandEncoder.INT_VEC4 = 0x8B55;
_GLCommandEncoder.BOOL = 0x8B56;
_GLCommandEncoder.BOOL_VEC2 = 0x8B57;
_GLCommandEncoder.BOOL_VEC3 = 0x8B58;
_GLCommandEncoder.BOOL_VEC4 = 0x8B59;
_GLCommandEncoder.FLOAT_MAT2 = 0x8B5A;
_GLCommandEncoder.FLOAT_MAT3 = 0x8B5B;
_GLCommandEncoder.FLOAT_MAT4 = 0x8B5C;
_GLCommandEncoder.SAMPLER_2D = 0x8B5E;
_GLCommandEncoder.SAMPLER_CUBE = 0x8B60;
function extendWebGLPlusToWebGLContext(gl) {
gl.prototype.createArrayBufferRef = function (arrayBuffer, type, syncRender) {
var bufferConchRef = webglPlus.createArrayBufferRef(arrayBuffer, type, syncRender, ARRAY_BUFFER_PARAM_TYPE.ARRAY_BUFFER_REF_REFERENCE);
arrayBuffer["conchRef"] = bufferConchRef;
arrayBuffer["_ptrID"] = bufferConchRef.id;
return bufferConchRef;
};
gl.prototype.createArrayBufferRefs = function (arrayBuffer, type, syncRender, refType) {
if (!arrayBuffer._refArray) {
arrayBuffer._refArray = [];
arrayBuffer._refNum = 1;
arrayBuffer._refArray.length = 1;
arrayBuffer.getRefNum = function () {
return this._refNum;
};
arrayBuffer.clearRefNum = function () {
this._refNum = 1;
};
arrayBuffer.getRefSize = function () {
return this._refArray.length;
};
arrayBuffer.getPtrID = function (index) {
index = index ? index : 0;
return this._refArray[index].ptrID;
};
}
var bufferConchRef = null;
if (refType == ARRAY_BUFFER_PARAM_TYPE.ARRAY_BUFFER_REF_REFERENCE) {
var refArray = arrayBuffer._refArray;
if (!refArray[0]) {
bufferConchRef = webglPlus.createArrayBufferRef(arrayBuffer, type, syncRender, refType);
refArray[0] = { "ref": bufferConchRef, "ptrID": bufferConchRef.id };
}
}
else {
if (arrayBuffer._refNum < arrayBuffer._refArray.length) {
bufferConchRef = arrayBuffer._refArray[arrayBuffer._refNum].ref;
var nPtrID = arrayBuffer.getPtrID(arrayBuffer._refNum);
webglPlus.syncArrayBufferDataToRuntime(nPtrID, bufferConchRef.isSyncToRender(), arrayBuffer);
}
else {
bufferConchRef = webglPlus.createArrayBufferRef(arrayBuffer, type, syncRender, refType);
arrayBuffer._refArray.push({ "ref": bufferConchRef, "ptrID": bufferConchRef.id });
}
arrayBuffer._refNum++;
}
return bufferConchRef;
};
gl.prototype.updateArrayBufferRef = function (bufferID, isSyncToRender, buffer) {
return webglPlus.updateArrayBufferRef(bufferID, isSyncToRender, buffer);
};
gl.prototype.updateAnimationNodeWorldMatix = function (locPosition, locRotation, locScaling, parentIndices, outWorldMatrix) {
return webglPlus.updateAnimationNodeWorldMatix(locPosition, locRotation, locScaling, parentIndices, outWorldMatrix);
};
gl.prototype.computeSubSkinnedData = function (worldMatrixs, worldMatrixIndex, inverseBindPoses, boneIndices, bindPoseInices, resultData) {
return webglPlus.computeSubSkinnedData(worldMatrixs, worldMatrixIndex, inverseBindPoses, boneIndices, bindPoseInices, resultData);
};
gl.prototype.evaluateClipDatasRealTime = function (nodes, playCurTime, realTimeCurrentFrameIndexs, addtive, frontPlay) {
webglPlus.evaluateClipDatasRealTime(nodes, playCurTime, realTimeCurrentFrameIndexs, addtive, frontPlay);
};
gl.prototype.culling = function (boundFrustumBuffer, cullingBuffer, cullingBufferIndices, cullingCount, cullingBufferResult) {
return webglPlus.culling(boundFrustumBuffer, cullingBuffer, cullingBufferIndices, cullingCount, cullingBufferResult);
};
if (!window["conch"]) {
gl.prototype.createCommandEncoder = function (reserveSize, adjustSize, isSyncToRenderThread) {
reserveSize = reserveSize ? reserveSize : 128;
adjustSize = adjustSize ? adjustSize : 64;
isSyncToRenderThread = isSyncToRenderThread ? isSyncToRenderThread : false;
var cmd = new _GLCommandEncoder(this, reserveSize, adjustSize, isSyncToRenderThread);
if (isSyncToRenderThread) {
this.syncBufferToRenderThread(cmd);
}
return cmd;
};
window["GLCommandEncoder"] = _GLCommandEncoder;
gl.prototype.syncBufferToRenderThread = function (value, index = 0) {
};
}
if (!window["conch"]) {
gl.prototype.uploadShaderUniforms = function (commandEncoder, data, type) {
if (type == UPLOAD_SHADER_UNIFORM_TYPE.UPLOAD_SHADER_UNIFORM_TYPE_ID) {
var dataID = data["_ptrID"];
this.syncBufferToRenderThread(data);
}
else {
var nAlignLength = this.getAlignLength(data);
}
return 0;
};
gl.prototype.uniformMatrix2fvEx = function (location, transpose, value) {
if (!value["_ptrID"]) {
this.createArrayBufferRef(value, ARRAY_BUFFER_TYPE.ARRAY_BUFFER_TYPE_DATA, true);
}
var nID = value["_ptrID"];
this.syncBufferToRenderThread(value);
};
gl.prototype.uniformMatrix3fvEx = function (location, transpose, value) {
if (!value["_ptrID"]) {
this.createArrayBufferRef(value, ARRAY_BUFFER_TYPE.ARRAY_BUFFER_TYPE_DATA, true);
}
var nID = value["_ptrID"];
this.syncBufferToRenderThread(value);
};
gl.prototype.uniformMatrix4fvEx = function (location, transpose, value) {
if (!value["_ptrID"]) {
this.createArrayBufferRef(value, ARRAY_BUFFER_TYPE.ARRAY_BUFFER_TYPE_DATA, true);
}
var nID = value["_ptrID"];
this.syncBufferToRenderThread(value);
};
}
}
window["extendWebGLPlusToWebGLContext"] = extendWebGLPlusToWebGLContext;
@@ -0,0 +1,39 @@
if( !window.runtime )
{
window.runtime=
{
ScriptFrameParent:null,
callObjectC:function(js)
{
if(!this.ScriptFrameParent)
{
this.ScriptFrameParent= document.createElement("div");
this.ScriptFrameParent.cssText="position:absolute;left:0px;top:0;width:1px;height:1px;display:none";
document.documentElement.appendChild(this.ScriptFrameParent);
}
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", "runtime:"+js );
this.ScriptFrameParent.appendChild(iframe);
this.ScriptFrameParent.removeChild(iframe);
iframe = null;
},
callConchJSFunction:function(name,json,callback)
{
this.callObjectC( "callConchJSFunction"+"\5" + name+"\5"+json+"\5"+callback );
},
JSLog:function( message )
{
this.callObjectC( "JSLog" + "\5" + message );
}
}
}
window.postRuntimeMessage=function(d,s){
window.runtime.callConchJSFunction('window.postRuntimeMessage',encodeURIComponent( JSON.stringify(d)),'');
};
window.__getMessemage=function(d,s){
d=decodeURIComponent(d);
var e=document.createEvent("MessageEvent");
e.initMessageEvent("message",false,false,JSON.parse(d),"","",window);
e.target=window;
window.dispatchEvent(e);
};