Revert "Revert "optimize interface in screen module (#9176)"" (#9490)

This reverts commit b88d4845cc.
This commit is contained in:
PP
2021-10-15 10:21:04 +08:00
committed by GitHub
parent b88d4845cc
commit f5511f4c87
44 changed files with 773 additions and 663 deletions
+50 -10
View File
@@ -7,6 +7,24 @@ declare module 'pal/screen-adapter' {
}
class ScreenAdapter {
/**
* Init the callback to rebuild frame buffer when update the resolution.
* This method will also init the resolution.
* This method should be called when the engine director.root is initiated.
* @param cbToRebuildFrameBuffer
*/
public init (cbToRebuildFrameBuffer: () => void);
/**
* On web mobile platform, sometimes we need to rotate the game frame.
* This field record the rotate state of game frame, which is false by default.
*/
public isFrameRotated: boolean;
/**
* In some case we don't want to handle the resize event.
* For example, when the soft keyboard shows up, we don't want to resize the canvas.
* This is true by default.
*/
public handleResizeEvent: boolean;
/**
* Query whether fullscreen feature is supported on the current platform.
*/
@@ -16,26 +34,48 @@ declare module 'pal/screen-adapter' {
*/
public get isFullScreen (): boolean;
/**
* Get the size of current window.
* On Web platform, this should be the size of game frame.
* The ratio of pixel sizes:
* the size of one CSS pixel to the size of one physical pixel.
*/
public get devicePixelRatio (): number;
/**
* Get the size of current window in physical pixels.
*/
public get windowSize (): import('cocos/core/math').Size;
/**
* Set the size of current window.
* On Web platform, this should be the size of game frame.
* @param {Size} Specify the size that the window need to resize to.
* @todo not implemented yet
* Get and set the size of current window in physical pixels.
*/
public get windowSize (): import('cocos/core/math').Size;
public set windowSize (size: import('cocos/core/math').Size);
/**
* Get the orientation of current game.
* Available on mobile related platform.
* Get the current resolution of game.
* This is a readonly property, you can change the value by setting screenAdapter.resolutionScale.
*/
public get resolution (): import('cocos/core/math').Size;
/**
* Update the resolution by resolutionScale.
* This method rebuilds the size of frame buffer and the size of canvas.
* This method should be called when window resized (fullscreen changing included) or the resolution scale changed.
*/
private _updateResolution ();
/**
* Get and set the resolution scale of screen, which will affect the quality of the rendering.
* Note: if this value is set too high, the rendering performance of GPU will be reduced, this value is 1 by default.
*/
public get resolutionScale (): number;
public set resolutionScale (value: number);
/**
* Get or set the orientation of current game.
* Available on mobile related platform for now.
*/
public get orientation (): import('pal/screen-adapter/enum-type').Orientation;
public set orientation (value: import('pal/screen-adapter/enum-type').Orientation);
/**
* Get the SafeAreaEdge based on the screen coordinate system.
* Get the SafeAreaEdge based on the screen coordinate system in physical pixels.
* @return {SafeAreaEdge} An interface displaying the distance of the sides 'top', 'bottom', 'left' and 'right'.
*/
public get safeAreaEdge (): SafeAreaEdge;
-2
View File
@@ -31,9 +31,7 @@ declare module 'pal/system-info' {
public get osMainVersion (): number;
public get browserType (): import('pal/system-info/enum-type').BrowserType;
public get browserVersion (): string;
public get pixelRatio (): number;
public hasFeature (feature: import('pal/system-info/enum-type').Feature): boolean;
public getBatteryLevel (): number;
public triggerGC (): void;
+8
View File
@@ -254,6 +254,14 @@ Forward render pipeline initialized.
Deferred render pipeline initialized. Note that non-transparent materials with no lighting will not be rendered, such as builtin-unlit.
### 1220
Failed to set shading scale, pipelineSceneData is invalid.
### 1221
Setting orientation is not supported yet.
### 1300
%s is not in the model pool and cannot be destroyed by destroyModel.
+3 -3
View File
@@ -41,7 +41,7 @@ import { legacyCC } from '../../core/global-exports';
import { Enum } from '../../core/value-types/enum';
import visibleRect from '../../core/platform/visible-rect';
import { RenderRoot2D } from './render-root-2d';
import { Node } from '../../core';
import { Node, screen } from '../../core';
import { NodeEventType } from '../../core/scene-graph/node-event';
const _worldPos = new Vec3();
@@ -225,9 +225,9 @@ export class Canvas extends RenderRoot2D {
if (this._cameraComponent.camera) { this._cameraComponent.camera.setFixedSize(win!.width, win!.height); }
this._cameraComponent.orthoHeight = visibleRect.height / 2;
} else if (game.canvas) {
const size = game.canvas;
const size = screen.windowSize;
if (this._cameraComponent.camera) { this._cameraComponent.camera.resize(size.width, size.height); }
this._cameraComponent.orthoHeight = game.canvas.height / view.getScaleY() / 2;
this._cameraComponent.orthoHeight = size.height / view.getScaleY() / 2;
}
this.node.getWorldPosition(_worldPos);
+6
View File
@@ -319,4 +319,10 @@ removeProperty(Director.prototype, 'director', [
name: 'purgeCachedData',
suggest: 'please use assetManager.releaseAll instead',
},
{
name: 'convertToGL',
},
{
name: 'convertToUI',
},
]);
-44
View File
@@ -247,50 +247,6 @@ export class Director extends EventTarget {
*/
public calculateDeltaTime (now) {}
/**
* @en
* Converts a view coordinate to an WebGL coordinate<br/>
* Useful to convert (multi) touches coordinates to the current layout (portrait or landscape)<br/>
* Implementation can be found in directorWebGL.
* @zh 将触摸点的屏幕坐标转换为 WebGL View 下的坐标。
* @deprecated since v2.0
*/
public convertToGL (uiPoint: Vec2) {
const container = game.container as Element;
const view = legacyCC.view;
const box = container.getBoundingClientRect();
const left = box.left + window.pageXOffset - container.clientLeft;
const top = box.top + window.pageYOffset - container.clientTop;
const x = view._devicePixelRatio * (uiPoint.x - left);
const y = view._devicePixelRatio * (top + box.height - uiPoint.y);
return view._isRotated ? v2(view._viewportRect.width - y, x) : v2(x, y);
}
/**
* @en
* Converts an OpenGL coordinate to a view coordinate<br/>
* Useful to convert node points to window points for calls such as glScissor<br/>
* Implementation can be found in directorWebGL.
* @zh 将触摸点的 WebGL View 坐标转换为屏幕坐标。
* @deprecated since v2.0
*/
public convertToUI (glPoint: Vec2) {
const container = game.container as Element;
const view = legacyCC.view;
const box = container.getBoundingClientRect();
const left = box.left + window.pageXOffset - container.clientLeft;
const top = box.top + window.pageYOffset - container.clientTop;
const uiPoint = v2(0, 0);
if (view._isRotated) {
uiPoint.x = left + glPoint.y / view._devicePixelRatio;
uiPoint.y = top + box.height - (view._viewportRect.width - glPoint.x) / view._devicePixelRatio;
} else {
uiPoint.x = left + glPoint.x * view._devicePixelRatio;
uiPoint.y = top + box.height - glPoint.y * view._devicePixelRatio;
}
return uiPoint;
}
/**
* @en End the life of director in the next frame
* @zh 执行完当前帧后停止 director 的执行
+12 -5
View File
@@ -48,6 +48,8 @@ import { BrowserType } from '../../pal/system-info/enum-type';
import { Layers } from './scene-graph';
import { log2 } from './math/bits';
import { garbageCollectionManager } from './data/garbage-collection';
import { screen } from './platform/screen';
import { Size } from './math';
interface ISceneInfo {
url: string;
@@ -591,7 +593,10 @@ export class Game extends EventTarget {
}
garbageCollectionManager.init();
return Promise.resolve(initPromise).then(() => this._setRenderPipelineNShowSplash());
return Promise.resolve(initPromise).then(() => this._setRenderPipelineNShowSplash()).then(() => {
// @ts-expect-error access private method.
screen._init();
});
}
// @ Persist root node section
@@ -659,7 +664,9 @@ export class Game extends EventTarget {
private _initEngine () {
this._initDevice();
return Promise.resolve(legacyCC.director._init()).then(() => {
const director = legacyCC.director;
return Promise.resolve(director._init()).then(() => {
legacyCC.view.init();
// Log engine version
debug.log(`Cocos Creator v${VERSION}`);
this.emit(Game.EVENT_ENGINE_INITED);
@@ -826,7 +833,6 @@ export class Game extends EventTarget {
// WebGL context created successfully
if (this.renderType === Game.RENDER_TYPE_WEBGL) {
const ctors: Constructor<Device>[] = [];
const deviceInfo = new DeviceInfo(bindingMappingInfo);
if (JSB && window.gfx) {
@@ -867,8 +873,9 @@ export class Game extends EventTarget {
}
const swapchainInfo = new SwapchainInfo(this.canvas!);
swapchainInfo.width = sys.windowPixelResolution.width;
swapchainInfo.height = sys.windowPixelResolution.height;
const windowSize = screen.windowSize;
swapchainInfo.width = windowSize.width;
swapchainInfo.height = windowSize.height;
this._swapchain = this._gfxDevice.createSwapchain(swapchainInfo);
this.canvas!.oncontextmenu = () => false;
+39
View File
@@ -23,11 +23,13 @@
THE SOFTWARE.
*/
import { screenAdapter } from 'pal/screen-adapter';
import { markAsWarning, removeProperty, replaceProperty } from '../utils';
import { sys } from './sys';
import { View } from './view';
import { legacyCC } from '../global-exports';
import { screen } from './screen';
import { Size } from '../math';
// #region deprecation on view
removeProperty(View.prototype, 'View.prototype', [
@@ -51,6 +53,35 @@ markAsWarning(View.prototype, 'View.prototype', [
{
name: 'isAutoFullScreenEnabled',
},
{
name: 'setCanvasSize',
suggest: 'setting size in CSS pixels is not recommended, please use screen.windowSize instead.',
},
{
name: 'getCanvasSize',
suggest: 'please use screen.windowSize instead.',
},
{
name: 'getFrameSize',
suggest: 'getting size in CSS pixels is not recommended, please use screen.windowSize instead.',
},
{
name: 'setFrameSize',
suggest: 'setting size in CSS pixels is not recommended, please use screen.windowSize instead.',
},
{
name: 'getDevicePixelRatio',
suggest: 'devicePixelRatio is a concept on web standard, please use screen.resolutionScale instead',
},
{
name: 'convertToLocationInView',
},
{
name: 'enableRetina',
},
{
name: 'isRetinaEnabled',
},
]);
markAsWarning(legacyCC, 'cc', [
{
@@ -138,6 +169,14 @@ removeProperty(sys, 'sys',
'WINRT', 'WP8', 'QQ_PLAY', 'FB_PLAYABLE_ADS'].map((item) => ({
name: item,
})));
replaceProperty(sys, 'sys', [
{
name: 'windowPixelResolution',
target: screen,
targetName: 'screen',
newName: 'windowSize',
},
]);
// deprecate screen API
markAsWarning(screen, 'screen', [
+49 -12
View File
@@ -31,7 +31,7 @@
import { screenAdapter } from 'pal/screen-adapter';
import { legacyCC } from '../global-exports';
import { Size } from '../math';
import { Size, Vec2 } from '../math';
import { warnID } from './debug';
/**
@@ -39,17 +39,54 @@ import { warnID } from './debug';
* @zh screen 单例对象提供简单的方法来做屏幕管理相关的工作。
*/
class Screen {
// TODO: windowSize should be physical size, and deprecate sys.windowPixelResolution
// /**
// * @en Get the size of current window.
// * On Web platform, this should be the size of game frame.
// * @zh 获取当前窗口尺寸。
// * 在 Web 平台,这里应该是 game frame 的尺寸
// * @returns {Size}
// */
// public get windowSize (): Size {
// return screenAdapter.windowSize;
// }
private _init () {
screenAdapter.init(() => {
const director = legacyCC.director;
if (!director.root?.pipeline) {
warnID(1220);
return;
}
director.root.pipeline.pipelineSceneData.shadingScale = screenAdapter.resolutionScale;
});
}
/**
* @en Get and set the size of current window in physical pixels.
* NOTE: Setting window size is only supported on Web platform for now.
* @zh 获取和设置当前窗口的物理像素尺寸。
* 注意:设置窗口尺寸目前只在 Web 平台上支持。
*/
public get windowSize (): Size {
return screenAdapter.windowSize;
}
public set windowSize (size: Size) {
screenAdapter.windowSize = size;
}
/**
* @en Get the current resolution of game.
* This is a readonly property, you can change the value by setting screen.resolutionScale.
* @zh 获取当前游戏的分辨率。
* 这是一个只读属性,你可以通过设置 screen.resolutionScale 来改变这个值。
*
* @readonly
*/
public get resolution () {
return screenAdapter.resolution;
}
/**
* @en Get and set the resolution scale of screen, which will affect the quality of the rendering.
* Note: if this value is set too high, the rendering performance of GPU will be reduced, this value is 1 by default.
* @zh 获取和设置屏幕的分辨率缩放比,这将会影响最终渲染的质量。
* 注意:如果这个值设置的太高,会降低 GPU 的渲染性能,该值默认为 1。
*/
public get resolutionScale () {
return screenAdapter.resolutionScale;
}
public set resolutionScale (v: number) {
screenAdapter.resolutionScale = v;
}
/**
* @en Whether it supports full screen?
+9 -25
View File
@@ -35,9 +35,7 @@ import { Rect } from '../math/rect';
import { warnID, log } from './debug';
import { NetworkType, Language, OS, Platform, BrowserType, Feature } from '../../../pal/system-info/enum-type';
import { Vec2 } from '../math';
const windowSize = screenAdapter.windowSize;
const pixelRatio = systemInfo.pixelRatio;
import { screen } from './screen';
export declare namespace sys {
/**
@@ -189,11 +187,10 @@ export const sys = {
/**
* @en Indicate the real pixel resolution of the whole game window
* @zh 指示游戏窗口的像素分辨率
*
* @deprecated since v3.4.0, please use screen.windowSize instead.
*/
windowPixelResolution: {
width: windowSize.width * pixelRatio,
height: windowSize.height * pixelRatio,
},
windowPixelResolution: screen.windowSize,
/**
* @en The capabilities of the current platform
@@ -317,17 +314,12 @@ export const sys = {
const windowSize = screenAdapter.windowSize;
// Get leftBottom and rightTop point in screen coordinates system.
const leftBottom = new Vec2(edge.left, windowSize.height - edge.bottom);
const rightTop = new Vec2(windowSize.width - edge.right, edge.top);
const leftBottom = new Vec2(edge.left, edge.bottom);
const rightTop = new Vec2(windowSize.width - edge.right, windowSize.height - edge.top);
// Convert to the location in game view coordinates system.
const relatedPos = { left: 0, top: 0, width: windowSize.width, height: windowSize.height };
locView.convertToLocationInView(leftBottom.x, leftBottom.y, relatedPos, leftBottom);
locView.convertToLocationInView(rightTop.x, rightTop.y, relatedPos, rightTop);
// Convert view point to design resolution size
locView._convertPointWithScale(leftBottom);
locView._convertPointWithScale(rightTop);
// Convert view point to UI coordinate system.
locView._convertToUISpace(leftBottom);
locView._convertToUISpace(rightTop);
const x = leftBottom.x;
const y = leftBottom.y;
@@ -359,14 +351,6 @@ export const sys = {
// @ts-expect-error HACK: this private property only needed on web
sys.__isWebIOS14OrIPadOS14Env = (sys.os === OS.IOS || sys.os === OS.OSX) && systemInfo.isBrowser
&& /(OS 1[4-9])|(Version\/1[4-9])/.test(window.navigator.userAgent);
screenAdapter.on('window-resize', () => {
const windowSize = screenAdapter.windowSize;
sys.windowPixelResolution = {
width: Math.round(windowSize.width * pixelRatio),
height: Math.round(windowSize.height * pixelRatio),
};
});
}());
legacyCC.sys = sys;
+101 -256
View File
@@ -35,14 +35,14 @@ import { EDITOR, MINIGAME, JSB, RUNTIME_BASED } from 'internal:constants';
import { screenAdapter } from 'pal/screen-adapter';
import { systemInfo } from 'pal/system-info';
import { EventTarget } from '../event';
import '../game';
import { Rect, Size, Vec2 } from '../math';
import visibleRect from './visible-rect';
import { legacyCC } from '../global-exports';
import { logID, errorID } from './debug';
import { sys } from './sys';
import { OS } from '../../../pal/system-info/enum-type';
import { screen } from './screen';
import { macro } from './macro';
import { Orientation } from '../../../pal/screen-adapter/enum-type';
import { game } from '../game';
/**
* @en View represents the game window.<br/>
@@ -63,26 +63,23 @@ import { screen } from './screen';
const localWinSize = new Size();
const orientationMap = {
[macro.ORIENTATION_AUTO]: Orientation.AUTO,
[macro.ORIENTATION_LANDSCAPE]: Orientation.LANDSCAPE,
[macro.ORIENTATION_PORTRAIT]: Orientation.PORTRAIT,
};
export class View extends EventTarget {
public static instance: View;
public _resizeWithBrowserSize: boolean;
public _designResolutionSize: Size;
private _prevDPR = -1;
private _frameSize: Size;
private _scaleX: number;
private _scaleY: number;
private _viewportRect: Rect;
private _visibleRect: Rect;
private _autoFullScreen: boolean;
private _devicePixelRatio: number;
private _maxPixelRatio: number;
private _retinaEnabled: boolean;
private _resizeCallback: (() => void) | null;
private _resizing: boolean;
private _orientationChanging: boolean;
private _isRotated: boolean;
private _orientation: any;
private _resolutionPolicy: ResolutionPolicy;
private _rpExactFit: ResolutionPolicy;
private _rpShowAll: ResolutionPolicy;
@@ -96,9 +93,6 @@ export class View extends EventTarget {
const _strategyer = ContainerStrategy;
const _strategy = ContentStrategy;
// Size of parent node that contains cc.game.container and cc.game.canvas
this._frameSize = new Size(0, 0);
// resolution size, it is the size appropriate for the app resources.
this._designResolutionSize = new Size(0, 0);
this._scaleX = 1;
@@ -109,22 +103,10 @@ export class View extends EventTarget {
this._visibleRect = new Rect(0, 0, 0, 0);
// Auto full screen disabled by default
this._autoFullScreen = false;
// The device's pixel ratio (for retina displays)
this._devicePixelRatio = 1;
if (JSB || RUNTIME_BASED) {
this._maxPixelRatio = 4;
} else {
this._maxPixelRatio = 2;
}
// Retina disabled by default
this._retinaEnabled = false;
// Custom callback for resize event
this._resizeCallback = null;
this._resizing = false;
this._resizeWithBrowserSize = false;
this._orientationChanging = true;
this._isRotated = false;
this._orientation = legacyCC.macro.ORIENTATION_AUTO;
// Setup system default resolution policies
this._rpExactFit = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.EXACT_FIT);
@@ -133,15 +115,13 @@ export class View extends EventTarget {
this._rpFixedHeight = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_HEIGHT);
this._rpFixedWidth = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH);
this._resolutionPolicy = this._rpShowAll;
legacyCC.game.once(legacyCC.Game.EVENT_ENGINE_INITED, this.init, this);
}
// Call init at the time Game.EVENT_ENGINE_INITED
public init () {
this._initFrameSize();
const w = legacyCC.game.canvas.width;
const h = legacyCC.game.canvas.height;
const windowSize = screen.windowSize;
const w = windowSize.width;
const h = windowSize.height;
this._designResolutionSize.width = w;
this._designResolutionSize.height = h;
this._viewportRect.width = w;
@@ -154,6 +134,10 @@ export class View extends EventTarget {
if (visibleRect) {
visibleRect.init(this._visibleRect);
}
// For now, the engine UI is adapted to resolution size, instead of window size.
screenAdapter.on('window-resize', this._updateAdaptResult, this);
screenAdapter.on('orientation-change', this._updateAdaptResult, this);
}
/**
@@ -165,19 +149,7 @@ export class View extends EventTarget {
* @param enabled - Whether enable automatic resize with browser's resize event
*/
public resizeWithBrowserSize (enabled: boolean) {
if (enabled) {
// enable
if (!this._resizeWithBrowserSize) {
this._resizeWithBrowserSize = true;
screenAdapter.on('window-resize', this._resizeEvent, this);
screenAdapter.on('orientation-change', this._orientationChange, this);
}
} else if (this._resizeWithBrowserSize) {
// disable
this._resizeWithBrowserSize = false;
screenAdapter.off('window-resize', this._resizeEvent, this);
screenAdapter.off('orientation-change', this._orientationChange, this);
}
screenAdapter.handleResizeEvent = enabled;
}
/**
@@ -212,10 +184,7 @@ export class View extends EventTarget {
* @param orientation - Possible values: macro.ORIENTATION_LANDSCAPE | macro.ORIENTATION_PORTRAIT | macro.ORIENTATION_AUTO
*/
public setOrientation (orientation: number) {
orientation &= legacyCC.macro.ORIENTATION_AUTO;
if (orientation && this._orientation !== orientation) {
this._orientation = orientation;
}
screenAdapter.orientation = orientationMap[orientation];
}
/**
@@ -244,6 +213,8 @@ export class View extends EventTarget {
* 它仅会在你调用 setDesignResolutionPolicy 方法时有影响。
* 仅在 Web 模式下有效。
* @param enabled - Enable or disable retina display
*
* @deprecated since v3.4.0
*/
public enableRetina (enabled: boolean) {
this._retinaEnabled = !!enabled;
@@ -255,6 +226,8 @@ export class View extends EventTarget {
* Only useful on web
* @zh 检查是否对 Retina 显示设备进行优化。
* 仅在 Web 模式下有效。
*
* @deprecated since v3.4.0
*/
public isRetinaEnabled (): boolean {
return this._retinaEnabled;
@@ -295,31 +268,25 @@ export class View extends EventTarget {
return this._autoFullScreen;
}
/*
* Not support on native.<br/>
* On web, it sets the size of the canvas.
* @zh 这个方法并不支持 native 平台,在 Web 平台下,可以用来设置 canvas 尺寸。
/**
* @en Set the canvas size in CSS pixels on Web platform.
* This method is not supported on other platforms.
* @zh Web 平台下,可以以 CSS 像素尺寸来设置 canvas 尺寸。
* 这个方法并不支持其他平台。
* @private
* @param {Number} width
* @param {Number} height
*
* @deprecated since v3.4.0, setting size in CSS pixels is not recommended, please use screen.windowSize instead.
*/
public setCanvasSize (width: number, height: number) {
const canvas = legacyCC.game.canvas;
const container = legacyCC.game.container;
this._devicePixelRatio = window.devicePixelRatio;
canvas.width = sys.windowPixelResolution.width;
canvas.height = sys.windowPixelResolution.height;
// set resolution scale to 1;
screen.resolutionScale = 1;
// canvas.width = width;
// canvas.height = height;
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
container.style.width = `${width}px`;
container.style.height = `${height}px`;
this._resizeEvent();
// set window size
const dpr = screenAdapter.devicePixelRatio;
const windowSize = new Size(width * dpr, height * dpr);
screen.windowSize = windowSize;
}
/**
@@ -330,38 +297,47 @@ export class View extends EventTarget {
* @zh 返回视图中 canvas 的尺寸。
* 在 native 平台下,它返回全屏视图下屏幕的尺寸。
* 在 Web 平台下,它返回 canvas 元素尺寸。
*
* @deprecated since v3.4.0, please use screen.windowSize instead.
*/
public getCanvasSize (): Size {
return new Size(legacyCC.game.canvas.width, legacyCC.game.canvas.height);
return screen.windowSize;
}
/**
* @en
* Returns the frame size of the view.<br/>
* Returns the frame size of the view in CSS pixels.<br/>
* On native platforms, it returns the screen size since the view is a fullscreen view.<br/>
* On web, it returns the size of the canvas's outer DOM element.
* @zh 返回视图中边框尺寸。
* @zh 以 CSS 像素尺寸返回视图中边框尺寸。
* 在 native 平台下,它返回全屏视图下屏幕的尺寸。
* 在 web 平台下,它返回 canvas 元素的外层 DOM 元素尺寸。
*
* @deprecated since v3.4.0, getting size in CSS pixels is not recommended, please use screen.windowSize instead.
*/
public getFrameSize (): Size {
return new Size(this._frameSize.width, this._frameSize.height);
const dpr = screenAdapter.devicePixelRatio;
const sizeInCssPixels = screen.windowSize;
sizeInCssPixels.width /= dpr;
sizeInCssPixels.height /= dpr;
return sizeInCssPixels;
}
/**
* @en On native, it sets the frame size of view.<br/>
* @en Setting the frame size of the view in CSS pixels.
* On native, it sets the frame size of view.<br/>
* On web, it sets the size of the canvas's outer DOM element.
* @zh 在 native 平台下,设置视图框架尺寸。
* @zh 以 CSS 像素尺寸设置视图中边框尺寸。
* 在 native 平台下,设置视图框架尺寸。
* 在 web 平台下,设置 canvas 外层 DOM 元素尺寸。
* @param {Number} width
* @param {Number} height
*
* @deprecated since v3.4.0, setting size in CSS pixels is not recommended, please use screen.windowSize instead.
*/
public setFrameSize (width: number, height: number) {
this._frameSize.width = width;
this._frameSize.height = height;
legacyCC.game.frame.style.width = `${width}px`;
legacyCC.game.frame.style.height = `${height}px`;
this._resizeEvent();
const dpr = screenAdapter.devicePixelRatio;
screen.windowSize = new Size(width * dpr, height * dpr);
}
/**
@@ -463,18 +439,6 @@ export class View extends EventTarget {
policy.preApply(this);
}
// Permit to re-detect the orientation of device.
this._orientationChanging = true;
// If resizing, then frame size is already initialized, this logic should be improved
if (!this._resizing) {
this._initFrameSize();
}
if (!policy) {
logID(2201);
return;
}
this._designResolutionSize.width = width;
this._designResolutionSize.height = height;
@@ -514,9 +478,7 @@ export class View extends EventTarget {
/**
* @en Returns the designed size for the view.
* Default resolution size is the same as 'getFrameSize'.
* @zh 返回视图的设计分辨率。
* 默认下分辨率尺寸同 `getFrameSize` 方法相同
*/
public getDesignResolutionSize (): Size {
return new Size(this._designResolutionSize.width, this._designResolutionSize.height);
@@ -577,9 +539,11 @@ export class View extends EventTarget {
/**
* @en Returns device pixel ratio for retina display.
* @zh 返回设备或浏览器像素比例。
*
* @deprecated since v3.4.0, devicePixelRatio is a concept on web standard, please use screen.resolutionScale instead.
*/
public getDevicePixelRatio (): number {
return this._devicePixelRatio;
return screenAdapter.devicePixelRatio;
}
/**
@@ -589,112 +553,42 @@ export class View extends EventTarget {
* @param ty - The Y axis translation
* @param relatedPos - The related position object including "left", "top", "width", "height" informations
* @param out - The out object to save the conversion result
*
* @deprecated since v3.4.0
*/
public convertToLocationInView (tx: number, ty: number, relatedPos: any, out: Vec2): Vec2 {
const result = out || new Vec2();
const x = this._devicePixelRatio * (tx - relatedPos.left);
const y = this._devicePixelRatio * ((relatedPos.top as number) + (relatedPos.height as number) - ty);
if (this._isRotated) {
result.x = legacyCC.game.canvas.width - y;
result.y = x;
public convertToLocationInView (tx: number, ty: number, relatedPos: any, out: Vec2 = new Vec2()): Vec2 {
const x = screenAdapter.devicePixelRatio * (tx - relatedPos.left);
const y = screenAdapter.devicePixelRatio * ((relatedPos.top as number) + (relatedPos.height as number) - ty);
if (screenAdapter.isFrameRotated) {
out.x = screen.windowSize.width - y;
out.y = x;
} else {
result.x = x;
result.y = y;
out.x = x;
out.y = y;
}
if (legacyCC.GAME_VIEW) {
result.x /= legacyCC.gameView.canvas.width / legacyCC.game.canvas.width;
result.y /= legacyCC.gameView.canvas.height / legacyCC.game.canvas.height;
}
return result;
return out;
}
private _convertPointWithScale (point) {
// Convert location in Cocos screen coordinate to location in UI space
private _convertToUISpace (point) {
const viewport = this._viewportRect;
point.x = (point.x - viewport.x) / this._scaleX;
point.y = (point.y - viewport.y) / this._scaleY;
}
// Resize helper functions
private _resizeEvent () {
// Check frame size changed or not
const prevFrameW = this._frameSize.width;
const prevFrameH = this._frameSize.height;
const prevRotated = this._isRotated;
if (legacyCC.sys.isMobile) {
const containerStyle = legacyCC.game.container.style;
const margin = containerStyle.margin;
containerStyle.margin = '0';
containerStyle.display = 'none';
this._initFrameSize();
containerStyle.margin = margin;
containerStyle.display = 'block';
} else {
this._initFrameSize();
}
if (!JSB && !RUNTIME_BASED && !this._orientationChanging && this._isRotated === prevRotated && this._frameSize.width === prevFrameW && this._frameSize.height === prevFrameH && this._prevDPR === systemInfo.pixelRatio) {
return;
}
this._prevDPR = systemInfo.pixelRatio;
private _updateAdaptResult () {
legacyCC.director.root.resize(screen.windowSize.width, screen.windowSize.height);
// Frame size changed, do resize works
const width = this._designResolutionSize.width;
const height = this._designResolutionSize.height;
this._resizing = true;
if (width > 0) {
this.setDesignResolutionSize(width, height, this._resolutionPolicy);
}
this._resizing = false;
this.emit('canvas-resize');
this._resizeCallback?.();
}
private _orientationChange () {
this._orientationChanging = true;
this._resizeEvent();
}
private _initFrameSize () {
const locFrameSize = this._frameSize;
const windowSize = screenAdapter.windowSize;
const w = windowSize.width;
const h = windowSize.height;
const isLandscape: boolean = w >= h;
if (EDITOR || !legacyCC.sys.isMobile
|| (isLandscape && this._orientation & legacyCC.macro.ORIENTATION_LANDSCAPE)
|| (!isLandscape && this._orientation & legacyCC.macro.ORIENTATION_PORTRAIT)) {
locFrameSize.width = w;
locFrameSize.height = h;
legacyCC.game.container.style['-webkit-transform'] = 'rotate(0deg)';
legacyCC.game.container.style.transform = 'rotate(0deg)';
this._isRotated = false;
} else {
locFrameSize.width = h;
locFrameSize.height = w;
legacyCC.game.container.style['-webkit-transform'] = 'rotate(90deg)';
legacyCC.game.container.style.transform = 'rotate(90deg)';
legacyCC.game.container.style['-webkit-transform-origin'] = '0px 0px 0px';
legacyCC.game.container.style.transformOrigin = '0px 0px 0px';
this._isRotated = true;
// Fix for issue: https://github.com/cocos-creator/fireball/issues/8365
// Reference: https://www.douban.com/note/343402554/
// For Chrome, z-index not working after container transform rotate 90deg.
// Because 'transform' style adds canvas (the top-element of container) to a new stack context.
// That causes the DOM Input was hidden under canvas.
// This should be done after container rotated, instead of in style-mobile.css.
legacyCC.game.canvas.style['-webkit-transform'] = 'translateZ(0px)';
legacyCC.game.canvas.style.transform = 'translateZ(0px)';
}
if (this._orientationChanging) {
setTimeout(() => {
legacyCC.view._orientationChanging = false;
}, 1000);
}
}
}
/**
@@ -748,45 +642,12 @@ class ContainerStrategy {
}
protected _setupContainer (_view, w, h) {
const locCanvas = legacyCC.game.canvas;
const locContainer = legacyCC.game.container;
if (sys.os === OS.ANDROID || sys.os === OS.OHOS) {
document.body.style.width = `${_view._isRotated ? h : w}px`;
document.body.style.height = `${_view._isRotated ? w : h}px`;
const locCanvas = game.canvas;
if (locCanvas) {
const windowSize = screen.windowSize;
locCanvas.width = windowSize.width;
locCanvas.height = windowSize.height;
}
// Setup style
locContainer.style.width = locCanvas.style.width = `${w}px`;
locContainer.style.height = locCanvas.style.height = `${h}px`;
// Setup pixel ratio for retina display
_view._devicePixelRatio = 1;
if (_view.isRetinaEnabled()) {
_view._devicePixelRatio = Math.min(_view._maxPixelRatio, window.devicePixelRatio || 1);
}
// Setup canvas
if (JSB) {
locCanvas.width = sys.windowPixelResolution.width;
locCanvas.height = sys.windowPixelResolution.height;
} else {
locCanvas.width = w * _view._devicePixelRatio;
locCanvas.height = h * _view._devicePixelRatio;
}
}
protected _fixContainer () {
// Add container to document body
document.body.insertBefore(legacyCC.game.container, document.body.firstChild);
// Set body's width height to window's size, and forbid overflow, so that game will be centered
const bs = document.body.style;
bs.width = `${window.innerWidth}px`;
bs.height = `${window.innerHeight}px`;
bs.overflow = 'hidden';
// Body size solution doesn't work on all mobile browser so this is the aleternative: fixed container
const contStyle = legacyCC.game.container.style;
contStyle.position = 'fixed';
contStyle.left = contStyle.top = '0px';
// Reposition body
document.body.scrollTop = 0;
}
}
@@ -875,16 +736,8 @@ class ContentStrategy {
class EqualToFrame extends ContainerStrategy {
public name = 'EqualToFrame';
public apply (_view) {
const frameH = _view._frameSize.height;
const containerStyle = legacyCC.game.container.style;
this._setupContainer(_view, _view._frameSize.width, _view._frameSize.height);
// Setup container's margin and padding
if (_view._isRotated) {
containerStyle.margin = `0 0 0 ${frameH}px`;
} else {
containerStyle.margin = '0px';
}
containerStyle.padding = '0px';
const windowSize = screen.windowSize;
this._setupContainer(_view, windowSize.width, windowSize.height);
}
}
@@ -895,8 +748,9 @@ class ContentStrategy {
class ProportionalToFrame extends ContainerStrategy {
public name = 'ProportionalToFrame';
public apply (_view, designedResolution) {
const frameW = _view._frameSize.width;
const frameH = _view._frameSize.height;
const windowSize = screen.windowSize;
const frameW = windowSize.width;
const frameH = windowSize.height;
const containerStyle = legacyCC.game.container.style;
const designW = designedResolution.width;
const designH = designedResolution.height;
@@ -922,7 +776,7 @@ class ContentStrategy {
this._setupContainer(_view, containerW, containerH);
if (!EDITOR) {
// Setup container's margin and padding
if (_view._isRotated) {
if (screenAdapter.isFrameRotated) {
containerStyle.margin = `0 0 0 ${frameH}px`;
} else {
containerStyle.margin = '0px';
@@ -935,18 +789,6 @@ class ContentStrategy {
}
}
// need to adapt prototype before instantiating
const _global = typeof window === 'undefined' ? global : window;
const globalAdapter = _global.__globalAdapter;
if (globalAdapter) {
if (globalAdapter.adaptContainerStrategy) {
globalAdapter.adaptContainerStrategy(ContainerStrategy.prototype);
}
if (globalAdapter.adaptView) {
globalAdapter.adaptView(View.prototype);
}
}
// Alias: Strategy that makes the container's size equals to the frame's size
ContainerStrategy.EQUAL_TO_FRAME = new EqualToFrame();
// Alias: Strategy that scale proportionally the container's size to frame's size
@@ -956,8 +798,9 @@ class ContentStrategy {
class ExactFit extends ContentStrategy {
public name = 'ExactFit';
public apply (_view: View, designedResolution: Size) {
const containerW = legacyCC.game.canvas.width;
const containerH = legacyCC.game.canvas.height;
const windowSize = screen.windowSize;
const containerW = windowSize.width;
const containerH = windowSize.height;
const scaleX = containerW / designedResolution.width;
const scaleY = containerH / designedResolution.height;
@@ -968,8 +811,9 @@ class ContentStrategy {
class ShowAll extends ContentStrategy {
public name = 'ShowAll';
public apply (_view, designedResolution) {
const containerW = legacyCC.game.canvas.width;
const containerH = legacyCC.game.canvas.height;
const windowSize = screen.windowSize;
const containerW = windowSize.width;
const containerH = windowSize.height;
const designW = designedResolution.width;
const designH = designedResolution.height;
const scaleX = containerW / designW;
@@ -995,8 +839,9 @@ class ContentStrategy {
class NoBorder extends ContentStrategy {
public name = 'NoBorder';
public apply (_view, designedResolution) {
const containerW = legacyCC.game.canvas.width;
const containerH = legacyCC.game.canvas.height;
const windowSize = screen.windowSize;
const containerW = windowSize.width;
const containerH = windowSize.height;
const designW = designedResolution.width;
const designH = designedResolution.height;
const scaleX = containerW / designW;
@@ -1022,8 +867,9 @@ class ContentStrategy {
class FixedHeight extends ContentStrategy {
public name = 'FixedHeight';
public apply (_view, designedResolution) {
const containerW = legacyCC.game.canvas.width;
const containerH = legacyCC.game.canvas.height;
const windowSize = screen.windowSize;
const containerW = windowSize.width;
const containerH = windowSize.height;
const designH = designedResolution.height;
const scale = containerH / designH;
const contentW = containerW;
@@ -1036,8 +882,9 @@ class ContentStrategy {
class FixedWidth extends ContentStrategy {
public name = 'FixedWidth';
public apply (_view, designedResolution) {
const containerW = legacyCC.game.canvas.width;
const containerH = legacyCC.game.canvas.height;
const windowSize = screen.windowSize;
const containerW = windowSize.width;
const containerH = windowSize.height;
const designW = designedResolution.width;
const scale = containerW / designW;
const contentW = containerW;
@@ -1118,7 +965,7 @@ export class ResolutionPolicy {
}
get canvasSize () {
return new Vec2(legacyCC.game.canvas.width, legacyCC.game.canvas.height);
return screen.windowSize;
}
/**
@@ -1127,7 +974,6 @@ export class ResolutionPolicy {
* @param _view The target view
*/
public preApply (_view: View) {
this._containerStrategy!.preApply(_view);
this._contentStrategy!.preApply(_view);
}
@@ -1151,7 +997,6 @@ export class ResolutionPolicy {
* @param _view - The target view
*/
public postApply (_view: View) {
this._containerStrategy!.postApply(_view);
this._contentStrategy!.postApply(_view);
}
+1 -7
View File
@@ -287,13 +287,7 @@ export class Root {
});
this._curWindow = this._mainWindow;
return Promise.resolve(builtinResMgr.initBuiltinRes(this._device)).then(() => {
legacyCC.view.on('design-resolution-changed', () => {
const width = legacyCC.game.canvas.width;
const height = legacyCC.game.canvas.height;
this.resize(width, height);
}, this);
});
return Promise.resolve(builtinResMgr.initBuiltinRes(this._device));
}
public destroy () {
+1 -2
View File
@@ -42,7 +42,7 @@ import { PipelineStateManager } from './pipeline';
import { legacyCC } from './global-exports';
import { Root } from './root';
import { SetIndex } from './pipeline/define';
import { error } from './platform';
import { error } from './platform/debug';
import { Mat4, Vec2 } from './math';
const v2_0 = new Vec2();
@@ -128,7 +128,6 @@ export class SplashScreen {
(this.settings as any) = null;
this._directCall = true;
} else {
legacyCC.view.enableRetina(true);
legacyCC.view.resizeWithBrowserSize(true);
const designRes = window._CCSettings.designResolution;
if (designRes) {
+2 -2
View File
@@ -29,8 +29,8 @@
* @module core
*/
import { systemInfo } from 'pal/system-info';
import { OS } from '../../../pal/system-info/enum-type';
import { sys } from '../platform/sys';
const EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/;
const DIRNAME_RE = /((.*)(\/|\\|\\\\))?(.*?\..*$)?/;
@@ -164,5 +164,5 @@ export function stripSep (path: string) {
}
export function getSeperator () {
return sys.os === OS.WINDOWS ? '\\' : '/';
return systemInfo.os === OS.WINDOWS ? '\\' : '/';
}
+2 -2
View File
@@ -215,7 +215,7 @@ export class EventMouse extends Event {
}
Vec2.set(out, this._x, this._y);
legacyCC.view._convertPointWithScale(out);
legacyCC.view._convertToUISpace(out);
return out;
}
@@ -244,7 +244,7 @@ export class EventMouse extends Event {
}
Vec2.set(out, this._prevX, this._prevY);
legacyCC.view._convertPointWithScale(out);
legacyCC.view._convertToUISpace(out);
return out;
}
+1 -1
View File
@@ -1,4 +1,4 @@
export * from './event';
export * from './event/index';
export * from './acceleration';
export { SystemEventType } from './event-enum';
export * from './key-code';
+4 -4
View File
@@ -99,7 +99,7 @@ export class Touch {
}
out.set(this._point.x, this._point.y);
legacyCC.view._convertPointWithScale(out);
legacyCC.view._convertToUISpace(out);
return out;
}
@@ -146,7 +146,7 @@ export class Touch {
}
out.set(this._prevPoint.x, this._prevPoint.y);
legacyCC.view._convertPointWithScale(out);
legacyCC.view._convertToUISpace(out);
return out;
}
@@ -175,7 +175,7 @@ export class Touch {
}
out.set(this._startPoint.x, this._startPoint.y);
legacyCC.view._convertPointWithScale(out);
legacyCC.view._convertToUISpace(out);
return out;
}
@@ -274,7 +274,7 @@ export class Touch {
this._id = id;
if (!this._startPointCaptured) {
this._startPoint = new Vec2(this._point);
// cc.view._convertPointWithScale(this._startPoint);
// cc.view._convertToUISpace(this._startPoint);
this._startPointCaptured = true;
}
}
+5 -10
View File
@@ -31,6 +31,7 @@
* @hidden
*/
import { screenAdapter } from 'pal/screen-adapter';
import { BitmapFont } from '../../2d/assets';
import { director } from '../../core/director';
import { game } from '../../core/game';
@@ -102,8 +103,6 @@ export class EditBoxImpl extends EditBoxImplBase {
this._initStyleSheet();
this._registerEventListeners();
this._addDomToGameContainer();
this.__autoResize = view._resizeWithBrowserSize;
}
public clear () {
@@ -226,18 +225,13 @@ export class EditBoxImpl extends EditBoxImplBase {
return;
}
if (this.__autoResize) {
view.resizeWithBrowserSize(false);
}
screenAdapter.handleResizeEvent = false;
this._adjustWindowScroll();
}
private _hideDomOnMobile () {
if (sys.os === OS.ANDROID || sys.os === OS.OHOS) {
if (this.__autoResize) {
view.resizeWithBrowserSize(true);
}
screenAdapter.handleResizeEvent = true;
}
this._scrollBackWindow();
@@ -282,7 +276,8 @@ export class EditBoxImpl extends EditBoxImplBase {
scaleX *= widthRatio;
scaleY *= heightRatio;
const viewport = view.getViewportRect();
const dpr = view.getDevicePixelRatio();
// TODO: implement editBox in PAL
const dpr = screenAdapter.devicePixelRatio;
node.getWorldMatrix(_matrix);
const transform = node._uiProps.uiTransformComp;
+2 -2
View File
@@ -65,12 +65,12 @@ export class SafeArea extends Component {
public onEnable () {
this.updateArea();
// IDEA: need to delay the callback on Native platform ?
screenAdapter.on('window-resize', this.updateArea, this);
screenAdapter.on('resolution-change', this.updateArea, this);
screenAdapter.on('orientation-change', this.updateArea, this);
}
public onDisable () {
screenAdapter.off('window-resize', this.updateArea, this);
screenAdapter.off('resolution-change', this.updateArea, this);
screenAdapter.off('orientation-change', this.updateArea, this);
}
+2 -2
View File
@@ -31,12 +31,12 @@
import { ccclass, help, menu, executionOrder, requireComponent, tooltip, serializable } from 'cc.decorator';
import { EDITOR } from 'internal:constants';
import { minigame } from 'pal/minigame';
import { screenAdapter } from 'pal/screen-adapter';
import { Component } from '../core/components/component';
import { view } from '../core/platform/view';
import { Sprite } from '../2d/components/sprite';
import { Node } from '../core/scene-graph';
import { UITransform } from '../2d/framework/ui-transform';
import { SpriteFrame } from '../2d/assets';
import { ImageAsset } from '../core/assets/image-asset';
import { Size } from '../core/math';
@@ -194,7 +194,7 @@ export class SubContextView extends Component {
const viewportRect = view.getViewportRect();
const box = contentTrans.getBoundingBoxToWorld();
const visibleSize = view.getVisibleSize();
const dpr = view.getDevicePixelRatio();
const dpr = screenAdapter.devicePixelRatio;
// TODO: the visibleSize need to be the size of Canvas node where the content node is.
const x = (viewportRect.width * (box.x / visibleSize.width) + viewportRect.x) / dpr;
+4 -2
View File
@@ -28,8 +28,9 @@
* @module component/video
*/
import { screenAdapter } from 'pal/screen-adapter';
import { mat4 } from '../core/math';
import { sys, view, screen, warn } from '../core/platform';
import { sys, screen, warn } from '../core/platform';
import { game } from '../core';
import { contains } from '../core/utils/misc';
import { EventType, READY_STATE } from './video-player-enums';
@@ -386,7 +387,8 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl {
this._w = width;
this._h = height;
const dpr = view.getDevicePixelRatio();
// TODO: implement videoPlayer in PAL
const dpr = screenAdapter.devicePixelRatio;
const scaleX = 1 / dpr;
const scaleY = 1 / dpr;
+4 -2
View File
@@ -28,8 +28,9 @@
* @module component/web-view
*/
import { screenAdapter } from 'pal/screen-adapter';
import { EventType } from './web-view-enums';
import { error, warn, view } from '../core/platform';
import { error, warn } from '../core/platform';
import { WebViewImpl } from './web-view-impl';
import { game } from '../core';
import { mat4 } from '../core/math';
@@ -164,7 +165,8 @@ export class WebViewImplWeb extends WebViewImpl {
this._w = width;
this._h = height;
const dpr = view.getDevicePixelRatio();
// TODO: implement webView in PAL
const dpr = screenAdapter.devicePixelRatio;
const scaleX = 1 / dpr;
const scaleY = 1 / dpr;
+3 -8
View File
@@ -5,7 +5,6 @@ import { systemInfo } from 'pal/system-info';
import { Vec2 } from '../../../cocos/core/math';
import { EventTarget } from '../../../cocos/core/event';
import { EventMouse } from '../../../cocos/input/types';
import { legacyCC } from '../../../cocos/core/global-exports';
import { InputEventType } from '../../../cocos/input/types/event-enum';
import { Feature } from '../../system-info/enum-type';
@@ -22,13 +21,9 @@ export class MouseInputSource {
private _getLocation (event: MouseEventData): Vec2 {
const windowSize = screenAdapter.windowSize;
let x = event.x;
let y = windowSize.height - event.y;
// TODO: should not call engine API
const view = legacyCC.view;
const dpr = view._devicePixelRatio;
x *= dpr;
y *= dpr;
const dpr = screenAdapter.devicePixelRatio;
const x = event.x * dpr;
const y = windowSize.height - event.y * dpr;
return new Vec2(x, y);
}
+3 -8
View File
@@ -4,7 +4,6 @@ import { screenAdapter } from 'pal/screen-adapter';
import { Size, Vec2 } from '../../../cocos/core/math';
import { EventTarget } from '../../../cocos/core/event';
import { EventTouch, Touch } from '../../../cocos/input/types';
import { legacyCC } from '../../../cocos/core/global-exports';
import { touchManager } from '../touch-manager';
import { macro } from '../../../cocos/core/platform/macro';
import { InputEventType } from '../../../cocos/input/types/event-enum';
@@ -56,13 +55,9 @@ export class TouchInputSource {
}
private _getLocation (touch: globalThis.Touch, windowSize: Size): Vec2 {
let x = touch.clientX;
let y = windowSize.height - touch.clientY;
// TODO: should not call engine API
const view = legacyCC.view;
const dpr = view._devicePixelRatio;
x *= dpr;
y *= dpr;
const dpr = screenAdapter.devicePixelRatio;
const x = touch.clientX * dpr;
const y = windowSize.height - touch.clientY * dpr;
return new Vec2(x, y);
}
+3 -9
View File
@@ -1,10 +1,8 @@
import { MouseCallback } from 'pal/input';
import { screenAdapter } from 'pal/screen-adapter';
import { systemInfo } from 'pal/system-info';
import { EventMouse } from '../../../cocos/input/types';
import { EventTarget } from '../../../cocos/core/event';
import { Vec2 } from '../../../cocos/core/math';
import { legacyCC } from '../../../cocos/core/global-exports';
import { InputEventType } from '../../../cocos/input/types/event-enum';
export class MouseInputSource {
@@ -18,13 +16,9 @@ export class MouseInputSource {
private _getLocation (event: jsb.MouseEvent): Vec2 {
const windowSize = screenAdapter.windowSize;
let x = event.x;
let y = windowSize.height - event.y;
// TODO: should not call engine API
const view = legacyCC.view;
const dpr = view._devicePixelRatio;
x *= dpr;
y *= dpr;
const dpr = screenAdapter.devicePixelRatio;
const x = event.x * dpr;
const y = windowSize.height - event.y * dpr;
return new Vec2(x, y);
}
+3 -8
View File
@@ -4,7 +4,6 @@ import { Size, Vec2 } from '../../../cocos/core/math';
import { EventTarget } from '../../../cocos/core/event';
import { EventTouch, Touch } from '../../../cocos/input/types';
import { touchManager } from '../touch-manager';
import { legacyCC } from '../../../cocos/core/global-exports';
import { macro } from '../../../cocos/core/platform/macro';
import { InputEventType } from '../../../cocos/input/types/event-enum';
@@ -55,13 +54,9 @@ export class TouchInputSource {
}
private _getLocation (touch: globalThis.Touch, windowSize: Size): Vec2 {
let x = touch.clientX;
let y = windowSize.height - touch.clientY;
// TODO: should not call engine API
const view = legacyCC.view;
const dpr = view._devicePixelRatio;
x *= dpr;
y *= dpr;
const dpr = screenAdapter.devicePixelRatio;
const x = touch.clientX * dpr;
const y = windowSize.height - touch.clientY * dpr;
return new Vec2(x, y);
}
+3 -4
View File
@@ -1,8 +1,8 @@
import { AccelerometerCallback } from 'pal/input';
import { systemInfo } from 'pal/system-info';
import { EventTarget } from '../../../cocos/core/event';
import { screenAdapter } from 'pal/screen-adapter';
import { EventTarget } from '../../../cocos/core/event/event-target';
import { BrowserType, OS } from '../../system-info/enum-type';
import { legacyCC } from '../../../cocos/core/global-exports';
import { EventAcceleration, Acceleration } from '../../../cocos/input/types';
import { InputEventType } from '../../../cocos/input/types/event-enum';
@@ -58,8 +58,7 @@ export class AccelerometerInputSource {
z = ((deviceOrientationEvent.alpha || 0) / 90) * 0.981;
}
// TODO: should not call engine API
if (legacyCC.view._isRotated) {
if (screenAdapter.isFrameRotated) {
const tmp = x;
x = -y;
y = tmp;
+2 -4
View File
@@ -1,10 +1,10 @@
import { TEST } from 'internal:constants';
import { MouseCallback } from 'pal/input';
import { systemInfo } from 'pal/system-info';
import { screenAdapter } from 'pal/screen-adapter';
import { EventMouse } from '../../../cocos/input/types';
import { EventTarget } from '../../../cocos/core/event';
import { Rect, Vec2 } from '../../../cocos/core/math';
import legacyCC from '../../../predefine';
import { InputEventType } from '../../../cocos/input/types/event-enum';
import { Feature } from '../../system-info/enum-type';
@@ -36,9 +36,7 @@ export class MouseInputSource {
private _getLocation (mouseEvent: MouseEvent): Vec2 {
const canvasRect = this._getCanvasRect();
// TODO: should not call engine API
const view = legacyCC.view;
const dpr = view._devicePixelRatio;
const dpr = screenAdapter.devicePixelRatio;
let x = this._pointLocked ? (this._preMousePos.x / dpr + mouseEvent.movementX) : (mouseEvent.clientX - canvasRect.x);
let y = this._pointLocked ? (this._preMousePos.y / dpr - mouseEvent.movementY) : (canvasRect.y + canvasRect.height - mouseEvent.clientY);
x *= dpr;
+3 -5
View File
@@ -1,9 +1,9 @@
import { TouchCallback } from 'pal/input';
import { TEST } from 'internal:constants';
import { systemInfo } from 'pal/system-info';
import { screenAdapter } from 'pal/screen-adapter';
import { Rect, Vec2 } from '../../../cocos/core/math';
import { EventTarget } from '../../../cocos/core/event';
import { legacyCC } from '../../../cocos/core/global-exports';
import { Touch, EventTouch } from '../../../cocos/input/types';
import { touchManager } from '../touch-manager';
import { macro } from '../../../cocos/core/platform/macro';
@@ -83,14 +83,12 @@ export class TouchInputSource {
private _getLocation (touch: globalThis.Touch, canvasRect: Rect): Vec2 {
let x = touch.clientX - canvasRect.x;
let y = canvasRect.y + canvasRect.height - touch.clientY;
// TODO: should not call engine API
const view = legacyCC.view;
if (view._isRotated) {
if (screenAdapter.isFrameRotated) {
const tmp = x;
x = canvasRect.height - y;
y = tmp;
}
const dpr = view._devicePixelRatio;
const dpr = screenAdapter.devicePixelRatio;
x *= dpr;
y *= dpr;
return new Vec2(x, y);
+13 -7
View File
@@ -1,9 +1,15 @@
const LEFT = 1 << 2;
const RIGHT = 1 << 3;
const _PORTRAIT = 1;
const _PORTRAIT_UPSIDE_DOWN = _PORTRAIT << 1;
const _LEFT = _PORTRAIT << 2;
const _RIGHT = _PORTRAIT << 3;
const _LANDSCAPE = _LEFT | _RIGHT;
const _AUTO = _PORTRAIT | _LANDSCAPE;
export enum Orientation {
PORTRAIT = 1,
PORTRAIT_UPSIDE_DOWN = 1 << 1,
LANDSCAPE_LEFT = LEFT,
LANDSCAPE_RIGHT = RIGHT,
LANDSCAPE = LEFT | RIGHT,
PORTRAIT = _PORTRAIT,
PORTRAIT_UPSIDE_DOWN = _PORTRAIT_UPSIDE_DOWN,
LANDSCAPE_LEFT = _LEFT,
LANDSCAPE_RIGHT = _RIGHT,
LANDSCAPE = _LANDSCAPE,
AUTO = _AUTO,
}
+1 -1
View File
@@ -1 +1 @@
export type PalScreenEvent = 'window-resize' | 'orientation-change' | 'fullscreen-change';
export type PalScreenEvent = 'window-resize' | 'resolution-change' | 'orientation-change' | 'fullscreen-change';
+107 -11
View File
@@ -1,14 +1,40 @@
import { ALIPAY, BAIDU, COCOSPLAY, RUNTIME_BASED, VIVO } from 'internal:constants';
import { minigame } from 'pal/minigame';
import { SafeAreaEdge } from 'pal/screen-adapter';
import { EventTarget } from '../../../cocos/core/event';
import { systemInfo } from 'pal/system-info';
import { warnID } from '../../../cocos/core/platform/debug';
import { EventTarget } from '../../../cocos/core/event/event-target';
import { Size } from '../../../cocos/core/math';
import { OS } from '../../system-info/enum-type';
import { Orientation } from '../enum-type';
class ScreenAdapter extends EventTarget {
constructor () {
super();
// TODO: onResize or onOrientationChange is not supported well
// HACK: In some platform like CocosPlay or Alipay iOS end
// the windowSize need to rotate when init screenAdapter if it's landscape
let rotateLandscape = false;
try {
if (ALIPAY) {
if (systemInfo.os === OS.IOS && !minigame.isDevTool) {
// @ts-expect-error TODO: use pal/fs
const fs = my.getFileSystemManager();
const screenOrientation = JSON.parse(fs.readFileSync({
filePath: 'game.json',
encoding: 'utf8',
}).data).screenOrientation;
rotateLandscape = (screenOrientation === 'landscape');
}
} else if (COCOSPLAY) {
// @ts-expect-error TODO: use pal/fs
const fs = ral.getFileSystemManager();
const deviceOrientation = JSON.parse(fs.readFileSync('game.config.json', 'utf8')).deviceOrientation;
rotateLandscape = (deviceOrientation === 'landscape');
}
} catch (e) {
console.error(e);
}
class ScreenAdapter extends EventTarget {
public isFrameRotated = false;
public handleResizeEvent = true;
public get supportFullScreen (): boolean {
return false;
@@ -16,23 +42,61 @@ class ScreenAdapter extends EventTarget {
public get isFullScreen (): boolean {
return false;
}
public get devicePixelRatio () {
if (VIVO) {
// NOTE: wrong DPR on vivo platform
return 1;
}
const sysInfo = minigame.getSystemInfoSync();
return sysInfo.pixelRatio;
}
public get windowSize (): Size {
const sysInfo = minigame.getSystemInfoSync();
return new Size(sysInfo.screenWidth, sysInfo.screenHeight);
const dpr = this.devicePixelRatio;
let screenWidth = sysInfo.screenWidth;
let screenHeight = sysInfo.screenHeight;
if ((COCOSPLAY || ALIPAY) && rotateLandscape && screenWidth < screenHeight) {
const temp = screenWidth;
screenWidth = screenHeight;
screenHeight = temp;
}
return new Size(screenWidth * dpr, screenHeight * dpr);
}
public set windowSize (size: Size) {
console.warn('Setting window size is not supported on this platform.');
warnID(1221);
}
public get resolution () {
return this._resolution;
}
public get resolutionScale () {
return this._resolutionScale;
}
public set resolutionScale (value: number) {
if (value === this._resolutionScale) {
return;
}
this._resolutionScale = value;
this._updateResolution();
}
public get orientation (): Orientation {
return minigame.orientation;
}
public set orientation (value: Orientation) {
console.warn('Setting orientation is not supported yet.');
}
public get safeAreaEdge (): SafeAreaEdge {
const minigameSafeArea = minigame.getSafeArea();
const windowSize = this.windowSize;
let topEdge = minigameSafeArea.top;
let bottomEdge = windowSize.height - minigameSafeArea.bottom;
let leftEdge = minigameSafeArea.left;
let rightEdge = windowSize.width - minigameSafeArea.right;
const dpr = this.devicePixelRatio;
let topEdge = minigameSafeArea.top * dpr;
let bottomEdge = windowSize.height - minigameSafeArea.bottom * dpr;
let leftEdge = minigameSafeArea.left * dpr;
let rightEdge = windowSize.width - minigameSafeArea.right * dpr;
const orientation = this.orientation;
// Make it symmetrical.
if (orientation === Orientation.PORTRAIT) {
@@ -53,12 +117,44 @@ class ScreenAdapter extends EventTarget {
right: rightEdge,
};
}
private _cbToUpdateFrameBuffer?: () => void;
private _resolution: Size = new Size(0, 0);
private _resolutionScale = 1;
constructor () {
super();
// TODO: onResize or onOrientationChange is not supported well
}
public init (cbToRebuildFrameBuffer: () => void) {
this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer;
this._updateResolution();
}
public requestFullScreen (): Promise<void> {
return Promise.reject(new Error('request fullscreen is not supported on this platform.'));
}
public exitFullScreen (): Promise<void> {
return Promise.reject(new Error('exit fullscreen is not supported on this platform.'));
}
private _updateResolution () {
const windowSize = this.windowSize;
// update resolution
this._resolution.width = windowSize.width;
this._resolution.height = windowSize.height;
// NOTE: on Alipay iOS end, the resolution size need forcing to be screenSize * dpr.
if (ALIPAY && systemInfo.os === OS.IOS) {
this._resolution.width *= this.devicePixelRatio;
this._resolution.height *= this.devicePixelRatio;
} else {
this._resolution.width *= this.resolutionScale;
this._resolution.height *= this.resolutionScale;
}
this._cbToUpdateFrameBuffer?.();
this.emit('resolution-change');
}
}
export const screenAdapter = new ScreenAdapter();
+75 -26
View File
@@ -1,6 +1,5 @@
import { SafeAreaEdge } from 'pal/screen-adapter';
import { systemInfo } from 'pal/system-info';
import { EventTarget } from '../../../cocos/core/event';
import { EventTarget } from '../../../cocos/core/event/event-target';
import { Size } from '../../../cocos/core/math';
import { Orientation } from '../enum-type';
@@ -13,25 +12,8 @@ const orientationMap: Record<string, Orientation> = {
};
class ScreenAdapter extends EventTarget {
constructor () {
super();
this._registerEvent();
}
private _registerEvent () {
jsb.onResize = (size) => {
if (size.width === 0 || size.height === 0) return;
size.width /= systemInfo.pixelRatio;
size.height /= systemInfo.pixelRatio;
// TODO: remove this function calling
window.resize(size.width, size.height);
this.emit('window-resize');
};
jsb.onOrientationChanged = (event) => {
this.emit('orientation-change');
};
}
public isFrameRotated = false;
public handleResizeEvent = true;
public get supportFullScreen (): boolean {
return false;
@@ -39,21 +21,50 @@ class ScreenAdapter extends EventTarget {
public get isFullScreen (): boolean {
return false;
}
public get devicePixelRatio () {
return jsb.device.getDevicePixelRatio() || 1;
}
public get windowSize (): Size {
return new Size(window.innerWidth, window.innerHeight);
const dpr = this.devicePixelRatio;
// NOTE: fix precision issue on Metal render end.
const roundWidth = Math.round(window.innerWidth);
const roundHeight = Math.round(window.innerHeight);
return new Size(roundWidth * dpr, roundHeight * dpr);
}
public set windowSize (size: Size) {
console.warn('Setting window size is not supported yet.');
}
public get resolution () {
return this._resolution;
}
public get resolutionScale () {
return this._resolutionScale;
}
public set resolutionScale (v: number) {
if (v === this._resolutionScale) {
return;
}
this._resolutionScale = v;
this._updateResolution();
}
public get orientation (): Orientation {
return orientationMap[jsb.device.getDeviceOrientation()];
}
public set orientation (value: Orientation) {
console.warn('Setting orientation is not supported yet.');
}
public get safeAreaEdge (): SafeAreaEdge {
const nativeSafeArea = jsb.device.getSafeAreaEdge();
let topEdge = nativeSafeArea.x;
let bottomEdge = nativeSafeArea.z;
let leftEdge = nativeSafeArea.y;
let rightEdge = nativeSafeArea.w;
const dpr = this.devicePixelRatio;
let topEdge = nativeSafeArea.x * dpr;
let bottomEdge = nativeSafeArea.z * dpr;
let leftEdge = nativeSafeArea.y * dpr;
let rightEdge = nativeSafeArea.w * dpr;
const orientation = this.orientation;
// Make it symmetrical.
if (orientation === Orientation.PORTRAIT) {
@@ -74,12 +85,50 @@ class ScreenAdapter extends EventTarget {
right: rightEdge,
};
}
private _cbToUpdateFrameBuffer?: () => void;
private _resolution: Size = new Size(1, 1); // NOTE: crash when init device if resolution is Size.ZERO on native platform.
private _resolutionScale = 1;
constructor () {
super();
this._registerEvent();
}
public init (cbToRebuildFrameBuffer: () => void) {
this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer;
this._updateResolution();
}
public requestFullScreen (): Promise<void> {
return Promise.reject(new Error('request fullscreen has not been supported yet on this platform.'));
}
public exitFullScreen (): Promise<void> {
return Promise.reject(new Error('exit fullscreen has not been supported yet on this platform.'));
}
private _registerEvent () {
jsb.onResize = (size) => {
if (size.width === 0 || size.height === 0) return;
size.width /= this.devicePixelRatio;
size.height /= this.devicePixelRatio;
// TODO: remove this function calling
window.resize(size.width, size.height);
this.emit('window-resize');
};
jsb.onOrientationChanged = (event) => {
this.emit('orientation-change');
};
}
private _updateResolution () {
const windowSize = this.windowSize;
// update resolution
this._resolution.width = windowSize.width * this.resolutionScale;
this._resolution.height = windowSize.height * this.resolutionScale;
this._cbToUpdateFrameBuffer?.();
this.emit('resolution-change');
}
}
export const screenAdapter = new ScreenAdapter();
+217 -84
View File
@@ -1,6 +1,9 @@
import { EDITOR, TEST } from 'internal:constants';
import { SafeAreaEdge } from 'pal/screen-adapter';
import { EventTarget } from '../../../cocos/core/event';
import { systemInfo } from 'pal/system-info';
import { EventTarget } from '../../../cocos/core/event/event-target';
import { Size } from '../../../cocos/core/math';
import { OS } from '../../system-info/enum-type';
import { Orientation } from '../enum-type';
interface IScreenFunctionName {
@@ -13,7 +16,106 @@ interface IScreenFunctionName {
}
class ScreenAdapter extends EventTarget {
public isFrameRotated = false;
public handleResizeEvent = true;
public get supportFullScreen (): boolean {
return this._supportFullScreen;
}
public get isFullScreen (): boolean {
if (!this._supportFullScreen) {
return false;
}
return !!document[this._fn.fullscreenElement];
}
public get devicePixelRatio () {
return window.devicePixelRatio || 1;
}
public get windowSize (): Size {
const result = this._windowSizeInCssPixels;
const dpr = this.devicePixelRatio;
result.width *= dpr;
result.height *= dpr;
return result;
}
public set windowSize (size: Size) {
if (systemInfo.isMobile || EDITOR) {
// We say that on web mobile, the window size equals to the browser inner size.
// The window size is readonly on web mobile.
return;
}
this._resizeFrame(this._convertToSizeInCssPixels(size));
}
public get resolution () {
return this._resolution;
}
public get resolutionScale () {
return this._resolutionScale;
}
public set resolutionScale (v: number) {
if (v === this._resolutionScale) {
return;
}
this._resolutionScale = v;
this._updateResolution();
}
public get orientation (): Orientation {
return this._orientation;
}
public set orientation (value: Orientation) {
if (this._orientation === value) {
return;
}
this._orientation = value;
if (!this._gameFrame) {
return;
}
const width = window.innerWidth;
const height = window.innerHeight;
const isBrowserLandscape = width > height;
const needToRotateDocument = systemInfo.isMobile && systemInfo.os === OS.ANDROID
&& ((isBrowserLandscape && value & Orientation.PORTRAIT) || (!isBrowserLandscape && value & Orientation.LANDSCAPE));
if (needToRotateDocument) {
this.isFrameRotated = true;
this._gameFrame.style['-webkit-transform'] = 'rotate(90deg)';
this._gameFrame.style.transform = 'rotate(90deg)';
this._gameFrame.style['-webkit-transform-origin'] = '0px 0px 0px';
this._gameFrame.style.transformOrigin = '0px 0px 0px';
this._gameFrame.style.margin = `0 0 0 ${width}px`;
this._gameFrame.style.width = `${height}px`;
this._gameFrame.style.height = `${width}px`;
this._resizeFrame(new Size(height, width));
} else {
this.isFrameRotated = false;
this._gameFrame.style['-webkit-transform'] = 'rotate(0deg)';
this._gameFrame.style.transform = 'rotate(0deg)';
// TODO
// this._gameFrame.style['-webkit-transform-origin'] = '0px 0px 0px';
// this._gameFrame.style.transformOrigin = '0px 0px 0px';
this._gameFrame.style.margin = '0px';
this._gameFrame.style.width = `${width}px`;
this._gameFrame.style.height = `${height}px`;
this._resizeFrame(new Size(width, height));
}
}
public get safeAreaEdge (): SafeAreaEdge {
return {
top: 0,
bottom: 0,
left: 0,
right: 0,
};
}
private _gameFrame?: HTMLDivElement;
private _gameContainer?: HTMLDivElement;
private _gameCanvas?: HTMLCanvasElement;
private _cbToUpdateFrameBuffer?: () => void;
private _supportFullScreen = false;
private _touchEventName: string;
private _onFullscreenChange?: () => void;
@@ -62,11 +164,30 @@ class ScreenAdapter extends EventTarget {
'msfullscreenerror',
],
];
private get _windowSizeInCssPixels () {
if (systemInfo.isMobile || EDITOR || TEST) {
if (this.isFrameRotated) {
return new Size(window.innerHeight, window.innerWidth);
}
return new Size(window.innerWidth, window.innerHeight);
} else {
if (!this._gameFrame) {
console.warn('Cannot access game frame');
return new Size(0, 0);
}
return new Size(this._gameFrame.clientWidth, this._gameFrame.clientHeight);
}
}
private _resolution: Size = new Size(0, 0);
private _resolutionScale = 1;
private _orientation = Orientation.AUTO;
constructor () {
super();
// TODO: need to access frame from 'pal/launcher' module
this._gameFrame = document.getElementById('GameDiv') as HTMLDivElement;
this._gameContainer = document.getElementById('Cocos3dGameContainer') as HTMLDivElement;
this._gameCanvas = document.getElementById('GameCanvas') as HTMLCanvasElement;
let fnList: Array<string>;
const fnGroup = this._fnGroup;
@@ -86,98 +207,22 @@ class ScreenAdapter extends EventTarget {
this._registerEvent();
}
private _registerEvent () {
document.addEventListener(this._fn.fullscreenerror, () => {
this._onFullscreenError?.();
});
document.addEventListener(this._fn.fullscreenchange, () => {
this._onFullscreenChange?.();
});
window.addEventListener('resize', () => {
this.emit('window-resize');
});
if (typeof window.matchMedia === 'function') {
const updateDPRChangeListener = () => {
const dpr = window.devicePixelRatio;
window.matchMedia(`(resolution: ${dpr}dppx)`).addEventListener('change', () => {
this.emit('window-resize');
updateDPRChangeListener();
}, { once: true });
};
updateDPRChangeListener();
}
window.addEventListener('orientationchange', () => {
this.emit('orientation-change');
});
document.addEventListener(this._fn.fullscreenchange, () => {
this.emit('fullscreen-change');
});
public init (cbToRebuildFrameBuffer: () => void) {
this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer;
this._resizeFrame(this._windowSizeInCssPixels);
}
public get supportFullScreen (): boolean {
return this._supportFullScreen;
}
public get isFullScreen (): boolean {
if (!this._supportFullScreen) {
return false;
}
return !!document[this._fn.fullscreenElement];
}
public get windowSize (): Size {
if (this._gameFrame) {
return new Size(this._gameFrame.clientWidth, this._gameFrame.clientHeight);
} else {
return new Size(window.innerWidth, window.innerHeight);
}
}
public set windowSize (size: Size) {
console.warn('Setting window size is not supported yet.');
}
public get orientation (): Orientation {
return Orientation.PORTRAIT; // TO BE IMPLEMENTED
}
public get safeAreaEdge (): SafeAreaEdge {
return {
top: 0,
bottom: 0,
left: 0,
right: 0,
};
}
private _doRequestFullScreen (): Promise<void> {
return new Promise((resolve, reject) => {
if (!this._gameFrame) {
reject(new Error('Cannot access game frame'));
return;
}
if (!this._supportFullScreen) {
reject(new Error('fullscreen is not supported'));
return;
}
this._onFullscreenChange = undefined;
this._onFullscreenError = undefined;
const requestPromise = this._gameFrame[this._fn.requestFullscreen]() as Promise<void> | undefined;
if (window.Promise && requestPromise instanceof Promise) {
requestPromise.then(resolve).catch(reject);
} else {
this._onFullscreenChange = resolve;
this._onFullscreenError = reject;
}
});
}
public requestFullScreen (): Promise<void> {
return new Promise((resolve, reject) => {
this._doRequestFullScreen().then(() => {
resolve();
}).catch(() => {
if (!this._gameFrame) {
reject(new Error('Cannot access game frame'));
const fullscreenTarget = this._getFullscreenTarget();
if (!fullscreenTarget) {
reject(new Error('Cannot access fullscreen target'));
return;
}
this._gameFrame.addEventListener(this._touchEventName, () => {
fullscreenTarget.addEventListener(this._touchEventName, () => {
this._doRequestFullScreen().then(() => {
resolve();
}).catch(reject);
@@ -195,6 +240,94 @@ class ScreenAdapter extends EventTarget {
resolve();
});
}
private _registerEvent () {
document.addEventListener(this._fn.fullscreenerror, () => {
this._onFullscreenError?.();
});
window.addEventListener('resize', () => {
if (!this.handleResizeEvent) {
return;
}
this._resizeFrame(this._windowSizeInCssPixels);
});
if (typeof window.matchMedia === 'function') {
const updateDPRChangeListener = () => {
const dpr = window.devicePixelRatio;
window.matchMedia(`(resolution: ${dpr}dppx)`).addEventListener('change', () => {
this.emit('window-resize');
updateDPRChangeListener();
}, { once: true });
};
updateDPRChangeListener();
}
window.addEventListener('orientationchange', () => {
if (!this.handleResizeEvent) {
return;
}
this._resizeFrame(this._windowSizeInCssPixels);
this.emit('orientation-change');
});
document.addEventListener(this._fn.fullscreenchange, () => {
this._resizeFrame(this._windowSizeInCssPixels);
this._onFullscreenChange?.();
this.emit('fullscreen-change');
});
}
private _convertToSizeInCssPixels (size: Size) {
const clonedSize = size.clone();
const dpr = this.devicePixelRatio;
clonedSize.width /= dpr;
clonedSize.height /= dpr;
return clonedSize;
}
private _resizeFrame (sizeInCssPixels: Size) {
if (this._gameFrame) {
this._gameFrame.style.width = `${sizeInCssPixels.width}px`;
this._gameFrame.style.height = `${sizeInCssPixels.height}px`;
this.emit('window-resize');
}
this._updateResolution();
}
private _updateResolution () {
const windowSize = this.windowSize;
// update resolution
this._resolution.width = windowSize.width * this.resolutionScale;
this._resolution.height = windowSize.height * this.resolutionScale;
this._cbToUpdateFrameBuffer?.();
this.emit('resolution-change');
}
private _getFullscreenTarget () {
// On web mobile, the transform of game frame doesn't work when it's on fullscreen.
// So we need to make the body fullscreen.
return systemInfo.isMobile ? document.body : this._gameFrame;
}
private _doRequestFullScreen (): Promise<void> {
return new Promise((resolve, reject) => {
if (!this._supportFullScreen) {
reject(new Error('fullscreen is not supported'));
return;
}
const fullscreenTarget = this._getFullscreenTarget();
if (!fullscreenTarget) {
reject(new Error('Cannot access fullscreen target'));
return;
}
this._onFullscreenChange = undefined;
this._onFullscreenError = undefined;
const requestPromise = fullscreenTarget[this._fn.requestFullscreen]() as Promise<void> | undefined;
if (window.Promise && requestPromise instanceof Promise) {
requestPromise.then(resolve).catch(reject);
} else {
this._onFullscreenChange = resolve;
this._onFullscreenError = reject;
}
});
}
}
export const screenAdapter = new ScreenAdapter();
-3
View File
@@ -44,7 +44,6 @@ class SystemInfo extends EventTarget {
public readonly osMainVersion: number;
public readonly browserType: BrowserType;
public readonly browserVersion: string;
public readonly pixelRatio: number;
private _featureMap: IFeatureMap;
constructor () {
@@ -94,8 +93,6 @@ class SystemInfo extends EventTarget {
this.browserType = BrowserType.UNKNOWN;
this.browserVersion = '';
this.pixelRatio = minigameSysInfo.pixelRatio;
// init capability
const _tmpCanvas1 = document.createElement('canvas'); // TODO: remove this
let supportWebp;
-4
View File
@@ -90,10 +90,6 @@ class SystemInfo extends EventTarget {
this._registerEvent();
}
get pixelRatio () {
return jsb.device.getDevicePixelRatio() || 1;
}
private _registerEvent () {
jsb.onPause = () => {
this.emit('hide');
-4
View File
@@ -184,10 +184,6 @@ class SystemInfo extends EventTarget {
this._registerEvent();
}
get pixelRatio () {
return window.devicePixelRatio || 1;
}
private _registerEvent () {
let hiddenPropName: string;
if (typeof document.hidden !== 'undefined') {
@@ -1,20 +0,0 @@
function adaptContainerStrategy (containerStrategyProto) {
containerStrategyProto._setupContainer = function (view, width, height) {
let locCanvas = cc.game.canvas;
// Setup pixel ratio for retina display
var devicePixelRatio = view._devicePixelRatio = 1;
if (view.isRetinaEnabled())
devicePixelRatio = view._devicePixelRatio = Math.min(view._maxPixelRatio, window.devicePixelRatio || 1);
// Setup canvas
width *= devicePixelRatio;
height *= devicePixelRatio;
// FIX: black screen on Baidu platform
// reset canvas size may call gl.clear(), especially when you call cc.director.loadScene()
if (locCanvas.width !== width || locCanvas.height !== height) {
locCanvas.width = width;
locCanvas.height = height;
}
};
}
module.exports = adaptContainerStrategy;
@@ -1,43 +0,0 @@
function adaptView (viewProto) {
Object.assign(viewProto, {
_adjustViewportMeta () {
// minigame not support
},
setRealPixelResolution (width, height, resolutionPolicy) {
// Reset the resolution size and policy
this.setDesignResolutionSize(width, height, resolutionPolicy);
},
enableAutoFullScreen (enabled) {
cc.warn('cc.view.enableAutoFullScreen() is not supported on minigame platform.');
},
isAutoFullScreenEnabled () {
return false;
},
setCanvasSize () {
cc.warn('cc.view.setCanvasSize() is not supported on minigame platform.');
},
setFrameSize () {
cc.warn('frame size is readonly on minigame platform.');
},
_initFrameSize () {
let locFrameSize = this._frameSize;
if (__globalAdapter.isSubContext) {
let sharedCanvas = window.sharedCanvas || __globalAdapter.getSharedCanvas();
locFrameSize.width = sharedCanvas.width;
locFrameSize.height = sharedCanvas.height;
}
else {
locFrameSize.width = window.innerWidth;
locFrameSize.height = window.innerHeight;
}
},
});
}
module.exports = adaptView;
@@ -1,5 +0,0 @@
window.__globalAdapter = {
adaptView: require('./View'),
adaptContainerStrategy: require('./ContainerStrategy'),
};
@@ -33,6 +33,8 @@ if (cc.internal.VideoPlayer) {
let _topLeft = new vec3();
let _bottomRight = new vec3();
const dpr = wx.getSystemInfoSync().pixelRatio;
cc.internal.VideoPlayerImplManager.getImpl = function(componenet) {
return new VideoPlayerImplMiniGame(componenet);
};
@@ -356,8 +358,6 @@ if (cc.internal.VideoPlayer) {
let canvas_width = cc.game.canvas.width;
let canvas_height = cc.game.canvas.height;
let dpr = cc.view._devicePixelRatio;
let ap = this._uiTrans.anchorPoint;
// Vectors in node space
vec3.set(_topLeft, -ap.x * this._w, (1.0 - ap.y) * this._h, 0);
+1 -1
View File
@@ -161,7 +161,7 @@
let node = this._delegate.node;
let viewScaleX = cc.view._scaleX;
let viewScaleY = cc.view._scaleY;
let dpr = cc.view._devicePixelRatio;
let dpr = jsb.device.getDevicePixelRatio() || 1;
node.getWorldMatrix(worldMat);
let transform = node._uiProps.uiTransformComp;
@@ -33,6 +33,8 @@ if (cc.internal.VideoPlayer) {
let _topLeft = new vec3();
let _bottomRight = new vec3();
const dpr = ral.getSystemInfoSync().pixelRatio;
cc.internal.VideoPlayerImplManager.getImpl = function (componenet) {
return new VideoPlayerImplMiniGame(componenet);
};
@@ -376,8 +378,6 @@ if (cc.internal.VideoPlayer) {
let canvas_width = cc.game.canvas.width;
let canvas_height = cc.game.canvas.height;
let dpr = cc.view._devicePixelRatio;
let ap = this._uiTrans.anchorPoint;
// Vectors in node space
vec3.set(_topLeft, -ap.x * this._w, (1.0 - ap.y) * this._h, 0);
+30 -11
View File
@@ -1,5 +1,5 @@
import { screenAdapter } from 'pal/screen-adapter';
import { Rect, Size, Vec2 } from '../../cocos/core';
import { Rect, screen, Size, sys, Vec2 } from '../../cocos/core';
import { view, ResolutionPolicy } from '../../cocos/core/platform/view';
describe('cc.view', () => {
@@ -12,6 +12,25 @@ describe('cc.view', () => {
const windowSize = screenAdapter.windowSize;
const relatedPos = { left: 0, top: 0, width: windowSize.width, height: windowSize.height };
test('test window interface', () => {
// legacy interface
expect(sys.windowPixelResolution.width).toBe(1024);
expect(sys.windowPixelResolution.height).toBe(768);
expect(view.getCanvasSize()).toEqual(new Size(1024, 768));
expect(view.getDevicePixelRatio()).toBe(1);
// new interface
screen.resolutionScale = 2;
expect(screen.resolutionScale).toBe(2);
expect(screen.windowSize).toEqual(new Size(1024, 768));
expect(screen.resolution).toEqual(new Size(2048, 1536));
screen.resolutionScale = 1;
expect(screen.resolutionScale).toBe(1);
expect(screen.windowSize).toEqual(new Size(1024, 768));
expect(screen.resolution).toEqual(new Size(1024, 768));
});
test('test view SHOW_ALL', () => {
const resolutionPolicy = new ResolutionPolicy(ContainerStrategy.EQUAL_TO_FRAME, ContentStrategy.SHOW_ALL)
view.setDesignResolutionSize(1280, 760, resolutionPolicy);
@@ -29,7 +48,7 @@ describe('cc.view', () => {
expect(tmpVec2).toEqual(new Vec2(10, 778));
tmpVec2.x = tmpX; tmpVec2.y = tmpY;
// @ts-expect-error private method
view._convertPointWithScale(tmpVec2);
view._convertToUISpace(tmpVec2);
expect(tmpVec2).toEqual(new Vec2(12.5, -112.5));
view.setDesignResolutionSize(760, 1280, resolutionPolicy);
@@ -47,7 +66,7 @@ describe('cc.view', () => {
expect(tmpVec2).toEqual(new Vec2(10, 778));
tmpVec2.x = tmpX; tmpVec2.y = tmpY;
// @ts-expect-error private method
view._convertPointWithScale(tmpVec2);
view._convertToUISpace(tmpVec2);
expect(tmpVec2.x).toBeCloseTo(-456.667);
expect(tmpVec2.y).toBeCloseTo(-16.667);
});
@@ -69,7 +88,7 @@ describe('cc.view', () => {
expect(tmpVec2).toEqual(new Vec2(10, 778));
tmpVec2.x = tmpX; tmpVec2.y = tmpY;
// @ts-expect-error private method
view._convertPointWithScale(tmpVec2);
view._convertToUISpace(tmpVec2);
expect(tmpVec2).toEqual(new Vec2(12.5, -12.5));
view.setDesignResolutionSize(760, 1280, resolutionPolicy);
@@ -87,7 +106,7 @@ describe('cc.view', () => {
expect(tmpVec2).toEqual(new Vec2(10, 778));
tmpVec2.x = tmpX; tmpVec2.y = tmpY;
// @ts-expect-error private method
view._convertPointWithScale(tmpVec2);
view._convertToUISpace(tmpVec2);
expect(tmpVec2.x).toBeCloseTo(7.422);
expect(tmpVec2.y).toBeCloseTo(-7.422);
});
@@ -111,7 +130,7 @@ describe('cc.view', () => {
expect(tmpVec2).toEqual(new Vec2(10, 778));
tmpVec2.x = tmpX; tmpVec2.y = tmpY;
// @ts-expect-error private method
view._convertPointWithScale(tmpVec2);
view._convertToUISpace(tmpVec2);
expect(tmpVec2.x).toBeCloseTo(9.896);
expect(tmpVec2.y).toBeCloseTo(-9.896);
@@ -132,7 +151,7 @@ describe('cc.view', () => {
expect(tmpVec2).toEqual(new Vec2(10, 778));
tmpVec2.x = tmpX; tmpVec2.y = tmpY;
// @ts-expect-error private method
view._convertPointWithScale(tmpVec2);
view._convertToUISpace(tmpVec2);
expect(tmpVec2.x).toBeCloseTo(16.667);
expect(tmpVec2.y).toBeCloseTo(-16.667);
});
@@ -158,7 +177,7 @@ describe('cc.view', () => {
expect(tmpVec2).toEqual(new Vec2(10, 778));
tmpVec2.x = tmpX; tmpVec2.y = tmpY;
// @ts-expect-error private method
view._convertPointWithScale(tmpVec2);
view._convertToUISpace(tmpVec2);
expect(tmpVec2.x).toBeCloseTo(143.489);
expect(tmpVec2.y).toBeCloseTo(-9.896);
@@ -181,7 +200,7 @@ describe('cc.view', () => {
expect(tmpVec2).toEqual(new Vec2(10, 778));
tmpVec2.x = tmpX; tmpVec2.y = tmpY;
// @ts-expect-error private method
view._convertPointWithScale(tmpVec2);
view._convertToUISpace(tmpVec2);
expect(tmpVec2.x).toBeCloseTo(7.422);
expect(tmpVec2.y).toBeCloseTo(347.344);
});
@@ -203,7 +222,7 @@ describe('cc.view', () => {
expect(tmpVec2).toEqual(new Vec2(10, 778));
tmpVec2.x = tmpX; tmpVec2.y = tmpY;
// @ts-expect-error private method
view._convertPointWithScale(tmpVec2);
view._convertToUISpace(tmpVec2);
expect(tmpVec2.x).toBe(12.5);
expect(tmpVec2.y).toBeCloseTo(-9.896);
@@ -222,7 +241,7 @@ describe('cc.view', () => {
expect(tmpVec2).toEqual(new Vec2(10, 778));
tmpVec2.x = tmpX; tmpVec2.y = tmpY;
// @ts-expect-error private method
view._convertPointWithScale(tmpVec2);
view._convertToUISpace(tmpVec2);
expect(tmpVec2.x).toBeCloseTo(7.422);
expect(tmpVec2.y).toBeCloseTo(-16.667);
});