Best JavaScript code snippet using wpt
webxr-test.js
Source:webxr-test.js
...978 };979 let submit_frame_sink;980 if (result.supportsSession) {981 submit_frame_sink = {982 clientReceiver: this.presentation_provider_._getClientReceiver(),983 provider: this.presentation_provider_._bindProvider(sessionOptions),984 transportOptions: options985 };986 const dataProviderPtr = new vrMojom.XRFrameDataProviderRemote();987 this.dataProviderReceiver_ =988 new vrMojom.XRFrameDataProviderReceiver(this);989 this.dataProviderReceiver_.$.bindHandle(990 dataProviderPtr.$.bindNewPipeAndPassReceiver().handle);991 this.sessionOptions_ = sessionOptions;992 this.sessionClient_ = new vrMojom.XRSessionClientRemote();993 const clientReceiver = this.sessionClient_.$.bindNewPipeAndPassReceiver();994 const enabled_features = [];995 for (let i = 0; i < sessionOptions.requiredFeatures.length; i++) {996 if (this.supportedFeatures_.indexOf(sessionOptions.requiredFeatures[i]) !== -1) {997 enabled_features.push(sessionOptions.requiredFeatures[i]);998 } else {999 return Promise.resolve({session: null});1000 }1001 }1002 for (let i =0; i < sessionOptions.optionalFeatures.length; i++) {1003 if (this.supportedFeatures_.indexOf(sessionOptions.optionalFeatures[i]) !== -1) {1004 enabled_features.push(sessionOptions.optionalFeatures[i]);1005 }1006 }1007 this.enabledFeatures_ = enabled_features;1008 return Promise.resolve({1009 session: {1010 submitFrameSink: submit_frame_sink,1011 dataProvider: dataProviderPtr,1012 clientReceiver: clientReceiver,1013 displayInfo: this.displayInfo_,1014 enabledFeatures: enabled_features,1015 deviceConfig: {1016 usesInputEventing: false,1017 defaultFramebufferScale: this.defaultFramebufferScale_,1018 supportsViewportScaling: true,1019 depthConfiguration:1020 enabled_features.includes(vrMojom.XRSessionFeature.DEPTH) ? {1021 depthUsage: vrMojom.XRDepthUsage.kCPUOptimized,1022 depthDataFormat: vrMojom.XRDepthDataFormat.kLuminanceAlpha,1023 } : null,1024 },1025 enviromentBlendMode: this.enviromentBlendMode_,1026 interactionMode: this.interactionMode_1027 }1028 });1029 } else {1030 return Promise.resolve({session: null});1031 }1032 });1033 }1034 _runtimeSupportsSession(options) {1035 let result = this.supportedModes_.includes(options.mode);1036 if (options.requiredFeatures.includes(vrMojom.XRSessionFeature.DEPTH)1037 || options.optionalFeatures.includes(vrMojom.XRSessionFeature.DEPTH)) {1038 result &= options.depthOptions.usagePreferences.includes(vrMojom.XRDepthUsage.kCPUOptimized);1039 result &= options.depthOptions.dataFormatPreferences.includes(vrMojom.XRDepthDataFormat.kLuminanceAlpha);1040 }1041 return Promise.resolve({1042 supportsSession: result,1043 });1044 }1045 // Private functions - utilities:1046 _nativeOriginKnown(nativeOriginInformation){1047 if (nativeOriginInformation.inputSourceSpaceInfo !== undefined) {1048 if (!this.input_sources_.has(nativeOriginInformation.inputSourceSpaceInfo.inputSourceId)) {1049 // Unknown input source.1050 return false;1051 }1052 return true;1053 } else if (nativeOriginInformation.referenceSpaceType !== undefined) {1054 // Bounded_floor & unbounded ref spaces are not yet supported for AR:1055 if (nativeOriginInformation.referenceSpaceType == vrMojom.XRReferenceSpaceType.kUnbounded1056 || nativeOriginInformation.referenceSpaceType == vrMojom.XRReferenceSpaceType.kBoundedFloor) {1057 return false;1058 }1059 return true;1060 } else {1061 // Planes and anchors are not yet supported by the mock interface.1062 return false;1063 }1064 }1065 // Private functions - anchors implementation:1066 // Modifies passed in frameData to add anchor information.1067 _calculateAnchorInformation(frameData) {1068 if (!this.supportedModes_.includes(vrMojom.XRSessionMode.kImmersiveAr)) {1069 return;1070 }1071 frameData.anchorsData = {allAnchorsIds: [], updatedAnchorsData: []};1072 for(const [id, controller] of this.anchor_controllers_) {1073 frameData.anchorsData.allAnchorsIds.push(id);1074 // Send the entire anchor data over if there was a change since last GetFrameData().1075 if(controller.dirty) {1076 const anchorData = {id};1077 if(!controller.paused) {1078 anchorData.mojoFromAnchor = getPoseFromTransform(1079 XRMathHelper.decomposeRigidTransform(1080 controller._getAnchorOrigin()));1081 }1082 controller._markProcessed();1083 frameData.anchorsData.updatedAnchorsData.push(anchorData);1084 }1085 }1086 }1087 // Private functions - depth sensing implementation:1088 // Modifies passed in frameData to add anchor information.1089 _calculateDepthInformation(frameData) {1090 if (!this.supportedModes_.includes(vrMojom.XRSessionMode.kImmersiveAr)) {1091 return;1092 }1093 if (!this.enabledFeatures_.includes(vrMojom.XRSessionFeature.DEPTH)) {1094 return;1095 }1096 // If we don't have a current depth data, we'll return null1097 // (i.e. no data is not a valid data, so it cannot be "StillValid").1098 if (this.depthSensingData_ == null) {1099 frameData.depthData = null;1100 return;1101 }1102 if(!this.depthSensingDataDirty_) {1103 frameData.depthData = { dataStillValid: {}};1104 return;1105 }1106 frameData.depthData = {1107 updatedDepthData: {1108 timeDelta: frameData.timeDelta,1109 normTextureFromNormView: this.depthSensingData_.normDepthBufferFromNormView,1110 rawValueToMeters: this.depthSensingData_.rawValueToMeters,1111 size: { width: this.depthSensingData_.width, height: this.depthSensingData_.height },1112 pixelData: { bytes: this.depthSensingData_.depthData }1113 }1114 };1115 this.depthSensingDataDirty_ = false;1116 }1117 // Private functions - hit test implementation:1118 // Returns a Promise<bool> that signifies whether hit test source creation should succeed.1119 // If we have a hit test source creation callback installed, invoke it and return its result.1120 // If it's not installed, for back-compat just return a promise that resolves to true.1121 _shouldHitTestSourceCreationSucceed(hitTestParameters, controller) {1122 if(this.hit_test_source_creation_callback_) {1123 return this.hit_test_source_creation_callback_(hitTestParameters, controller);1124 } else {1125 return Promise.resolve(true);1126 }1127 }1128 // Modifies passed in frameData to add hit test results.1129 _calculateHitTestResults(frameData) {1130 if (!this.supportedModes_.includes(vrMojom.XRSessionMode.kImmersiveAr)) {1131 return;1132 }1133 frameData.hitTestSubscriptionResults = {results: [],1134 transientInputResults: []};1135 if (!this.world_) {1136 return;1137 }1138 // Non-transient hit test:1139 for (const [id, subscription] of this.hitTestSubscriptions_) {1140 const mojo_from_native_origin = this._getMojoFromNativeOrigin(subscription.nativeOriginInformation);1141 if (!mojo_from_native_origin) continue;1142 const [mojo_ray_origin, mojo_ray_direction] = this._transformRayToMojoSpace(1143 subscription.ray,1144 mojo_from_native_origin1145 );1146 const results = this._hitTestWorld(mojo_ray_origin, mojo_ray_direction, subscription.entityTypes);1147 frameData.hitTestSubscriptionResults.results.push(1148 {subscriptionId: id, hitTestResults: results});1149 }1150 // Transient hit test:1151 const mojo_from_viewer = this._getMojoFromViewer();1152 for (const [id, subscription] of this.transientHitTestSubscriptions_) {1153 const result = {subscriptionId: id,1154 inputSourceIdToHitTestResults: new Map()};1155 // Find all input sources that match the profile name:1156 const matching_input_sources = Array.from(this.input_sources_.values())1157 .filter(input_source => input_source.profiles_.includes(subscription.profileName));1158 for (const input_source of matching_input_sources) {1159 const mojo_from_native_origin = input_source._getMojoFromInputSource(mojo_from_viewer);1160 const [mojo_ray_origin, mojo_ray_direction] = this._transformRayToMojoSpace(1161 subscription.ray,1162 mojo_from_native_origin1163 );1164 const results = this._hitTestWorld(mojo_ray_origin, mojo_ray_direction, subscription.entityTypes);1165 result.inputSourceIdToHitTestResults.set(input_source.source_id_, results);1166 }1167 frameData.hitTestSubscriptionResults.transientInputResults.push(result);1168 }1169 }1170 // Returns 2-element array [origin, direction] of a ray in mojo space.1171 // |ray| is expressed relative to native origin.1172 _transformRayToMojoSpace(ray, mojo_from_native_origin) {1173 const ray_origin = {1174 x: ray.origin.x,1175 y: ray.origin.y,1176 z: ray.origin.z,1177 w: 11178 };1179 const ray_direction = {1180 x: ray.direction.x,1181 y: ray.direction.y,1182 z: ray.direction.z,1183 w: 01184 };1185 const mojo_ray_origin = XRMathHelper.transform_by_matrix(1186 mojo_from_native_origin,1187 ray_origin);1188 const mojo_ray_direction = XRMathHelper.transform_by_matrix(1189 mojo_from_native_origin,1190 ray_direction);1191 return [mojo_ray_origin, mojo_ray_direction];1192 }1193 // Hit tests the passed in ray (expressed as origin and direction) against the mocked world data.1194 _hitTestWorld(origin, direction, entityTypes) {1195 let result = [];1196 for (const region of this.world_.hitTestRegions) {1197 const partial_result = this._hitTestRegion(1198 region,1199 origin, direction,1200 entityTypes);1201 result = result.concat(partial_result);1202 }1203 return result.sort((lhs, rhs) => lhs.distance - rhs.distance).map((hitTest) => {1204 delete hitTest.distance;1205 return hitTest;1206 });1207 }1208 // Hit tests the passed in ray (expressed as origin and direction) against world region.1209 // |entityTypes| is a set of FakeXRRegionTypes.1210 // |region| is FakeXRRegion.1211 // Returns array of XRHitResults, each entry will be decorated with the distance from the ray origin (along the ray).1212 _hitTestRegion(region, origin, direction, entityTypes) {1213 const regionNameToMojoEnum = {1214 "point": vrMojom.EntityTypeForHitTest.POINT,1215 "plane": vrMojom.EntityTypeForHitTest.PLANE,1216 "mesh":null1217 };1218 if (!entityTypes.includes(regionNameToMojoEnum[region.type])) {1219 return [];1220 }1221 const result = [];1222 for (const face of region.faces) {1223 const maybe_hit = this._hitTestFace(face, origin, direction);1224 if (maybe_hit) {1225 result.push(maybe_hit);1226 }1227 }1228 // The results should be sorted by distance and there should be no 2 entries with1229 // the same distance from ray origin - that would mean they are the same point.1230 // This situation is possible when a ray intersects the region through an edge shared1231 // by 2 faces.1232 return result.sort((lhs, rhs) => lhs.distance - rhs.distance)1233 .filter((val, index, array) => index === 0 || val.distance !== array[index - 1].distance);1234 }1235 // Hit tests the passed in ray (expressed as origin and direction) against a single face.1236 // |face|, |origin|, and |direction| are specified in world (aka mojo) coordinates.1237 // |face| is an array of DOMPointInits.1238 // Returns null if the face does not intersect with the ray, otherwise the result is1239 // an XRHitResult with matrix describing the pose of the intersection point.1240 _hitTestFace(face, origin, direction) {1241 const add = XRMathHelper.add;1242 const sub = XRMathHelper.sub;1243 const mul = XRMathHelper.mul;1244 const normalize = XRMathHelper.normalize;1245 const dot = XRMathHelper.dot;1246 const cross = XRMathHelper.cross;1247 const neg = XRMathHelper.neg;1248 //1. Calculate plane normal in world coordinates.1249 const point_A = face.vertices[0];1250 const point_B = face.vertices[1];1251 const point_C = face.vertices[2];1252 const edge_AB = sub(point_B, point_A);1253 const edge_AC = sub(point_C, point_A);1254 const normal = normalize(cross(edge_AB, edge_AC));1255 const numerator = dot(sub(point_A, origin), normal);1256 const denominator = dot(direction, normal);1257 if (Math.abs(denominator) < XRMathHelper.EPSILON) {1258 // Planes are nearly parallel - there's either infinitely many intersection points or 0.1259 // Both cases signify a "no hit" for us.1260 return null;1261 } else {1262 // Single intersection point between the infinite plane and the line (*not* ray).1263 // Need to calculate the hit test matrix taking into account the face vertices.1264 const distance = numerator / denominator;1265 if (distance < 0) {1266 // Line - plane intersection exists, but not the half-line - plane does not.1267 return null;1268 } else {1269 const intersection_point = add(origin, mul(distance, direction));1270 // Since we are treating the face as a solid, flip the normal so that its1271 // half-space will contain the ray origin.1272 const y_axis = denominator > 0 ? neg(normal) : normal;1273 let z_axis = null;1274 const cos_direction_and_y_axis = dot(direction, y_axis);1275 if (Math.abs(cos_direction_and_y_axis) > (1 - XRMathHelper.EPSILON)) {1276 // Ray and the hit test normal are co-linear - try using the 'up' or 'right' vector's projection on the face plane as the Z axis.1277 // Note: this edge case is currently not covered by the spec.1278 const up = {x: 0.0, y: 1.0, z: 0.0, w: 0.0};1279 const right = {x: 1.0, y: 0.0, z: 0.0, w: 0.0};1280 z_axis = Math.abs(dot(up, y_axis)) > (1 - XRMathHelper.EPSILON)1281 ? sub(up, mul(dot(right, y_axis), y_axis)) // `up is also co-linear with hit test normal, use `right`1282 : sub(up, mul(dot(up, y_axis), y_axis)); // `up` is not co-linear with hit test normal, use it1283 } else {1284 // Project the ray direction onto the plane, negate it and use as a Z axis.1285 z_axis = neg(sub(direction, mul(cos_direction_and_y_axis, y_axis))); // Z should point towards the ray origin, not away.1286 }1287 z_axis = normalize(z_axis);1288 const x_axis = normalize(cross(y_axis, z_axis));1289 // Filter out the points not in polygon.1290 if (!XRMathHelper.pointInFace(intersection_point, face)) {1291 return null;1292 }1293 const hitResult = {planeId: 0n};1294 hitResult.distance = distance; // Extend the object with additional information used by higher layers.1295 // It will not be serialized over mojom.1296 const matrix = new Array(16);1297 matrix[0] = x_axis.x;1298 matrix[1] = x_axis.y;1299 matrix[2] = x_axis.z;1300 matrix[3] = 0;1301 matrix[4] = y_axis.x;1302 matrix[5] = y_axis.y;1303 matrix[6] = y_axis.z;1304 matrix[7] = 0;1305 matrix[8] = z_axis.x;1306 matrix[9] = z_axis.y;1307 matrix[10] = z_axis.z;1308 matrix[11] = 0;1309 matrix[12] = intersection_point.x;1310 matrix[13] = intersection_point.y;1311 matrix[14] = intersection_point.z;1312 matrix[15] = 1;1313 hitResult.mojoFromResult = getPoseFromTransform(1314 XRMathHelper.decomposeRigidTransform(matrix));1315 return hitResult;1316 }1317 }1318 }1319 _getMojoFromViewer() {1320 if (!this.pose_) {1321 return XRMathHelper.identity();1322 }1323 const transform = {1324 position: [1325 this.pose_.position.x,1326 this.pose_.position.y,1327 this.pose_.position.z],1328 orientation: [1329 this.pose_.orientation.x,1330 this.pose_.orientation.y,1331 this.pose_.orientation.z,1332 this.pose_.orientation.w],1333 };1334 return getMatrixFromTransform(transform);1335 }1336 _getMojoFromViewerWithOffset(viewOffset) {1337 return { matrix: XRMathHelper.mul4x4(this._getMojoFromViewer(), viewOffset.matrix) };1338 }1339 _getMojoFromNativeOrigin(nativeOriginInformation) {1340 const mojo_from_viewer = this._getMojoFromViewer();1341 if (nativeOriginInformation.inputSourceSpaceInfo !== undefined) {1342 if (!this.input_sources_.has(nativeOriginInformation.inputSourceSpaceInfo.inputSourceId)) {1343 return null;1344 } else {1345 const inputSource = this.input_sources_.get(nativeOriginInformation.inputSourceSpaceInfo.inputSourceId);1346 return inputSource._getMojoFromInputSource(mojo_from_viewer);1347 }1348 } else if (nativeOriginInformation.referenceSpaceType !== undefined) {1349 switch (nativeOriginInformation.referenceSpaceType) {1350 case vrMojom.XRReferenceSpaceType.kLocal:1351 return XRMathHelper.identity();1352 case vrMojom.XRReferenceSpaceType.kLocalFloor:1353 if (this.stageParameters_ == null || this.stageParameters_.mojoFromFloor == null) {1354 console.warn("Standing transform not available.");1355 return null;1356 }1357 return this.stageParameters_.mojoFromFloor.matrix;1358 case vrMojom.XRReferenceSpaceType.kViewer:1359 return mojo_from_viewer;1360 case vrMojom.XRReferenceSpaceType.kBoundedFloor:1361 return null;1362 case vrMojom.XRReferenceSpaceType.kUnbounded:1363 return null;1364 default:1365 throw new TypeError("Unrecognized XRReferenceSpaceType!");1366 }1367 } else {1368 // Anchors & planes are not yet supported for hit test.1369 return null;1370 }1371 }1372}1373class MockXRInputSource {1374 constructor(fakeInputSourceInit, id, pairedDevice) {1375 this.source_id_ = id;1376 this.pairedDevice_ = pairedDevice;1377 this.handedness_ = fakeInputSourceInit.handedness;1378 this.target_ray_mode_ = fakeInputSourceInit.targetRayMode;1379 if (fakeInputSourceInit.pointerOrigin == null) {1380 throw new TypeError("FakeXRInputSourceInit.pointerOrigin is required.");1381 }1382 this.setPointerOrigin(fakeInputSourceInit.pointerOrigin);1383 this.setProfiles(fakeInputSourceInit.profiles);1384 this.primary_input_pressed_ = false;1385 if (fakeInputSourceInit.selectionStarted != null) {1386 this.primary_input_pressed_ = fakeInputSourceInit.selectionStarted;1387 }1388 this.primary_input_clicked_ = false;1389 if (fakeInputSourceInit.selectionClicked != null) {1390 this.primary_input_clicked_ = fakeInputSourceInit.selectionClicked;1391 }1392 this.primary_squeeze_pressed_ = false;1393 this.primary_squeeze_clicked_ = false;1394 this.mojo_from_input_ = null;1395 if (fakeInputSourceInit.gripOrigin != null) {1396 this.setGripOrigin(fakeInputSourceInit.gripOrigin);1397 }1398 // This properly handles if supportedButtons were not specified.1399 this.setSupportedButtons(fakeInputSourceInit.supportedButtons);1400 this.emulated_position_ = false;1401 this.desc_dirty_ = true;1402 }1403 // WebXR Test API1404 setHandedness(handedness) {1405 if (this.handedness_ != handedness) {1406 this.desc_dirty_ = true;1407 this.handedness_ = handedness;1408 }1409 }1410 setTargetRayMode(targetRayMode) {1411 if (this.target_ray_mode_ != targetRayMode) {1412 this.desc_dirty_ = true;1413 this.target_ray_mode_ = targetRayMode;1414 }1415 }1416 setProfiles(profiles) {1417 this.desc_dirty_ = true;1418 this.profiles_ = profiles;1419 }1420 setGripOrigin(transform, emulatedPosition = false) {1421 // grip_origin was renamed to mojo_from_input in mojo1422 this.mojo_from_input_ = composeGFXTransform(transform);1423 this.emulated_position_ = emulatedPosition;1424 // Technically, setting the grip shouldn't make the description dirty, but1425 // the webxr-test-api sets our pointer as mojoFromPointer; however, we only1426 // support it across mojom as inputFromPointer, so we need to recalculate it1427 // whenever the grip moves.1428 this.desc_dirty_ = true;1429 }1430 clearGripOrigin() {1431 // grip_origin was renamed to mojo_from_input in mojo1432 if (this.mojo_from_input_ != null) {1433 this.mojo_from_input_ = null;1434 this.emulated_position_ = false;1435 this.desc_dirty_ = true;1436 }1437 }1438 setPointerOrigin(transform, emulatedPosition = false) {1439 // pointer_origin is mojo_from_pointer.1440 this.desc_dirty_ = true;1441 this.mojo_from_pointer_ = composeGFXTransform(transform);1442 this.emulated_position_ = emulatedPosition;1443 }1444 disconnect() {1445 this.pairedDevice_._removeInputSource(this);1446 }1447 reconnect() {1448 this.pairedDevice_._addInputSource(this);1449 }1450 startSelection() {1451 this.primary_input_pressed_ = true;1452 if (this.gamepad_) {1453 this.gamepad_.buttons[0].pressed = true;1454 this.gamepad_.buttons[0].touched = true;1455 }1456 }1457 endSelection() {1458 if (!this.primary_input_pressed_) {1459 throw new Error("Attempted to end selection which was not started");1460 }1461 this.primary_input_pressed_ = false;1462 this.primary_input_clicked_ = true;1463 if (this.gamepad_) {1464 this.gamepad_.buttons[0].pressed = false;1465 this.gamepad_.buttons[0].touched = false;1466 }1467 }1468 simulateSelect() {1469 this.primary_input_clicked_ = true;1470 }1471 setSupportedButtons(supportedButtons) {1472 this.gamepad_ = null;1473 this.supported_buttons_ = [];1474 // If there are no supported buttons, we can stop now.1475 if (supportedButtons == null || supportedButtons.length < 1) {1476 return;1477 }1478 const supported_button_map = {};1479 this.gamepad_ = this._getEmptyGamepad();1480 for (let i = 0; i < supportedButtons.length; i++) {1481 const buttonType = supportedButtons[i].buttonType;1482 this.supported_buttons_.push(buttonType);1483 supported_button_map[buttonType] = supportedButtons[i];1484 }1485 // Let's start by building the button state in order of priority:1486 // Primary button is index 0.1487 this.gamepad_.buttons.push({1488 pressed: this.primary_input_pressed_,1489 touched: this.primary_input_pressed_,1490 value: this.primary_input_pressed_ ? 1.0 : 0.01491 });1492 // Now add the rest of our buttons1493 this._addGamepadButton(supported_button_map['grip']);1494 this._addGamepadButton(supported_button_map['touchpad']);1495 this._addGamepadButton(supported_button_map['thumbstick']);1496 this._addGamepadButton(supported_button_map['optional-button']);1497 this._addGamepadButton(supported_button_map['optional-thumbstick']);1498 // Finally, back-fill placeholder buttons/axes1499 for (let i = 0; i < this.gamepad_.buttons.length; i++) {1500 if (this.gamepad_.buttons[i] == null) {1501 this.gamepad_.buttons[i] = {1502 pressed: false,1503 touched: false,1504 value: 01505 };1506 }1507 }1508 for (let i=0; i < this.gamepad_.axes.length; i++) {1509 if (this.gamepad_.axes[i] == null) {1510 this.gamepad_.axes[i] = 0;1511 }1512 }1513 }1514 updateButtonState(buttonState) {1515 if (this.supported_buttons_.indexOf(buttonState.buttonType) == -1) {1516 throw new Error("Tried to update state on an unsupported button");1517 }1518 const buttonIndex = this._getButtonIndex(buttonState.buttonType);1519 const axesStartIndex = this._getAxesStartIndex(buttonState.buttonType);1520 if (buttonIndex == -1) {1521 throw new Error("Unknown Button Type!");1522 }1523 // is this a 'squeeze' button?1524 if (buttonIndex === this._getButtonIndex('grip')) {1525 // squeeze1526 if (buttonState.pressed) {1527 this.primary_squeeze_pressed_ = true;1528 } else if (this.gamepad_.buttons[buttonIndex].pressed) {1529 this.primary_squeeze_clicked_ = true;1530 this.primary_squeeze_pressed_ = false;1531 } else {1532 this.primary_squeeze_clicked_ = false;1533 this.primary_squeeze_pressed_ = false;1534 }1535 }1536 this.gamepad_.buttons[buttonIndex].pressed = buttonState.pressed;1537 this.gamepad_.buttons[buttonIndex].touched = buttonState.touched;1538 this.gamepad_.buttons[buttonIndex].value = buttonState.pressedValue;1539 if (axesStartIndex != -1) {1540 this.gamepad_.axes[axesStartIndex] = buttonState.xValue == null ? 0.0 : buttonState.xValue;1541 this.gamepad_.axes[axesStartIndex + 1] = buttonState.yValue == null ? 0.0 : buttonState.yValue;1542 }1543 }1544 // DOM Overlay Extensions1545 setOverlayPointerPosition(x, y) {1546 this.overlay_pointer_position_ = {x: x, y: y};1547 }1548 // Helpers for Mojom1549 _getInputSourceState() {1550 const input_state = {};1551 input_state.sourceId = this.source_id_;1552 input_state.isAuxiliary = false;1553 input_state.primaryInputPressed = this.primary_input_pressed_;1554 input_state.primaryInputClicked = this.primary_input_clicked_;1555 input_state.primarySqueezePressed = this.primary_squeeze_pressed_;1556 input_state.primarySqueezeClicked = this.primary_squeeze_clicked_;1557 // Setting the input source's "clicked" state should generate one "select"1558 // event. Reset the input value to prevent it from continuously generating1559 // events.1560 this.primary_input_clicked_ = false;1561 // Setting the input source's "clicked" state should generate one "squeeze"1562 // event. Reset the input value to prevent it from continuously generating1563 // events.1564 this.primary_squeeze_clicked_ = false;1565 input_state.mojoFromInput = this.mojo_from_input_;1566 input_state.gamepad = this.gamepad_;1567 input_state.emulatedPosition = this.emulated_position_;1568 if (this.desc_dirty_) {1569 const input_desc = {};1570 switch (this.target_ray_mode_) {1571 case 'gaze':1572 input_desc.targetRayMode = vrMojom.XRTargetRayMode.GAZING;1573 break;1574 case 'tracked-pointer':1575 input_desc.targetRayMode = vrMojom.XRTargetRayMode.POINTING;1576 break;1577 case 'screen':1578 input_desc.targetRayMode = vrMojom.XRTargetRayMode.TAPPING;1579 break;1580 default:1581 throw new Error('Unhandled target ray mode ' + this.target_ray_mode_);1582 }1583 switch (this.handedness_) {1584 case 'left':1585 input_desc.handedness = vrMojom.XRHandedness.LEFT;1586 break;1587 case 'right':1588 input_desc.handedness = vrMojom.XRHandedness.RIGHT;1589 break;1590 default:1591 input_desc.handedness = vrMojom.XRHandedness.NONE;1592 break;1593 }1594 // Mojo requires us to send the pointerOrigin as relative to the grip1595 // space. If we don't have a grip space, we'll just assume that there1596 // is a grip at identity. This allows tests to simulate controllers that1597 // are really just a pointer with no tracked grip, though we will end up1598 // exposing that grip space.1599 let mojo_from_input = XRMathHelper.identity();1600 switch (this.target_ray_mode_) {1601 case 'gaze':1602 case 'screen':1603 // For gaze and screen space, we won't have a mojo_from_input; however1604 // the "input" position is just the viewer, so use mojo_from_viewer.1605 mojo_from_input = this.pairedDevice_._getMojoFromViewer();1606 break;1607 case 'tracked-pointer':1608 // If we have a tracked grip position (e.g. mojo_from_input), then use1609 // that. If we don't, then we'll just set the pointer offset directly,1610 // using identity as set above.1611 if (this.mojo_from_input_) {1612 mojo_from_input = this.mojo_from_input_.matrix;1613 }1614 break;1615 default:1616 throw new Error('Unhandled target ray mode ' + this.target_ray_mode_);1617 }1618 // To convert mojo_from_pointer to input_from_pointer, we need:1619 // input_from_pointer = input_from_mojo * mojo_from_pointer1620 // Since we store mojo_from_input, we need to invert it here before1621 // multiplying.1622 let input_from_mojo = XRMathHelper.inverse(mojo_from_input);1623 input_desc.inputFromPointer = {};1624 input_desc.inputFromPointer.matrix =1625 XRMathHelper.mul4x4(input_from_mojo, this.mojo_from_pointer_.matrix);1626 input_desc.profiles = this.profiles_;1627 input_state.description = input_desc;1628 this.desc_dirty_ = false;1629 }1630 // Pointer data for DOM Overlay, set by setOverlayPointerPosition()1631 if (this.overlay_pointer_position_) {1632 input_state.overlayPointerPosition = this.overlay_pointer_position_;1633 this.overlay_pointer_position_ = null;1634 }1635 return input_state;1636 }1637 _getEmptyGamepad() {1638 // Mojo complains if some of the properties on Gamepad are null, so set1639 // everything to reasonable defaults that tests can override.1640 const gamepad = {1641 connected: true,1642 id: [],1643 timestamp: 0n,1644 axes: [],1645 buttons: [],1646 mapping: GamepadMapping.GamepadMappingStandard,1647 displayId: 0,1648 };1649 switch (this.handedness_) {1650 case 'left':1651 gamepad.hand = GamepadHand.GamepadHandLeft;1652 break;1653 case 'right':1654 gamepad.hand = GamepadHand.GamepadHandRight;1655 break;1656 default:1657 gamepad.hand = GamepadHand.GamepadHandNone;1658 break;1659 }1660 return gamepad;1661 }1662 _addGamepadButton(buttonState) {1663 if (buttonState == null) {1664 return;1665 }1666 const buttonIndex = this._getButtonIndex(buttonState.buttonType);1667 const axesStartIndex = this._getAxesStartIndex(buttonState.buttonType);1668 if (buttonIndex == -1) {1669 throw new Error("Unknown Button Type!");1670 }1671 this.gamepad_.buttons[buttonIndex] = {1672 pressed: buttonState.pressed,1673 touched: buttonState.touched,1674 value: buttonState.pressedValue1675 };1676 // Add x/y value if supported.1677 if (axesStartIndex != -1) {1678 this.gamepad_.axes[axesStartIndex] = (buttonState.xValue == null ? 0.0 : buttonSate.xValue);1679 this.gamepad_.axes[axesStartIndex + 1] = (buttonState.yValue == null ? 0.0 : buttonSate.yValue);1680 }1681 }1682 // General Helper methods1683 _getButtonIndex(buttonType) {1684 switch (buttonType) {1685 case 'grip':1686 return 1;1687 case 'touchpad':1688 return 2;1689 case 'thumbstick':1690 return 3;1691 case 'optional-button':1692 return 4;1693 case 'optional-thumbstick':1694 return 5;1695 default:1696 return -1;1697 }1698 }1699 _getAxesStartIndex(buttonType) {1700 switch (buttonType) {1701 case 'touchpad':1702 return 0;1703 case 'thumbstick':1704 return 2;1705 case 'optional-thumbstick':1706 return 4;1707 default:1708 return -1;1709 }1710 }1711 _getMojoFromInputSource(mojo_from_viewer) {1712 return this.mojo_from_pointer_.matrix;1713 }1714}1715// Mojo helper classes1716class FakeXRHitTestSourceController {1717 constructor(id) {1718 this.id_ = id;1719 this.deleted_ = false;1720 }1721 get deleted() {1722 return this.deleted_;1723 }1724 // Internal setter:1725 set deleted(value) {1726 this.deleted_ = value;1727 }1728}1729class MockXRPresentationProvider {1730 constructor() {1731 this.receiver_ = null;1732 this.submit_frame_count_ = 0;1733 this.missing_frame_count_ = 0;1734 }1735 _bindProvider() {1736 const provider = new vrMojom.XRPresentationProviderRemote();1737 if (this.receiver_) {1738 this.receiver_.$.close();1739 }1740 this.receiver_ = new vrMojom.XRPresentationProviderReceiver(this);1741 this.receiver_.$.bindHandle(provider.$.bindNewPipeAndPassReceiver().handle);1742 return provider;1743 }1744 _getClientReceiver() {1745 this.submitFrameClient_ = new vrMojom.XRPresentationClientRemote();1746 return this.submitFrameClient_.$.bindNewPipeAndPassReceiver();1747 }1748 // XRPresentationProvider mojo implementation1749 updateLayerBounds(frameId, leftBounds, rightBounds, sourceSize) {}1750 submitFrameMissing(frameId, mailboxHolder, timeWaited) {1751 this.missing_frame_count_++;1752 }1753 submitFrame(frameId, mailboxHolder, timeWaited) {1754 this.submit_frame_count_++;1755 // Trigger the submit completion callbacks here. WARNING: The1756 // Javascript-based mojo mocks are *not* re-entrant. It's OK to1757 // wait for these notifications on the next frame, but waiting1758 // within the current frame would never finish since the incoming...
Using AI Code Generation
1var wptools = require('wptools');2var wp = new wptools('Albert Einstein');3wp._getClientReceiver(function(err, client, receiver) {4 if (err) {5 console.log(err);6 } else {7 console.log(client);8 console.log(receiver);9 }10});11var wptools = require('wptools');12var wp = new wptools('Albert Einstein');13wp._getClientReceiver(function(err, client, receiver) {14 if (err) {15 console.log(err);16 } else {17 console.log(client);18 console.log(receiver);19 }20});21var wptools = require('wptools');22var wp = new wptools('Albert Einstein');23wp._getClientReceiver(function(err, client, receiver) {24 if (err) {25 console.log(err);26 } else {27 console.log(client);28 console.log(receiver);29 }30});31var wptools = require('wptools');32var wp = new wptools('Albert Einstein');33wp._getClientReceiver(function(err, client, receiver) {34 if (err) {35 console.log(err);36 } else {37 console.log(client);38 console.log(receiver);39 }40});41var wptools = require('wptools');42var wp = new wptools('Albert Einstein');43wp._getClientReceiver(function(err, client, receiver) {44 if (err) {45 console.log(err);46 } else {47 console.log(client);48 console.log(receiver);49 }50});51var wptools = require('wptools');52var wp = new wptools('Albert Einstein');53wp._getClientReceiver(function(err, client, receiver) {54 if (err) {55 console.log(err);56 } else {57 console.log(client);58 console.log(receiver);59 }60});61var wptools = require('wptools');
Using AI Code Generation
1var wptools = require('./wptools.js');2wptools._getClientReceiver(function (err, client, receiver) {3 console.log("client: " + client);4 console.log("receiver: " + receiver);5});6var util = require('util');7var events = require('events');8function WPTools() {9 events.EventEmitter.call(this);10}11util.inherits(WPTools, events.EventEmitter);12WPTools.prototype._getClientReceiver = function(callback) {13 var client = "client";14 var receiver = "receiver";15 callback(null, client, receiver);16};17module.exports = new WPTools();18function WPTools() {19 events.EventEmitter.call(this);20 this._getClientReceiver = function(callback) {21 var client = "client";22 var receiver = "receiver";23 callback(null, client, receiver);24 };25}26util.inherits(WPTools, events.EventEmitter);27TypeError: Object function WPTools() {28 events.EventEmitter.call(this);29 this._getClientReceiver = function(callback) {30 var client = "client";31 var receiver = "receiver";32 callback(null, client, receiver);33 };34} has no method 'on'
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3console.log(clientReceiver);4var wpt = require('webpagetest');5var wpt = new WebPageTest('www.webpagetest.org');6console.log(clientReceiver);7{ ip: '
Using AI Code Generation
1var wpt = require('./wpt.js');2var wptClient = wpt._getClientReceiver('test', 'test');3console.log(wptClient);4module.exports = {5 _getClientReceiver: function (username, password) {6 return new ClientReceiver(username, password);7 }8}
Using AI Code Generation
1var wptools = require('wptools');2var wp = new wptools('Barack Obama');3wp._getClientReceiver(function(err, response) {4 console.log(response);5});6{ batchcomplete: '',7 { normalized: [ { from: 'Barack Obama', to: 'Barack Obama' } ],8 { '271786': 9 { pageid: 271786,10 revisions: [ [Object] ] } } } }
Using AI Code Generation
1var wptools = require('wptools');2var page = wptools.page('Barack_Obama');3page.get(function(err, infobox) {4 if (err) {5 console.log(err);6 }7 else {8 console.log(infobox);9 }10});11var wptools = require('wptools');12var page = wptools.page('Barack_Obama');13page._getClientReceiver(function(err, receiver) {14 if (err) {15 console.log(err);16 }17 else {18 console.log(receiver);19 }20});21var wptools = require('wptools');22var page = wptools.page('Barack_Obama');23page._getClientReceiver(function(err, receiver) {24 if (err) {25 console.log(err);26 }27 else {28 receiver.on('data', function(data) {29 console.log(data);30 });31 }32});33var wptools = require('wptools');34var page = wptools.page('Barack_Obama');35page._getClientReceiver(function(err, receiver) {36 if (err) {37 console.log(err);38 }39 else {40 receiver.on('data', function(data) {41 console.log(data);42 });43 receiver.on('end', function() {44 console.log('Done!');45 });46 }47});48var wptools = require('wptools');49var page = wptools.page('Barack_Obama');50page._getClientReceiver(function(err, receiver) {51 if (err) {52 console.log(err);53 }54 else {55 receiver.on('data', function(data) {56 console.log(data);57 });58 receiver.on('end', function() {59 console.log('Done!');60 });61 receiver.on('error', function(err) {62 console.log('Error: ' + err);63 });64 }65});
Using AI Code Generation
1function test1() {2 var clientReceiver = _getClientReceiver();3 clientReceiver.testMethod();4}5var ClientReceiver = {6 testMethod: function() {7 alert('testMethod called');8 }9};10function _getClientReceiver() {11 return ClientReceiver;12}13The _getClientReceiver() method of the wptoolkit.js file is defined as follows:14function _getClientReceiver() {15 return ClientReceiver;16}17var clientReceiver = _getClientReceiver();18clientReceiver.testMethod();19var ClientReceiver = {20 testMethod: function() {21 alert('testMethod called');22 }23};24The _getClientReceiver() method of the wptoolkit.js file is defined as follows:25function _getClientReceiver() {26 return ClientReceiver;27}28var clientReceiver = _getClientReceiver();29clientReceiver.testMethod();30var ClientReceiver = {31 testMethod: function() {32 alert('testMethod called');33 }34};35The testMethod() method of the ClientReceiver
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!