diff --git a/examples/users.js b/examples/users.js index f6406efe60..d6ebe86d4e 100644 --- a/examples/users.js +++ b/examples/users.js @@ -9,54 +9,258 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +var PopUpMenu = function (properties) { + var value = properties.value, + promptOverlay, + valueOverlay, + buttonOverlay, + optionOverlays = [], + isDisplayingOptions = false, + OPTION_MARGIN = 4, + HIFI_PUBLIC_BUCKET = "http://s3.amazonaws.com/hifi-public/", + MIN_MAX_BUTTON_SVG = HIFI_PUBLIC_BUCKET + "images/tools/min-max-toggle.svg", + MIN_MAX_BUTTON_SVG_WIDTH = 17.1, + MIN_MAX_BUTTON_SVG_HEIGHT = 32.5, + MIN_MAX_BUTTON_WIDTH = 14, + MIN_MAX_BUTTON_HEIGHT = MIN_MAX_BUTTON_WIDTH; + + function positionDisplayOptions() { + var y, + i; + + y = properties.y - (properties.values.length - 1) * properties.lineHeight - OPTION_MARGIN; + + for (i = 0; i < properties.values.length; i += 1) { + Overlays.editOverlay(optionOverlays[i], { y: y }); + y += properties.lineHeight; + } + } + + function showDisplayOptions() { + var i, + yOffScreen = Controller.getViewportDimensions().y; + + for (i = 0; i < properties.values.length; i += 1) { + optionOverlays[i] = Overlays.addOverlay("text", { + x: properties.x + properties.promptWidth, + y: yOffScreen, + width: properties.width - properties.promptWidth, + height: properties.textHeight + OPTION_MARGIN, // Only need to add margin at top to balance descenders + topMargin: OPTION_MARGIN, + leftMargin: OPTION_MARGIN, + color: properties.optionColor, + alpha: properties.optionAlpha, + backgroundColor: properties.popupBackgroundColor, + backgroundAlpha: properties.popupBackgroundAlpha, + text: properties.displayValues[i], + font: properties.font, + visible: true + }); + } + + positionDisplayOptions(); + + isDisplayingOptions = true; + } + + function deleteDisplayOptions() { + var i; + + for (i = 0; i < optionOverlays.length; i += 1) { + Overlays.deleteOverlay(optionOverlays[i]); + } + + isDisplayingOptions = false; + } + + function handleClick(overlay) { + var clicked = false, + i; + + if (overlay === valueOverlay || overlay === buttonOverlay) { + showDisplayOptions(); + return true; + } + + if (isDisplayingOptions) { + for (i = 0; i < optionOverlays.length; i += 1) { + if (overlay === optionOverlays[i]) { + value = properties.values[i]; + Overlays.editOverlay(valueOverlay, { text: properties.displayValues[i] }); + clicked = true; + } + } + + deleteDisplayOptions(); + } + + return clicked; + } + + function updatePosition(x, y) { + properties.x = x; + properties.y = y; + Overlays.editOverlay(promptOverlay, { x: x, y: y }); + Overlays.editOverlay(valueOverlay, { x: x + properties.promptWidth, y: y - OPTION_MARGIN }); + Overlays.editOverlay(buttonOverlay, + { x: x + properties.width - MIN_MAX_BUTTON_WIDTH - 1, y: y - OPTION_MARGIN + 1 }); + if (isDisplayingOptions) { + positionDisplayOptions(); + } + } + + function setVisible(visible) { + Overlays.editOverlay(promptOverlay, { visible: visible }); + Overlays.editOverlay(valueOverlay, { visible: visible }); + Overlays.editOverlay(buttonOverlay, { visible: visible }); + } + + function tearDown() { + Overlays.deleteOverlay(promptOverlay); + Overlays.deleteOverlay(valueOverlay); + Overlays.deleteOverlay(buttonOverlay); + if (isDisplayingOptions) { + deleteDisplayOptions(); + } + } + + function getValue() { + return value; + } + + function setValue(newValue) { + var index; + + index = properties.values.indexOf(newValue); + if (index !== -1) { + value = newValue; + Overlays.editOverlay(valueOverlay, { text: properties.displayValues[index] }); + } + } + + promptOverlay = Overlays.addOverlay("text", { + x: properties.x, + y: properties.y, + width: properties.promptWidth, + height: properties.textHeight, + topMargin: 0, + leftMargin: 0, + color: properties.promptColor, + alpha: properties.promptAlpha, + backgroundColor: properties.promptBackgroundColor, + backgroundAlpha: properties.promptBackgroundAlpha, + text: properties.prompt, + font: properties.font, + visible: properties.visible + }); + + valueOverlay = Overlays.addOverlay("text", { + x: properties.x + properties.promptWidth, + y: properties.y, + width: properties.width - properties.promptWidth, + height: properties.textHeight + OPTION_MARGIN, // Only need to add margin at top to balance descenders + topMargin: OPTION_MARGIN, + leftMargin: OPTION_MARGIN, + color: properties.optionColor, + alpha: properties.optionAlpha, + backgroundColor: properties.optionBackgroundColor, + backgroundAlpha: properties.optionBackgroundAlpha, + text: properties.displayValues[properties.values.indexOf(value)], + font: properties.font, + visible: properties.visible + }); + + buttonOverlay = Overlays.addOverlay("image", { + x: properties.x + properties.width - MIN_MAX_BUTTON_WIDTH - 1, + y: properties.y, + width: MIN_MAX_BUTTON_WIDTH, + height: MIN_MAX_BUTTON_HEIGHT, + imageURL: MIN_MAX_BUTTON_SVG, + subImage: { x: 0, y: 0, width: MIN_MAX_BUTTON_SVG_WIDTH, height: MIN_MAX_BUTTON_SVG_HEIGHT / 2 }, + color: properties.buttonColor, + alpha: properties.buttonAlpha, + visible: properties.visible + }); + + return { + updatePosition: updatePosition, + setVisible: setVisible, + handleClick: handleClick, + tearDown: tearDown, + getValue: getValue, + setValue: setValue + }; +}; + var usersWindow = (function () { var HIFI_PUBLIC_BUCKET = "http://s3.amazonaws.com/hifi-public/", - WINDOW_WIDTH_2D = 160, - WINDOW_MARGIN_2D = 12, - WINDOW_BASE_MARGIN_2D = 6, // A little less is needed in order look correct - WINDOW_FONT_2D = { size: 12 }, - WINDOW_FOREGROUND_COLOR_2D = { red: 240, green: 240, blue: 240 }, - WINDOW_FOREGROUND_ALPHA_2D = 0.9, - WINDOW_HEADING_COLOR_2D = { red: 180, green: 180, blue: 180 }, - WINDOW_HEADING_ALPHA_2D = 0.9, - WINDOW_BACKGROUND_COLOR_2D = { red: 80, green: 80, blue: 80 }, - WINDOW_BACKGROUND_ALPHA_2D = 0.7, - windowPane2D, - windowHeading2D, - MINIMIZE_BUTTON_SVG = HIFI_PUBLIC_BUCKET + "images/tools/min-max-toggle.svg", - MINIMIZE_BUTTON_SVG_WIDTH = 17.1, - MINIMIZE_BUTTON_SVG_HEIGHT = 32.5, - MINIMIZE_BUTTON_WIDTH_2D = 14, - MINIMIZE_BUTTON_HEIGHT_2D = MINIMIZE_BUTTON_WIDTH_2D, - MINIMIZE_BUTTON_COLOR_2D = { red: 255, green: 255, blue: 255 }, - MINIMIZE_BUTTON_ALPHA_2D = 0.9, - minimizeButton2D, - SCROLLBAR_BACKGROUND_WIDTH_2D = 12, - SCROLLBAR_BACKGROUND_COLOR_2D = { red: 80, green: 80, blue: 80 }, - SCROLLBAR_BACKGROUND_ALPHA_2D = 0.8, - scrollbarBackground2D, + WINDOW_WIDTH = 160, + WINDOW_MARGIN = 12, + WINDOW_BASE_MARGIN = 6, // A little less is needed in order look correct + WINDOW_FONT = { size: 12 }, + WINDOW_FOREGROUND_COLOR = { red: 240, green: 240, blue: 240 }, + WINDOW_FOREGROUND_ALPHA = 0.9, + WINDOW_HEADING_COLOR = { red: 180, green: 180, blue: 180 }, + WINDOW_HEADING_ALPHA = 0.9, + WINDOW_BACKGROUND_COLOR = { red: 80, green: 80, blue: 80 }, + WINDOW_BACKGROUND_ALPHA = 0.7, + windowPane, + windowHeading, + MIN_MAX_BUTTON_SVG = HIFI_PUBLIC_BUCKET + "images/tools/min-max-toggle.svg", + MIN_MAX_BUTTON_SVG_WIDTH = 17.1, + MIN_MAX_BUTTON_SVG_HEIGHT = 32.5, + MIN_MAX_BUTTON_WIDTH = 14, + MIN_MAX_BUTTON_HEIGHT = MIN_MAX_BUTTON_WIDTH, + MIN_MAX_BUTTON_COLOR = { red: 255, green: 255, blue: 255 }, + MIN_MAX_BUTTON_ALPHA = 0.9, + minimizeButton, + SCROLLBAR_BACKGROUND_WIDTH = 12, + SCROLLBAR_BACKGROUND_COLOR = { red: 70, green: 70, blue: 70 }, + SCROLLBAR_BACKGROUND_ALPHA = 0.8, + scrollbarBackground, SCROLLBAR_BAR_MIN_HEIGHT = 5, - SCROLLBAR_BAR_COLOR_2D = { red: 180, green: 180, blue: 180 }, - SCROLLBAR_BAR_ALPHA_2D = 0.8, - SCROLLBAR_BAR_SELECTED_ALPHA_2D = 0.9, - scrollbarBar2D, + SCROLLBAR_BAR_COLOR = { red: 170, green: 170, blue: 170 }, + SCROLLBAR_BAR_ALPHA = 0.8, + SCROLLBAR_BAR_SELECTED_ALPHA = 0.9, + scrollbarBar, scrollbarBackgroundHeight, scrollbarBarHeight, - FRIENDS_BUTTON_SPACER_2D = 12, // Space before add/remove friends button + FRIENDS_BUTTON_SPACER = 6, // Space before add/remove friends button FRIENDS_BUTTON_SVG = HIFI_PUBLIC_BUCKET + "images/tools/add-remove-friends.svg", FRIENDS_BUTTON_SVG_WIDTH = 107, FRIENDS_BUTTON_SVG_HEIGHT = 27, - FRIENDS_BUTTON_WIDTH_2D = FRIENDS_BUTTON_SVG_WIDTH, - FRIENDS_BUTTON_HEIGHT_2D = FRIENDS_BUTTON_SVG_HEIGHT, - FRIENDS_BUTTON_COLOR_2D = { red: 255, green: 255, blue: 255 }, - FRIENDS_BUTTON_ALPHA_2D = 0.9, - friendsButton2D, - VISIBILITY_SPACER_2D = 12, // Space between before visibility controls - visibilityHeading2D, - VISIBILITY_RADIO_SPACE = 16, - visibilityControls2D, + FRIENDS_BUTTON_WIDTH = FRIENDS_BUTTON_SVG_WIDTH, + FRIENDS_BUTTON_HEIGHT = FRIENDS_BUTTON_SVG_HEIGHT, + FRIENDS_BUTTON_COLOR = { red: 255, green: 255, blue: 255 }, + FRIENDS_BUTTON_ALPHA = 0.9, + friendsButton, + + OPTION_BACKGROUND_COLOR = { red: 60, green: 60, blue: 60 }, + OPTION_BACKGROUND_ALPHA = 0.8, + + DISPLAY_SPACER = 12, // Space before display control + DISPLAY_PROMPT = "Show me:", + DISPLAY_PROMPT_WIDTH = 60, + DISPLAY_EVERYONE = "everyone", + DISPLAY_FRIENDS = "friends", + DISPLAY_VALUES = [DISPLAY_EVERYONE, DISPLAY_FRIENDS], + DISPLAY_DISPLAY_VALUES = DISPLAY_VALUES, + DISPLAY_OPTIONS_BACKGROUND_COLOR = { red: 40, green: 40, blue: 40 }, + DISPLAY_OPTIONS_BACKGROUND_ALPHA = 0.95, + displayControl, + + VISIBILITY_SPACER = 6, // Space before visibility control + VISIBILITY_PROMPT = "Visible to:", + VISIBILITY_PROMPT_WIDTH = 60, + VISIBILITY_ALL = "all", + VISIBILITY_FRIENDS = "friends", + VISIBILITY_NONE = "none", + VISIBILITY_VALUES = [VISIBILITY_ALL, VISIBILITY_FRIENDS, VISIBILITY_NONE], + VISIBILITY_DISPLAY_VALUES = ["everyone", "friends", "no one"], + visibilityControl, + windowHeight, windowTextHeight, windowLineSpacing, @@ -68,6 +272,7 @@ var usersWindow = (function () { firstUserToDisplay = 0, API_URL = "https://metaverse.highfidelity.com/api/v1/users?status=online", + API_FRIENDS_FILTER = "&filter=friends", HTTP_GET_TIMEOUT = 60000, // ms = 1 minute usersRequest, processUsers, @@ -76,7 +281,6 @@ var usersWindow = (function () { USERS_UPDATE_TIMEOUT = 5000, // ms = 5s myVisibility, - VISIBILITY_VALUES = ["all", "friends", "none"], MENU_NAME = "Tools", MENU_ITEM = "Users Online", @@ -94,12 +298,7 @@ var usersWindow = (function () { scrollbarBackgroundPosition = {}, scrollbarBarPosition = {}, scrollbarBarClickedAt, // 0.0 .. 1.0 - scrollbarValue = 0.0, // 0.0 .. 1.0 - - RADIO_BUTTON_SVG = HIFI_PUBLIC_BUCKET + "images/radio-button.svg", - RADIO_BUTTON_SVG_DIAMETER = 14, - RADIO_BUTTON_DISPLAY_SCALE = 0.7, // 1.0 = windowTextHeight - radioButtonDiameter; + scrollbarValue = 0.0; // 0.0 .. 1.0 function calculateWindowHeight() { var AUDIO_METER_HEIGHT = 52, @@ -108,18 +307,18 @@ var usersWindow = (function () { maxWindowHeight; if (isMinimized) { - windowHeight = windowTextHeight + WINDOW_MARGIN_2D + WINDOW_BASE_MARGIN_2D; + windowHeight = windowTextHeight + WINDOW_MARGIN + WINDOW_BASE_MARGIN; return; } - // Reserve 5 lines for window heading plus visibility heading and controls - // Subtract windowLineSpacing for both end of user list and end of controls - nonUsersHeight = 5 * windowLineHeight - 2 * windowLineSpacing - + FRIENDS_BUTTON_SPACER_2D + FRIENDS_BUTTON_HEIGHT_2D - + VISIBILITY_SPACER_2D + WINDOW_MARGIN_2D + WINDOW_BASE_MARGIN_2D; + // Reserve space for title, friends button, and option controls + nonUsersHeight = WINDOW_MARGIN + windowLineHeight + + FRIENDS_BUTTON_SPACER + FRIENDS_BUTTON_HEIGHT + + DISPLAY_SPACER + windowLineHeight + + VISIBILITY_SPACER + windowLineHeight + WINDOW_BASE_MARGIN; // Limit window to height of viewport minus VU meter and mirror if displayed - windowHeight = linesOfUsers.length * windowLineHeight - windowLineSpacing + nonUsersHeight; // DJRTODO: - windowLineSpacing or not? + windowHeight = linesOfUsers.length * windowLineHeight - windowLineSpacing + nonUsersHeight; maxWindowHeight = viewportHeight - AUDIO_METER_HEIGHT; if (isMirrorDisplay && !isFullscreenMirror) { maxWindowHeight -= MIRROR_HEIGHT; @@ -127,7 +326,7 @@ var usersWindow = (function () { windowHeight = Math.max(Math.min(windowHeight, maxWindowHeight), nonUsersHeight); // Corresponding number of users to actually display - numUsersToDisplay = Math.max(Math.round((windowHeight - nonUsersHeight) / windowLineHeight), 0); // DJRTODO: .floor or .round? + numUsersToDisplay = Math.max(Math.round((windowHeight - nonUsersHeight) / windowLineHeight), 0); isUsingScrollbars = 0 < numUsersToDisplay && numUsersToDisplay < linesOfUsers.length; if (isUsingScrollbars) { firstUserToDisplay = Math.floor(scrollbarValue * (linesOfUsers.length - numUsersToDisplay)); @@ -138,57 +337,39 @@ var usersWindow = (function () { } function updateOverlayPositions() { - var i, - y; + var y; - Overlays.editOverlay(windowPane2D, { + Overlays.editOverlay(windowPane, { y: viewportHeight - windowHeight }); - Overlays.editOverlay(windowHeading2D, { - y: viewportHeight - windowHeight + WINDOW_MARGIN_2D + Overlays.editOverlay(windowHeading, { + y: viewportHeight - windowHeight + WINDOW_MARGIN }); - Overlays.editOverlay(minimizeButton2D, { - y: viewportHeight - windowHeight + WINDOW_MARGIN_2D / 2 + Overlays.editOverlay(minimizeButton, { + y: viewportHeight - windowHeight + WINDOW_MARGIN / 2 }); - scrollbarBackgroundPosition.y = viewportHeight - windowHeight + WINDOW_MARGIN_2D + windowTextHeight; - Overlays.editOverlay(scrollbarBackground2D, { + scrollbarBackgroundPosition.y = viewportHeight - windowHeight + WINDOW_MARGIN + windowTextHeight; + Overlays.editOverlay(scrollbarBackground, { y: scrollbarBackgroundPosition.y }); scrollbarBarPosition.y = scrollbarBackgroundPosition.y + 1 + scrollbarValue * (scrollbarBackgroundHeight - scrollbarBarHeight - 2); - Overlays.editOverlay(scrollbarBar2D, { + Overlays.editOverlay(scrollbarBar, { y: scrollbarBarPosition.y }); - Overlays.editOverlay(friendsButton2D, { - y: viewportHeight - FRIENDS_BUTTON_HEIGHT_2D - VISIBILITY_SPACER_2D - - 4 * windowLineHeight + windowLineSpacing - WINDOW_BASE_MARGIN_2D - }); + y = viewportHeight - FRIENDS_BUTTON_HEIGHT + - DISPLAY_SPACER - windowLineHeight + - VISIBILITY_SPACER - windowLineHeight - WINDOW_BASE_MARGIN; + Overlays.editOverlay(friendsButton, { y: y }); - Overlays.editOverlay(visibilityHeading2D, { - y: viewportHeight - 4 * windowLineHeight + windowLineSpacing - WINDOW_BASE_MARGIN_2D - }); - for (i = 0; i < visibilityControls2D.length; i += 1) { - y = viewportHeight - (3 - i) * windowLineHeight + windowLineSpacing - WINDOW_BASE_MARGIN_2D; - Overlays.editOverlay(visibilityControls2D[i].radioOverlay, { y: y }); - Overlays.editOverlay(visibilityControls2D[i].textOverlay, { y: y }); - } - } + y += FRIENDS_BUTTON_HEIGHT + DISPLAY_SPACER; + displayControl.updatePosition(WINDOW_MARGIN, y); - function updateVisibilityControls() { - var i, - color; - - for (i = 0; i < visibilityControls2D.length; i += 1) { - color = visibilityControls2D[i].selected ? WINDOW_FOREGROUND_COLOR_2D : WINDOW_HEADING_COLOR_2D; - Overlays.editOverlay(visibilityControls2D[i].radioOverlay, { - color: color, - subImage: { y: visibilityControls2D[i].selected ? 0 : RADIO_BUTTON_SVG_DIAMETER } - }); - Overlays.editOverlay(visibilityControls2D[i].textOverlay, { color: color }); - } + y += windowLineHeight + VISIBILITY_SPACER; + visibilityControl.updatePosition(WINDOW_MARGIN, y); } function updateUsersDisplay() { @@ -202,8 +383,8 @@ var usersWindow = (function () { i; if (!isMinimized) { - maxTextWidth = WINDOW_WIDTH_2D - (isUsingScrollbars ? SCROLLBAR_BACKGROUND_WIDTH_2D : 0) - 2 * WINDOW_MARGIN_2D; - ellipsisWidth = Overlays.textSize(windowPane2D, "...").width; + maxTextWidth = WINDOW_WIDTH - (isUsingScrollbars ? SCROLLBAR_BACKGROUND_WIDTH : 0) - 2 * WINDOW_MARGIN; + ellipsisWidth = Overlays.textSize(windowPane, "...").width; reducedTextWidth = maxTextWidth - ellipsisWidth; for (i = 0; i < numUsersToDisplay; i += 1) { @@ -213,10 +394,10 @@ var usersWindow = (function () { if (textWidth > maxTextWidth) { // Trim and append "..." to fit window width - maxTextWidth = maxTextWidth - Overlays.textSize(windowPane2D, "...").width; + maxTextWidth = maxTextWidth - Overlays.textSize(windowPane, "...").width; while (textWidth > reducedTextWidth) { userText = userText.slice(0, -1); - textWidth = Overlays.textSize(windowPane2D, userText).width; + textWidth = Overlays.textSize(windowPane, userText).width; } userText += "..."; } @@ -227,31 +408,37 @@ var usersWindow = (function () { displayText = displayText.slice(1); // Remove leading "\n". scrollbarBackgroundHeight = numUsersToDisplay * windowLineHeight - windowLineSpacing / 2; - Overlays.editOverlay(scrollbarBackground2D, { + Overlays.editOverlay(scrollbarBackground, { height: scrollbarBackgroundHeight, visible: isUsingScrollbars }); scrollbarBarHeight = Math.max(numUsersToDisplay / linesOfUsers.length * scrollbarBackgroundHeight, SCROLLBAR_BAR_MIN_HEIGHT); - Overlays.editOverlay(scrollbarBar2D, { + Overlays.editOverlay(scrollbarBar, { height: scrollbarBarHeight, visible: isUsingScrollbars }); } - Overlays.editOverlay(windowPane2D, { + Overlays.editOverlay(windowPane, { height: windowHeight, text: displayText }); - Overlays.editOverlay(windowHeading2D, { + Overlays.editOverlay(windowHeading, { text: linesOfUsers.length > 0 ? "Users online" : "No users online" }); } function pollUsers() { + var url = API_URL; + + if (displayControl.getValue() === DISPLAY_FRIENDS) { + url += API_FRIENDS_FILTER; + } + usersRequest = new XMLHttpRequest(); - usersRequest.open("GET", API_URL, true); + usersRequest.open("GET", url, true); usersRequest.timeout = HTTP_GET_TIMEOUT; usersRequest.ontimeout = pollUsersTimedOut; usersRequest.onreadystatechange = processUsers; @@ -291,7 +478,7 @@ var usersWindow = (function () { } usersOnline[i].text = userText; - usersOnline[i].textWidth = Overlays.textSize(windowPane2D, userText).width; + usersOnline[i].textWidth = Overlays.textSize(windowPane, userText).width; linesOfUsers.push(i); } @@ -317,19 +504,14 @@ var usersWindow = (function () { }; function updateOverlayVisibility() { - var i; - - Overlays.editOverlay(windowPane2D, { visible: isVisible }); - Overlays.editOverlay(windowHeading2D, { visible: isVisible }); - Overlays.editOverlay(minimizeButton2D, { visible: isVisible }); - Overlays.editOverlay(scrollbarBackground2D, { visible: isVisible && isUsingScrollbars && !isMinimized }); - Overlays.editOverlay(scrollbarBar2D, { visible: isVisible && isUsingScrollbars && !isMinimized }); - Overlays.editOverlay(friendsButton2D, { visible: isVisible && !isMinimized }); - Overlays.editOverlay(visibilityHeading2D, { visible: isVisible && !isMinimized }); - for (i = 0; i < visibilityControls2D.length; i += 1) { - Overlays.editOverlay(visibilityControls2D[i].radioOverlay, { visible: isVisible && !isMinimized }); - Overlays.editOverlay(visibilityControls2D[i].textOverlay, { visible: isVisible && !isMinimized }); - } + Overlays.editOverlay(windowPane, { visible: isVisible }); + Overlays.editOverlay(windowHeading, { visible: isVisible }); + Overlays.editOverlay(minimizeButton, { visible: isVisible }); + Overlays.editOverlay(scrollbarBackground, { visible: isVisible && isUsingScrollbars && !isMinimized }); + Overlays.editOverlay(scrollbarBar, { visible: isVisible && isUsingScrollbars && !isMinimized }); + Overlays.editOverlay(friendsButton, { visible: isVisible && !isMinimized }); + displayControl.setVisible(isVisible && !isMinimized); + visibilityControl.setVisible(isVisible && !isMinimized); } function setVisible(visible) { @@ -350,8 +532,8 @@ var usersWindow = (function () { function setMinimized(minimized) { isMinimized = minimized; - Overlays.editOverlay(minimizeButton2D, { - subImage: { y: isMinimized ? MINIMIZE_BUTTON_SVG_HEIGHT / 2 : 0 } + Overlays.editOverlay(minimizeButton, { + subImage: { y: isMinimized ? MIN_MAX_BUTTON_SVG_HEIGHT / 2 : 0 } }); updateOverlayVisibility(); } @@ -363,13 +545,11 @@ var usersWindow = (function () { } function onFindableByChanged(event) { - var i; - - for (i = 0; i < visibilityControls2D.length; i += 1) { - visibilityControls2D[i].selected = event === VISIBILITY_VALUES[i]; + if (VISIBILITY_VALUES.indexOf(event) !== -1) { + visibilityControl.setValue(event); + } else { + print("Error: Unrecognized onFindableByChanged value: " + myVisibility); } - - updateVisibilityControls(); } function onMousePressEvent(event) { @@ -381,7 +561,6 @@ var usersWindow = (function () { maxY, lineClicked, userClicked, - i, delta; if (!isVisible) { @@ -390,10 +569,24 @@ var usersWindow = (function () { clickedOverlay = Overlays.getOverlayAtPoint({ x: event.x, y: event.y }); - if (clickedOverlay === windowPane2D) { + if (displayControl.handleClick(clickedOverlay)) { + if (usersTimer !== null) { + Script.clearTimeout(usersTimer); + usersTimer = null; + } + pollUsers(); + return; + } - overlayX = event.x - WINDOW_MARGIN_2D; - overlayY = event.y - viewportHeight + windowHeight - WINDOW_MARGIN_2D - windowLineHeight; + if (visibilityControl.handleClick(clickedOverlay)) { + GlobalServices.findableBy = visibilityControl.getValue(); + return; + } + + if (clickedOverlay === windowPane) { + + overlayX = event.x - WINDOW_MARGIN; + overlayY = event.y - viewportHeight + windowHeight - WINDOW_MARGIN - windowLineHeight; numLinesBefore = Math.round(overlayY / windowLineHeight); minY = numLinesBefore * windowLineHeight; @@ -415,15 +608,7 @@ var usersWindow = (function () { return; } - for (i = 0; i < visibilityControls2D.length; i += 1) { - // Don't need to test radioOverlay if it us under textOverlay. - if (clickedOverlay === visibilityControls2D[i].textOverlay && event.x <= visibilityControls2D[i].optionWidth) { - GlobalServices.findableBy = VISIBILITY_VALUES[i]; - return; - } - } - - if (clickedOverlay === minimizeButton2D) { + if (clickedOverlay === minimizeButton) { setMinimized(!isMinimized); calculateWindowHeight(); updateOverlayPositions(); @@ -431,16 +616,16 @@ var usersWindow = (function () { return; } - if (clickedOverlay === scrollbarBar2D) { + if (clickedOverlay === scrollbarBar) { scrollbarBarClickedAt = (event.y - scrollbarBarPosition.y) / scrollbarBarHeight; - Overlays.editOverlay(scrollbarBar2D, { - backgroundAlpha: SCROLLBAR_BAR_SELECTED_ALPHA_2D + Overlays.editOverlay(scrollbarBar, { + backgroundAlpha: SCROLLBAR_BAR_SELECTED_ALPHA }); isMovingScrollbar = true; return; } - if (clickedOverlay === scrollbarBackground2D) { + if (clickedOverlay === scrollbarBackground) { delta = scrollbarBarHeight / (scrollbarBackgroundHeight - scrollbarBarHeight); if (event.y < scrollbarBarPosition.y) { @@ -455,17 +640,17 @@ var usersWindow = (function () { return; } - if (clickedOverlay === friendsButton2D) { + if (clickedOverlay === friendsButton) { GlobalServices.editFriends(); } } function onMouseMoveEvent(event) { if (isMovingScrollbar) { - if (scrollbarBackgroundPosition.x - WINDOW_MARGIN_2D <= event.x - && event.x <= scrollbarBackgroundPosition.x + SCROLLBAR_BACKGROUND_WIDTH_2D + WINDOW_MARGIN_2D - && scrollbarBackgroundPosition.y - WINDOW_MARGIN_2D <= event.y - && event.y <= scrollbarBackgroundPosition.y + scrollbarBackgroundHeight + WINDOW_MARGIN_2D) { + if (scrollbarBackgroundPosition.x - WINDOW_MARGIN <= event.x + && event.x <= scrollbarBackgroundPosition.x + SCROLLBAR_BACKGROUND_WIDTH + WINDOW_MARGIN + && scrollbarBackgroundPosition.y - WINDOW_MARGIN <= event.y + && event.y <= scrollbarBackgroundPosition.y + scrollbarBackgroundHeight + WINDOW_MARGIN) { scrollbarValue = (event.y - scrollbarBarClickedAt * scrollbarBarHeight - scrollbarBackgroundPosition.y) / (scrollbarBackgroundHeight - scrollbarBarHeight - 2); scrollbarValue = Math.min(Math.max(scrollbarValue, 0.0), 1.0); @@ -473,8 +658,8 @@ var usersWindow = (function () { updateOverlayPositions(); updateUsersDisplay(); } else { - Overlays.editOverlay(scrollbarBar2D, { - backgroundAlpha: SCROLLBAR_BAR_ALPHA_2D + Overlays.editOverlay(scrollbarBar, { + backgroundAlpha: SCROLLBAR_BAR_ALPHA }); isMovingScrollbar = false; } @@ -482,8 +667,8 @@ var usersWindow = (function () { } function onMouseReleaseEvent() { - Overlays.editOverlay(scrollbarBar2D, { - backgroundAlpha: SCROLLBAR_BAR_ALPHA_2D + Overlays.editOverlay(scrollbarBar, { + backgroundAlpha: SCROLLBAR_BAR_ALPHA }); isMovingScrollbar = false; } @@ -509,183 +694,161 @@ var usersWindow = (function () { } function setUp() { - var textSizeOverlay, - optionText; + var textSizeOverlay; - textSizeOverlay = Overlays.addOverlay("text", { font: WINDOW_FONT_2D, visible: false }); + textSizeOverlay = Overlays.addOverlay("text", { font: WINDOW_FONT, visible: false }); windowTextHeight = Math.floor(Overlays.textSize(textSizeOverlay, "1").height); windowLineSpacing = Math.floor(Overlays.textSize(textSizeOverlay, "1\n2").height - 2 * windowTextHeight); windowLineHeight = windowTextHeight + windowLineSpacing; - radioButtonDiameter = RADIO_BUTTON_DISPLAY_SCALE * windowTextHeight; Overlays.deleteOverlay(textSizeOverlay); viewportHeight = Controller.getViewportDimensions().y; calculateWindowHeight(); - windowPane2D = Overlays.addOverlay("text", { + windowPane = Overlays.addOverlay("text", { x: 0, y: viewportHeight, // Start up off-screen - width: WINDOW_WIDTH_2D, + width: WINDOW_WIDTH, height: windowHeight, - topMargin: WINDOW_MARGIN_2D + windowLineHeight, - leftMargin: WINDOW_MARGIN_2D, - color: WINDOW_FOREGROUND_COLOR_2D, - alpha: WINDOW_FOREGROUND_ALPHA_2D, - backgroundColor: WINDOW_BACKGROUND_COLOR_2D, - backgroundAlpha: WINDOW_BACKGROUND_ALPHA_2D, + topMargin: WINDOW_MARGIN + windowLineHeight, + leftMargin: WINDOW_MARGIN, + color: WINDOW_FOREGROUND_COLOR, + alpha: WINDOW_FOREGROUND_ALPHA, + backgroundColor: WINDOW_BACKGROUND_COLOR, + backgroundAlpha: WINDOW_BACKGROUND_ALPHA, text: "", - font: WINDOW_FONT_2D, + font: WINDOW_FONT, visible: isVisible }); - windowHeading2D = Overlays.addOverlay("text", { - x: WINDOW_MARGIN_2D, + windowHeading = Overlays.addOverlay("text", { + x: WINDOW_MARGIN, y: viewportHeight, - width: WINDOW_WIDTH_2D - 2 * WINDOW_MARGIN_2D, + width: WINDOW_WIDTH - 2 * WINDOW_MARGIN, height: windowTextHeight, topMargin: 0, leftMargin: 0, - color: WINDOW_HEADING_COLOR_2D, - alpha: WINDOW_HEADING_ALPHA_2D, + color: WINDOW_HEADING_COLOR, + alpha: WINDOW_HEADING_ALPHA, backgroundAlpha: 0.0, text: "No users online", - font: WINDOW_FONT_2D, + font: WINDOW_FONT, visible: isVisible && !isMinimized }); - minimizeButton2D = Overlays.addOverlay("image", { - x: WINDOW_WIDTH_2D - WINDOW_MARGIN_2D / 2 - MINIMIZE_BUTTON_WIDTH_2D, + minimizeButton = Overlays.addOverlay("image", { + x: WINDOW_WIDTH - WINDOW_MARGIN / 2 - MIN_MAX_BUTTON_WIDTH, y: viewportHeight, - width: MINIMIZE_BUTTON_WIDTH_2D, - height: MINIMIZE_BUTTON_HEIGHT_2D, - imageURL: MINIMIZE_BUTTON_SVG, - subImage: { x: 0, y: 0, width: MINIMIZE_BUTTON_SVG_WIDTH, height: MINIMIZE_BUTTON_SVG_HEIGHT / 2 }, - color: MINIMIZE_BUTTON_COLOR_2D, - alpha: MINIMIZE_BUTTON_ALPHA_2D, + width: MIN_MAX_BUTTON_WIDTH, + height: MIN_MAX_BUTTON_HEIGHT, + imageURL: MIN_MAX_BUTTON_SVG, + subImage: { x: 0, y: 0, width: MIN_MAX_BUTTON_SVG_WIDTH, height: MIN_MAX_BUTTON_SVG_HEIGHT / 2 }, + color: MIN_MAX_BUTTON_COLOR, + alpha: MIN_MAX_BUTTON_ALPHA, visible: isVisible && !isMinimized }); scrollbarBackgroundPosition = { - x: WINDOW_WIDTH_2D - 0.5 * WINDOW_MARGIN_2D - SCROLLBAR_BACKGROUND_WIDTH_2D, + x: WINDOW_WIDTH - 0.5 * WINDOW_MARGIN - SCROLLBAR_BACKGROUND_WIDTH, y: viewportHeight }; - scrollbarBackground2D = Overlays.addOverlay("text", { + scrollbarBackground = Overlays.addOverlay("text", { x: scrollbarBackgroundPosition.x, y: scrollbarBackgroundPosition.y, - width: SCROLLBAR_BACKGROUND_WIDTH_2D, + width: SCROLLBAR_BACKGROUND_WIDTH, height: windowTextHeight, - backgroundColor: SCROLLBAR_BACKGROUND_COLOR_2D, - backgroundAlpha: SCROLLBAR_BACKGROUND_ALPHA_2D, + backgroundColor: SCROLLBAR_BACKGROUND_COLOR, + backgroundAlpha: SCROLLBAR_BACKGROUND_ALPHA, text: "", visible: isVisible && isUsingScrollbars && !isMinimized }); scrollbarBarPosition = { - x: WINDOW_WIDTH_2D - 0.5 * WINDOW_MARGIN_2D - SCROLLBAR_BACKGROUND_WIDTH_2D + 1, + x: WINDOW_WIDTH - 0.5 * WINDOW_MARGIN - SCROLLBAR_BACKGROUND_WIDTH + 1, y: viewportHeight }; - scrollbarBar2D = Overlays.addOverlay("text", { + scrollbarBar = Overlays.addOverlay("text", { x: scrollbarBarPosition.x, y: scrollbarBarPosition.y, - width: SCROLLBAR_BACKGROUND_WIDTH_2D - 2, + width: SCROLLBAR_BACKGROUND_WIDTH - 2, height: windowTextHeight, - backgroundColor: SCROLLBAR_BAR_COLOR_2D, - backgroundAlpha: SCROLLBAR_BAR_ALPHA_2D, + backgroundColor: SCROLLBAR_BAR_COLOR, + backgroundAlpha: SCROLLBAR_BAR_ALPHA, text: "", visible: isVisible && isUsingScrollbars && !isMinimized }); - friendsButton2D = Overlays.addOverlay("image", { - x: WINDOW_MARGIN_2D, + friendsButton = Overlays.addOverlay("image", { + x: WINDOW_MARGIN, y: viewportHeight, - width: FRIENDS_BUTTON_WIDTH_2D, - height: FRIENDS_BUTTON_HEIGHT_2D, + width: FRIENDS_BUTTON_WIDTH, + height: FRIENDS_BUTTON_HEIGHT, imageURL: FRIENDS_BUTTON_SVG, subImage: { x: 0, y: 0, width: FRIENDS_BUTTON_SVG_WIDTH, height: FRIENDS_BUTTON_SVG_HEIGHT }, - color: FRIENDS_BUTTON_COLOR_2D, - alpha: FRIENDS_BUTTON_ALPHA_2D + color: FRIENDS_BUTTON_COLOR, + alpha: FRIENDS_BUTTON_ALPHA }); - visibilityHeading2D = Overlays.addOverlay("text", { - x: WINDOW_MARGIN_2D, + displayControl = new PopUpMenu({ + prompt: DISPLAY_PROMPT, + value: DISPLAY_VALUES[0], + values: DISPLAY_VALUES, + displayValues: DISPLAY_DISPLAY_VALUES, + x: WINDOW_MARGIN, y: viewportHeight, - width: WINDOW_WIDTH_2D - 2 * WINDOW_MARGIN_2D, - height: windowTextHeight, - topMargin: 0, - leftMargin: 0, - color: WINDOW_HEADING_COLOR_2D, - alpha: WINDOW_HEADING_ALPHA_2D, - backgroundAlpha: 0.0, - text: "I am visible to:", - font: WINDOW_FONT_2D, + width: WINDOW_WIDTH - 1.5 * WINDOW_MARGIN, + promptWidth: DISPLAY_PROMPT_WIDTH, + lineHeight: windowLineHeight, + textHeight: windowTextHeight, + font: WINDOW_FONT, + promptColor: WINDOW_HEADING_COLOR, + promptAlpha: WINDOW_HEADING_ALPHA, + promptBackgroundColor: WINDOW_BACKGROUND_COLOR, + promptBackgroundAlpha: 0.0, + optionColor: WINDOW_FOREGROUND_COLOR, + optionAlpha: WINDOW_FOREGROUND_ALPHA, + optionBackgroundColor: OPTION_BACKGROUND_COLOR, + optionBackgroundAlpha: OPTION_BACKGROUND_ALPHA, + popupBackgroundColor: DISPLAY_OPTIONS_BACKGROUND_COLOR, + popupBackgroundAlpha: DISPLAY_OPTIONS_BACKGROUND_ALPHA, + buttonColor: MIN_MAX_BUTTON_COLOR, + buttonAlpha: MIN_MAX_BUTTON_ALPHA, visible: isVisible && !isMinimized }); myVisibility = GlobalServices.findableBy; - if (!/^(all|friends|none)$/.test(myVisibility)) { - print("Error: Unrecognized findableBy value"); - myVisibility = ""; + if (VISIBILITY_VALUES.indexOf(myVisibility) === -1) { + print("Error: Unrecognized findableBy value: " + myVisibility); + myVisibility = VISIBILITY_ALL; } - optionText = "everyone"; - visibilityControls2D = [{ - radioOverlay: Overlays.addOverlay("image", { // Create first so that it is under textOverlay. - x: WINDOW_MARGIN_2D, - y: viewportHeight, - width: radioButtonDiameter, - height: radioButtonDiameter, - imageURL: RADIO_BUTTON_SVG, - subImage: { - x: 0, - y: RADIO_BUTTON_SVG_DIAMETER, // Off - width: RADIO_BUTTON_SVG_DIAMETER, - height: RADIO_BUTTON_SVG_DIAMETER - }, - color: WINDOW_HEADING_COLOR_2D, - alpha: WINDOW_FOREGROUND_ALPHA_2D, - visible: isVisible && !isMinimized - }), - textOverlay: Overlays.addOverlay("text", { - x: WINDOW_MARGIN_2D, - y: viewportHeight, - width: WINDOW_WIDTH_2D - SCROLLBAR_BACKGROUND_WIDTH_2D - 2 * WINDOW_MARGIN_2D, - height: windowTextHeight, - topMargin: 0, - leftMargin: VISIBILITY_RADIO_SPACE, - color: WINDOW_HEADING_COLOR_2D, - alpha: WINDOW_FOREGROUND_ALPHA_2D, - backgroundAlpha: 0.0, - text: optionText, - font: WINDOW_FONT_2D, - visible: isVisible && !isMinimized - }), - selected: myVisibility === VISIBILITY_VALUES[0] - }]; - visibilityControls2D[0].optionWidth = WINDOW_MARGIN_2D + VISIBILITY_RADIO_SPACE - + Overlays.textSize(visibilityControls2D[0].textOverlay, optionText).width; - - optionText = "my friends"; - visibilityControls2D[1] = { - radioOverlay: Overlays.cloneOverlay(visibilityControls2D[0].radioOverlay), - textOverlay: Overlays.cloneOverlay(visibilityControls2D[0].textOverlay), - selected: myVisibility === VISIBILITY_VALUES[1] - }; - Overlays.editOverlay(visibilityControls2D[1].textOverlay, { text: optionText }); - visibilityControls2D[1].optionWidth = WINDOW_MARGIN_2D + VISIBILITY_RADIO_SPACE - + Overlays.textSize(visibilityControls2D[1].textOverlay, optionText).width; - - optionText = "no one"; - visibilityControls2D[2] = { - radioOverlay: Overlays.cloneOverlay(visibilityControls2D[0].radioOverlay), - textOverlay: Overlays.cloneOverlay(visibilityControls2D[0].textOverlay), - selected: myVisibility === VISIBILITY_VALUES[2] - }; - Overlays.editOverlay(visibilityControls2D[2].textOverlay, { text: optionText }); - visibilityControls2D[2].optionWidth = WINDOW_MARGIN_2D + VISIBILITY_RADIO_SPACE - + Overlays.textSize(visibilityControls2D[2].textOverlay, optionText).width; - - updateVisibilityControls(); + visibilityControl = new PopUpMenu({ + prompt: VISIBILITY_PROMPT, + value: myVisibility, + values: VISIBILITY_VALUES, + displayValues: VISIBILITY_DISPLAY_VALUES, + x: WINDOW_MARGIN, + y: viewportHeight, + width: WINDOW_WIDTH - 1.5 * WINDOW_MARGIN, + promptWidth: VISIBILITY_PROMPT_WIDTH, + lineHeight: windowLineHeight, + textHeight: windowTextHeight, + font: WINDOW_FONT, + promptColor: WINDOW_HEADING_COLOR, + promptAlpha: WINDOW_HEADING_ALPHA, + promptBackgroundColor: WINDOW_BACKGROUND_COLOR, + promptBackgroundAlpha: 0.0, + optionColor: WINDOW_FOREGROUND_COLOR, + optionAlpha: WINDOW_FOREGROUND_ALPHA, + optionBackgroundColor: OPTION_BACKGROUND_COLOR, + optionBackgroundAlpha: OPTION_BACKGROUND_ALPHA, + popupBackgroundColor: DISPLAY_OPTIONS_BACKGROUND_COLOR, + popupBackgroundAlpha: DISPLAY_OPTIONS_BACKGROUND_ALPHA, + buttonColor: MIN_MAX_BUTTON_COLOR, + buttonAlpha: MIN_MAX_BUTTON_ALPHA, + visible: isVisible && !isMinimized + }); Controller.mousePressEvent.connect(onMousePressEvent); Controller.mouseMoveEvent.connect(onMouseMoveEvent); @@ -709,22 +872,17 @@ var usersWindow = (function () { } function tearDown() { - var i; - Menu.removeMenuItem(MENU_NAME, MENU_ITEM); Script.clearTimeout(usersTimer); - Overlays.deleteOverlay(windowPane2D); - Overlays.deleteOverlay(windowHeading2D); - Overlays.deleteOverlay(minimizeButton2D); - Overlays.deleteOverlay(scrollbarBackground2D); - Overlays.deleteOverlay(scrollbarBar2D); - Overlays.deleteOverlay(friendsButton2D); - Overlays.deleteOverlay(visibilityHeading2D); - for (i = 0; i <= visibilityControls2D.length; i += 1) { - Overlays.deleteOverlay(visibilityControls2D[i].textOverlay); - Overlays.deleteOverlay(visibilityControls2D[i].radioOverlay); - } + Overlays.deleteOverlay(windowPane); + Overlays.deleteOverlay(windowHeading); + Overlays.deleteOverlay(minimizeButton); + Overlays.deleteOverlay(scrollbarBackground); + Overlays.deleteOverlay(scrollbarBar); + Overlays.deleteOverlay(friendsButton); + displayControl.tearDown(); + visibilityControl.tearDown(); } setUp(); diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 303892d072..6356902d9d 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -94,6 +94,7 @@ #include "Menu.h" #include "ModelPackager.h" #include "Util.h" +#include "InterfaceLogging.h" #include "avatar/AvatarManager.h" @@ -330,7 +331,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _applicationStartupTime = startup_time; - qDebug() << "[VERSION] Build sequence: " << qPrintable(applicationVersion()); + qCDebug(interfaceapp) << "[VERSION] Build sequence: " << qPrintable(applicationVersion()); _bookmarks = new Bookmarks(); // Before setting up the menu @@ -528,7 +529,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : // check first run... if (_firstRun.get()) { - qDebug() << "This is a first run..."; + qCDebug(interfaceapp) << "This is a first run..."; // clear the scripts, and set out script to our default scripts clearScriptsBeforeRunning(); loadScript(DEFAULT_SCRIPTS_JS_URL); @@ -649,7 +650,7 @@ Application::~Application() { } void Application::initializeGL() { - qDebug() << "Created Display Window."; + qCDebug(interfaceapp) << "Created Display Window."; // initialize glut for shape drawing; Qt apparently initializes it on OS X #ifndef __APPLE__ @@ -661,22 +662,22 @@ void Application::initializeGL() { } #endif - qDebug() << "GL Version: " << QString((const char*) glGetString(GL_VERSION)); - qDebug() << "GL Shader Language Version: " << QString((const char*) glGetString(GL_SHADING_LANGUAGE_VERSION)); - qDebug() << "GL Vendor: " << QString((const char*) glGetString(GL_VENDOR)); - qDebug() << "GL Renderer: " << QString((const char*) glGetString(GL_RENDERER)); + qCDebug(interfaceapp) << "GL Version: " << QString((const char*) glGetString(GL_VERSION)); + qCDebug(interfaceapp) << "GL Shader Language Version: " << QString((const char*) glGetString(GL_SHADING_LANGUAGE_VERSION)); + qCDebug(interfaceapp) << "GL Vendor: " << QString((const char*) glGetString(GL_VENDOR)); + qCDebug(interfaceapp) << "GL Renderer: " << QString((const char*) glGetString(GL_RENDERER)); #ifdef WIN32 GLenum err = glewInit(); if (GLEW_OK != err) { - /* Problem: glewInit failed, something is seriously wrong. */ - qDebug("Error: %s\n", glewGetErrorString(err)); + /* Problem: glewInit failed, something is seriously wrong. */ + qCDebug(interfaceapp, "Error: %s\n", glewGetErrorString(err)); } - qDebug("Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); + qCDebug(interfaceapp, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); if (wglewGetExtension("WGL_EXT_swap_control")) { int swapInterval = wglGetSwapIntervalEXT(); - qDebug("V-Sync is %s\n", (swapInterval > 0 ? "ON" : "OFF")); + qCDebug(interfaceapp, "V-Sync is %s\n", (swapInterval > 0 ? "ON" : "OFF")); } #endif @@ -684,15 +685,15 @@ void Application::initializeGL() { // TODO: Write the correct code for Linux... /* if (wglewGetExtension("WGL_EXT_swap_control")) { int swapInterval = wglGetSwapIntervalEXT(); - qDebug("V-Sync is %s\n", (swapInterval > 0 ? "ON" : "OFF")); + qCDebug(interfaceapp, "V-Sync is %s\n", (swapInterval > 0 ? "ON" : "OFF")); }*/ #endif initDisplay(); - qDebug( "Initialized Display."); + qCDebug(interfaceapp, "Initialized Display."); init(); - qDebug( "init() complete."); + qCDebug(interfaceapp, "init() complete."); // create thread for parsing of octee data independent of the main network and rendering threads _octreeProcessor.initialize(_enableProcessOctreeThread); @@ -713,7 +714,7 @@ void Application::initializeGL() { if (_justStarted) { float startupTime = (float)_applicationStartupTime.elapsed() / 1000.0; _justStarted = false; - qDebug("Startup time: %4.2f seconds.", startupTime); + qCDebug(interfaceapp, "Startup time: %4.2f seconds.", startupTime); } // update before the first render @@ -1800,7 +1801,7 @@ bool Application::exportEntities(const QString& filename, float x, float y, floa } exportTree.writeToSVOFile(filename.toLocal8Bit().constData()); } else { - qDebug() << "No models were selected"; + qCDebug(interfaceapp) << "No models were selected"; return false; } @@ -1898,7 +1899,7 @@ void Application::init() { DependencyManager::get()->loadSettings(addressLookupString); - qDebug() << "Loaded settings"; + qCDebug(interfaceapp) << "Loaded settings"; #ifdef __APPLE__ if (Menu::getInstance()->isOptionChecked(MenuOption::SixenseEnabled)) { @@ -2379,7 +2380,7 @@ int Application::sendNackPackets() { void Application::queryOctree(NodeType_t serverType, PacketType packetType, NodeToJurisdictionMap& jurisdictions) { - //qDebug() << ">>> inside... queryOctree()... _viewFrustum.getFieldOfView()=" << _viewFrustum.getFieldOfView(); + //qCDebug(interfaceapp) << ">>> inside... queryOctree()... _viewFrustum.getFieldOfView()=" << _viewFrustum.getFieldOfView(); bool wantExtraDebugging = getLogger()->extraDebugging(); // These will be the same for all servers, so we can set them up once and then reuse for each server we send to. @@ -2442,7 +2443,7 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node }); if (wantExtraDebugging) { - qDebug("Servers: total %d, in view %d, unknown jurisdiction %d", + qCDebug(interfaceapp, "Servers: total %d, in view %d, unknown jurisdiction %d", totalServers, inViewServers, unknownJurisdictionServers); } @@ -2463,7 +2464,7 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node } if (wantExtraDebugging) { - qDebug("perServerPPS: %d perUnknownServer: %d", perServerPPS, perUnknownServer); + qCDebug(interfaceapp, "perServerPPS: %d perUnknownServer: %d", perServerPPS, perUnknownServer); } nodeList->eachNode([&](const SharedNodePointer& node){ @@ -2482,7 +2483,7 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node if (jurisdictions.find(nodeUUID) == jurisdictions.end()) { unknownView = true; // assume it's in view if (wantExtraDebugging) { - qDebug() << "no known jurisdiction for node " << *node << ", assume it's visible."; + qCDebug(interfaceapp) << "no known jurisdiction for node " << *node << ", assume it's visible."; } } else { const JurisdictionMap& map = (jurisdictions)[nodeUUID]; @@ -2502,7 +2503,7 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node } } else { if (wantExtraDebugging) { - qDebug() << "Jurisdiction without RootCode for node " << *node << ". That's unusual!"; + qCDebug(interfaceapp) << "Jurisdiction without RootCode for node " << *node << ". That's unusual!"; } } } @@ -2511,7 +2512,7 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node _octreeQuery.setMaxOctreePacketsPerSecond(perServerPPS); } else if (unknownView) { if (wantExtraDebugging) { - qDebug() << "no known jurisdiction for node " << *node << ", give it budget of " + qCDebug(interfaceapp) << "no known jurisdiction for node " << *node << ", give it budget of " << perUnknownServer << " to send us jurisdiction."; } @@ -2525,11 +2526,11 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node _octreeQuery.setCameraNearClip(0.1f); _octreeQuery.setCameraFarClip(0.1f); if (wantExtraDebugging) { - qDebug() << "Using 'minimal' camera position for node" << *node; + qCDebug(interfaceapp) << "Using 'minimal' camera position for node" << *node; } } else { if (wantExtraDebugging) { - qDebug() << "Using regular camera position for node" << *node; + qCDebug(interfaceapp) << "Using regular camera position for node" << *node; } } _octreeQuery.setMaxOctreePacketsPerSecond(perUnknownServer); @@ -3298,13 +3299,13 @@ void Application::updateWindowTitle(){ #ifndef WIN32 // crashes with vs2013/win32 - qDebug("Application title set to: %s", title.toStdString().c_str()); + qCDebug(interfaceapp, "Application title set to: %s", title.toStdString().c_str()); #endif _window->setWindowTitle(title); } void Application::clearDomainOctreeDetails() { - qDebug() << "Clearing domain octree details..."; + qCDebug(interfaceapp) << "Clearing domain octree details..."; // reset the environment so that we don't erroneously end up with multiple _environment.resetToDefault(); @@ -3376,7 +3377,7 @@ void Application::nodeKilled(SharedNodePointer node) { voxelDetailsForCode(rootCode, rootDetails); _entityServerJurisdictions.unlock(); - qDebug("model server going away...... v[%f, %f, %f, %f]", + qCDebug(interfaceapp, "model server going away...... v[%f, %f, %f, %f]", rootDetails.x, rootDetails.y, rootDetails.z, rootDetails.s); // Add the jurisditionDetails object to the list of "fade outs" @@ -3462,7 +3463,7 @@ int Application::parseOctreeStats(const QByteArray& packet, const SharedNodePoin if (jurisdiction->find(nodeUUID) == jurisdiction->end()) { jurisdiction->unlock(); - qDebug("stats from new %s server... [%f, %f, %f, %f]", + qCDebug(interfaceapp, "stats from new %s server... [%f, %f, %f, %f]", qPrintable(serverType), rootDetails.x, rootDetails.y, rootDetails.z, rootDetails.s); // Add the jurisditionDetails object to the list of "fade outs" @@ -3708,7 +3709,7 @@ bool Application::askToSetAvatarUrl(const QString& url) { QNetworkRequest networkRequest = QNetworkRequest(url); networkRequest.setHeader(QNetworkRequest::UserAgentHeader, HIGH_FIDELITY_USER_AGENT); QNetworkReply* reply = networkAccessManager.get(networkRequest); - qDebug() << "Downloading avatar file at " << url; + qCDebug(interfaceapp) << "Downloading avatar file at " << url; QEventLoop loop; QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); loop.exec(); @@ -3757,13 +3758,13 @@ bool Application::askToSetAvatarUrl(const QString& url) { msgBox.exec(); if (msgBox.clickedButton() == headButton) { - qDebug() << "Chose to use for head: " << url; + qCDebug(interfaceapp) << "Chose to use for head: " << url; _myAvatar->setFaceModelURL(url); UserActivityLogger::getInstance().changedModel("head", url); _myAvatar->sendIdentityPacket(); emit faceURLChanged(url); } else if (msgBox.clickedButton() == bodyButton) { - qDebug() << "Chose to use for body: " << url; + qCDebug(interfaceapp) << "Chose to use for body: " << url; _myAvatar->setSkeletonModelURL(url); // if the head is empty, reset it to the default head. if (_myAvatar->getFaceModelURLString().isEmpty()) { @@ -3775,7 +3776,7 @@ bool Application::askToSetAvatarUrl(const QString& url) { _myAvatar->sendIdentityPacket(); emit skeletonURLChanged(url); } else if (msgBox.clickedButton() == bodyAndHeadButton) { - qDebug() << "Chose to use for body + head: " << url; + qCDebug(interfaceapp) << "Chose to use for body + head: " << url; _myAvatar->setFaceModelURL(QString()); _myAvatar->setSkeletonModelURL(url); UserActivityLogger::getInstance().changedModel("skeleton", url); @@ -3783,7 +3784,7 @@ bool Application::askToSetAvatarUrl(const QString& url) { emit faceURLChanged(QString()); emit skeletonURLChanged(url); } else { - qDebug() << "Declined to use the avatar: " << url; + qCDebug(interfaceapp) << "Declined to use the avatar: " << url; } return true; } @@ -3795,10 +3796,10 @@ bool Application::askToLoadScript(const QString& scriptFilenameOrURL) { reply = QMessageBox::question(getWindow(), "Run Script", message, QMessageBox::Yes|QMessageBox::No); if (reply == QMessageBox::Yes) { - qDebug() << "Chose to run the script: " << scriptFilenameOrURL; + qCDebug(interfaceapp) << "Chose to run the script: " << scriptFilenameOrURL; loadScript(scriptFilenameOrURL); } else { - qDebug() << "Declined to run the script: " << scriptFilenameOrURL; + qCDebug(interfaceapp) << "Declined to run the script: " << scriptFilenameOrURL; } return true; } @@ -3856,7 +3857,7 @@ void Application::handleScriptEngineLoaded(const QString& scriptFilename) { } void Application::handleScriptLoadError(const QString& scriptFilename) { - qDebug() << "Application::loadScript(), script failed to load..."; + qCDebug(interfaceapp) << "Application::loadScript(), script failed to load..."; QMessageBox::warning(getWindow(), "Error Loading Script", scriptFilename + " failed to load."); } @@ -3878,7 +3879,7 @@ void Application::stopAllScripts(bool restart) { connect(it.value(), SIGNAL(finished(const QString&)), SLOT(loadScript(const QString&))); } it.value()->stop(); - qDebug() << "stopping script..." << it.key(); + qCDebug(interfaceapp) << "stopping script..." << it.key(); } // HACK: ATM scripts cannot set/get their animation priorities, so we clear priorities // whenever a script stops in case it happened to have been setting joint rotations. @@ -3890,7 +3891,7 @@ void Application::stopScript(const QString &scriptName) { const QString& scriptURLString = QUrl(scriptName).toString(); if (_scriptEnginesHash.contains(scriptURLString)) { _scriptEnginesHash.value(scriptURLString)->stop(); - qDebug() << "stopping script..." << scriptName; + qCDebug(interfaceapp) << "stopping script..." << scriptName; // HACK: ATM scripts cannot set/get their animation priorities, so we clear priorities // whenever a script stops in case it happened to have been setting joint rotations. // TODO: expose animation priorities and provide a layered animation control system. @@ -3988,8 +3989,8 @@ void Application::domainSettingsReceived(const QJsonObject& domainSettingsObject voxelWalletUUID = QUuid(voxelObject[VOXEL_WALLET_UUID].toString()); } - qDebug() << "Octree edits costs are" << satoshisPerVoxel << "per octree cell and" << satoshisPerMeterCubed << "per meter cubed"; - qDebug() << "Destination wallet UUID for edit payments is" << voxelWalletUUID; + qCDebug(interfaceapp) << "Octree edits costs are" << satoshisPerVoxel << "per octree cell and" << satoshisPerMeterCubed << "per meter cubed"; + qCDebug(interfaceapp) << "Destination wallet UUID for edit payments is" << voxelWalletUUID; } QString Application::getPreviousScriptLocation() { @@ -4154,9 +4155,9 @@ void Application::setVSyncEnabled() { if (wglewGetExtension("WGL_EXT_swap_control")) { wglSwapIntervalEXT(vsyncOn); int swapInterval = wglGetSwapIntervalEXT(); - qDebug("V-Sync is %s\n", (swapInterval > 0 ? "ON" : "OFF")); + qCDebug(interfaceapp, "V-Sync is %s\n", (swapInterval > 0 ? "ON" : "OFF")); } else { - qDebug("V-Sync is FORCED ON on this system\n"); + qCDebug(interfaceapp, "V-Sync is FORCED ON on this system\n"); } #elif defined(Q_OS_LINUX) // TODO: write the poper code for linux @@ -4165,13 +4166,13 @@ void Application::setVSyncEnabled() { glxSwapIntervalEXT(vsyncOn); int swapInterval = xglGetSwapIntervalEXT(); _isVSyncOn = swapInterval; - qDebug("V-Sync is %s\n", (swapInterval > 0 ? "ON" : "OFF")); + qCDebug(interfaceapp, "V-Sync is %s\n", (swapInterval > 0 ? "ON" : "OFF")); } else { - qDebug("V-Sync is FORCED ON on this system\n"); + qCDebug(interfaceapp, "V-Sync is FORCED ON on this system\n"); } */ #else - qDebug("V-Sync is FORCED ON on this system\n"); + qCDebug(interfaceapp, "V-Sync is FORCED ON on this system\n"); #endif } @@ -4287,7 +4288,7 @@ void Application::notifyPacketVersionMismatch() { void Application::checkSkeleton() { if (_myAvatar->getSkeletonModel().isActive() && !_myAvatar->getSkeletonModel().hasSkeleton()) { - qDebug() << "MyAvatar model has no skeleton"; + qCDebug(interfaceapp) << "MyAvatar model has no skeleton"; QString message = "Your selected avatar body has no skeleton.\n\nThe default body will be loaded..."; QMessageBox msgBox; diff --git a/interface/src/Bookmarks.cpp b/interface/src/Bookmarks.cpp index 4d484fd2cc..4f022623dc 100644 --- a/interface/src/Bookmarks.cpp +++ b/interface/src/Bookmarks.cpp @@ -23,6 +23,7 @@ #include "MainWindow.h" #include "Menu.h" +#include "InterfaceLogging.h" #include "Bookmarks.h" @@ -35,7 +36,7 @@ void Bookmarks::insert(const QString& name, const QString& address) { _bookmarks.insert(name, address); if (contains(name)) { - qDebug() << "Added bookmark:" << name << "," << address; + qCDebug(interfaceapp) << "Added bookmark:" << name << "," << address; persistToFile(); } else { qWarning() << "Couldn't add bookmark: " << name << "," << address; @@ -46,7 +47,7 @@ void Bookmarks::remove(const QString& name) { _bookmarks.remove(name); if (!contains(name)) { - qDebug() << "Deleted bookmark:" << name; + qCDebug(interfaceapp) << "Deleted bookmark:" << name; persistToFile(); } else { qWarning() << "Couldn't delete bookmark:" << name; diff --git a/interface/src/DatagramProcessor.cpp b/interface/src/DatagramProcessor.cpp index 9ac2b51097..f477be0718 100644 --- a/interface/src/DatagramProcessor.cpp +++ b/interface/src/DatagramProcessor.cpp @@ -18,6 +18,7 @@ #include "avatar/AvatarManager.h" #include "AudioClient.h" #include "Menu.h" +#include "InterfaceLogging.h" #include "DatagramProcessor.h" @@ -125,8 +126,8 @@ void DatagramProcessor::processDatagrams() { // output to the log so the user knows they got a denied connection request // and check and signal for an access token so that we can make sure they are logged in - qDebug() << "The domain-server denied a connection request: " << reason; - qDebug() << "You may need to re-log to generate a keypair so you can provide a username signature."; + qCDebug(interfaceapp) << "The domain-server denied a connection request: " << reason; + qCDebug(interfaceapp) << "You may need to re-log to generate a keypair so you can provide a username signature."; application->domainConnectionDenied(reason); AccountManager::getInstance().checkAndSignalForAccessToken(); break; diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index e6fc0184cf..a08abfc920 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -24,6 +24,7 @@ #include "Application.h" #include "Camera.h" #include "world.h" +#include "InterfaceLogging.h" #include "Environment.h" @@ -49,7 +50,7 @@ Environment::~Environment() { void Environment::init() { if (_initialized) { - qDebug("[ERROR] Environment is already initialized."); + qCDebug(interfaceapp, "[ERROR] Environment is already initialized."); return; } diff --git a/interface/src/InterfaceLogging.cpp b/interface/src/InterfaceLogging.cpp new file mode 100644 index 0000000000..18bc4e58e8 --- /dev/null +++ b/interface/src/InterfaceLogging.cpp @@ -0,0 +1,14 @@ +// +// InterfaceLogging.cpp +// libraries/interface/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "InterfaceLogging.h" + +Q_LOGGING_CATEGORY(interfaceapp, "hifi.interface") diff --git a/interface/src/InterfaceLogging.h b/interface/src/InterfaceLogging.h new file mode 100644 index 0000000000..d1d92aa93d --- /dev/null +++ b/interface/src/InterfaceLogging.h @@ -0,0 +1,19 @@ +// +// InterfaceLogging.h +// interface/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_InterfaceLogging_h +#define hifi_InterfaceLogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(interfaceapp) + +#endif // hifi_InterfaceLogging_h diff --git a/interface/src/LODManager.cpp b/interface/src/LODManager.cpp index cb4913df72..93ef8041ac 100644 --- a/interface/src/LODManager.cpp +++ b/interface/src/LODManager.cpp @@ -14,6 +14,7 @@ #include "Application.h" #include "ui/DialogsManager.h" +#include "InterfaceLogging.h" #include "LODManager.h" @@ -78,7 +79,7 @@ void LODManager::autoAdjustLOD(float currentFPS) { doDownShift = _fpsAverageDownWindow.getAverage() < getLODDecreaseFPS(); if (!doDownShift) { - qDebug() << "---- WE APPEAR TO BE DONE DOWN SHIFTING -----"; + qCDebug(interfaceapp) << "---- WE APPEAR TO BE DONE DOWN SHIFTING -----"; _isDownshifting = false; _lastStable = now; } @@ -102,7 +103,7 @@ void LODManager::autoAdjustLOD(float currentFPS) { if (changed) { if (_isDownshifting) { // subsequent downshift - qDebug() << "adjusting LOD DOWN..." + qCDebug(interfaceapp) << "adjusting LOD DOWN..." << "average fps for last "<< DOWN_SHIFT_WINDOW_IN_SECS <<"seconds was " << _fpsAverageDownWindow.getAverage() << "minimum is:" << getLODDecreaseFPS() @@ -110,7 +111,7 @@ void LODManager::autoAdjustLOD(float currentFPS) { << " NEW _octreeSizeScale=" << _octreeSizeScale; } else { // first downshift - qDebug() << "adjusting LOD DOWN after initial delay..." + qCDebug(interfaceapp) << "adjusting LOD DOWN after initial delay..." << "average fps for last "<< START_DELAY_WINDOW_IN_SECS <<"seconds was " << _fpsAverageStartWindow.getAverage() << "minimum is:" << getLODDecreaseFPS() @@ -145,7 +146,7 @@ void LODManager::autoAdjustLOD(float currentFPS) { } if (changed) { - qDebug() << "adjusting LOD UP... average fps for last "<< UP_SHIFT_WINDOW_IN_SECS <<"seconds was " + qCDebug(interfaceapp) << "adjusting LOD UP... average fps for last "<< UP_SHIFT_WINDOW_IN_SECS <<"seconds was " << _fpsAverageUpWindow.getAverage() << "upshift point is:" << getLODIncreaseFPS() << "elapsedSinceUpShift:" << elapsedSinceUpShift diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index f95ffddbfb..1cce0b1f56 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -39,6 +39,7 @@ #include "ui/DialogsManager.h" #include "ui/NodeBounds.h" #include "ui/StandAloneJSConsole.h" +#include "InterfaceLogging.h" #include "Menu.h" @@ -51,7 +52,7 @@ Menu* Menu::getInstance() { menuInstanceMutex.lock(); if (!_instance) { - qDebug("First call to Menu::getInstance() - initing menu."); + qCDebug(interfaceapp, "First call to Menu::getInstance() - initing menu."); _instance = new Menu(); } @@ -743,7 +744,7 @@ void Menu::triggerOption(const QString& menuOption) { if (action) { action->trigger(); } else { - qDebug() << "NULL Action for menuOption '" << menuOption << "'"; + qCDebug(interfaceapp) << "NULL Action for menuOption '" << menuOption << "'"; } } @@ -987,7 +988,7 @@ void Menu::setVisibility() { } else if (Menu::getInstance()->isOptionChecked(MenuOption::VisibleToNoOne)) { discoverabilityManager->setDiscoverabilityMode(Discoverability::None); } else { - qDebug() << "ERROR Menu::setVisibility() called with unrecognized value."; + qCDebug(interfaceapp) << "ERROR Menu::setVisibility() called with unrecognized value."; } } @@ -999,6 +1000,6 @@ void Menu::visibilityChanged(Discoverability::Mode discoverabilityMode) { } else if (discoverabilityMode == Discoverability::None) { setIsOptionChecked(MenuOption::VisibleToNoOne, true); } else { - qDebug() << "ERROR Menu::visibilityChanged() called with unrecognized value."; + qCDebug(interfaceapp) << "ERROR Menu::visibilityChanged() called with unrecognized value."; } } diff --git a/interface/src/ModelPackager.cpp b/interface/src/ModelPackager.cpp index 787c21a2ef..2864738f9c 100644 --- a/interface/src/ModelPackager.cpp +++ b/interface/src/ModelPackager.cpp @@ -18,6 +18,7 @@ #include "ModelSelector.h" #include "ModelPropertiesDialog.h" +#include "InterfaceLogging.h" #include "ModelPackager.h" @@ -84,7 +85,7 @@ bool ModelPackager::loadModel() { qWarning() << QString("ModelPackager::loadModel(): Could not open FST file %1").arg(_modelFile.filePath()); return false; } - qDebug() << "Reading FST file : " << _modelFile.filePath(); + qCDebug(interfaceapp) << "Reading FST file : " << _modelFile.filePath(); _mapping = FSTReader::readMapping(fst.readAll()); fst.close(); @@ -103,7 +104,7 @@ bool ModelPackager::loadModel() { qWarning() << QString("ModelPackager::loadModel(): Could not open FBX file %1").arg(_fbxInfo.filePath()); return false; } - qDebug() << "Reading FBX file : " << _fbxInfo.filePath(); + qCDebug(interfaceapp) << "Reading FBX file : " << _fbxInfo.filePath(); QByteArray fbxContents = fbx.readAll(); _geometry = readFBX(fbxContents, QVariantHash()); @@ -188,7 +189,7 @@ bool ModelPackager::zipModel() { fst.write(FSTReader::writeMapping(_mapping)); fst.close(); } else { - qDebug() << "Couldn't write FST file" << fst.fileName(); + qCDebug(interfaceapp) << "Couldn't write FST file" << fst.fileName(); return false; } @@ -196,7 +197,7 @@ bool ModelPackager::zipModel() { QString saveDirPath = QFileDialog::getExistingDirectory(nullptr, "Save Model", "", QFileDialog::ShowDirsOnly); if (saveDirPath.isEmpty()) { - qDebug() << "Invalid directory" << saveDirPath; + qCDebug(interfaceapp) << "Invalid directory" << saveDirPath; return false; } @@ -404,7 +405,7 @@ bool ModelPackager::copyTextures(const QString& oldDir, const QDir& newDir) { if (!errors.isEmpty()) { QMessageBox::warning(nullptr, "ModelPackager::copyTextures()", "Missing textures:" + errors); - qDebug() << "ModelPackager::copyTextures():" << errors; + qCDebug(interfaceapp) << "ModelPackager::copyTextures():" << errors; return false; } diff --git a/interface/src/ScriptsModel.cpp b/interface/src/ScriptsModel.cpp index 99b4111f0c..a59d499863 100644 --- a/interface/src/ScriptsModel.cpp +++ b/interface/src/ScriptsModel.cpp @@ -19,6 +19,7 @@ #include "Application.h" #include "Menu.h" +#include "InterfaceLogging.h" #include "ScriptsModel.h" @@ -181,7 +182,7 @@ void ScriptsModel::downloadFinished() { if (!data.isEmpty()) { finished = parseXML(data); } else { - qDebug() << "Error: Received no data when loading remote scripts"; + qCDebug(interfaceapp) << "Error: Received no data when loading remote scripts"; } } @@ -230,7 +231,7 @@ bool ScriptsModel::parseXML(QByteArray xmlFile) { // Error handling if (xml.hasError()) { - qDebug() << "Error loading remote scripts: " << xml.errorString(); + qCDebug(interfaceapp) << "Error loading remote scripts: " << xml.errorString(); return true; } diff --git a/interface/src/SpeechRecognizer.cpp b/interface/src/SpeechRecognizer.cpp index a83fdaac31..f5d0cb9e24 100644 --- a/interface/src/SpeechRecognizer.cpp +++ b/interface/src/SpeechRecognizer.cpp @@ -12,6 +12,7 @@ #include #include +#include "InterfaceLogging.h" #include "SpeechRecognizer.h" #if defined(Q_OS_WIN) @@ -139,13 +140,13 @@ void SpeechRecognizer::setEnabled(bool enabled) { _enabled = SUCCEEDED(hr); - qDebug() << "Speech recognition" << (_enabled ? "enabled" : "enable failed"); + qCDebug(interfaceapp) << "Speech recognition" << (_enabled ? "enabled" : "enable failed"); } else { _commandRecognizedNotifier->setEnabled(false); static_cast(_speechRecognizerContext)->Release(); static_cast(_speechRecognizer)->Release(); - qDebug() << "Speech recognition disabled"; + qCDebug(interfaceapp) << "Speech recognition disabled"; } emit enabledUpdated(_enabled); @@ -207,7 +208,7 @@ void SpeechRecognizer::reloadCommands() { } if (FAILED(hr)) { - qDebug() << "ERROR: Didn't successfully reload speech commands"; + qCDebug(interfaceapp) << "ERROR: Didn't successfully reload speech commands"; } } diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index da4ada2dc2..1f217d92b9 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -27,6 +27,7 @@ #include "InterfaceConfig.h" #include "world.h" #include "Application.h" +#include "InterfaceLogging.h" #include "Util.h" @@ -136,43 +137,43 @@ void runTimingTests() { float NSEC_TO_USEC = 1.0f / 1000.0f; elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; - qDebug("QElapsedTimer::nsecElapsed() usecs: %f", elapsedUsecs); + qCDebug(interfaceapp, "QElapsedTimer::nsecElapsed() usecs: %f", elapsedUsecs); // Test sleep functions for accuracy startTime.start(); QThread::msleep(1); elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; - qDebug("QThread::msleep(1) ms: %f", elapsedUsecs / 1000.0f); + qCDebug(interfaceapp, "QThread::msleep(1) ms: %f", elapsedUsecs / 1000.0f); startTime.start(); QThread::sleep(1); elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; - qDebug("QThread::sleep(1) ms: %f", elapsedUsecs / 1000.0f); + qCDebug(interfaceapp, "QThread::sleep(1) ms: %f", elapsedUsecs / 1000.0f); startTime.start(); usleep(1); elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; - qDebug("usleep(1) ms: %f", elapsedUsecs / 1000.0f); + qCDebug(interfaceapp, "usleep(1) ms: %f", elapsedUsecs / 1000.0f); startTime.start(); usleep(10); elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; - qDebug("usleep(10) ms: %f", elapsedUsecs / 1000.0f); + qCDebug(interfaceapp, "usleep(10) ms: %f", elapsedUsecs / 1000.0f); startTime.start(); usleep(100); elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; - qDebug("usleep(100) ms: %f", elapsedUsecs / 1000.0f); + qCDebug(interfaceapp, "usleep(100) ms: %f", elapsedUsecs / 1000.0f); startTime.start(); usleep(1000); elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; - qDebug("usleep(1000) ms: %f", elapsedUsecs / 1000.0f); + qCDebug(interfaceapp, "usleep(1000) ms: %f", elapsedUsecs / 1000.0f); startTime.start(); usleep(15000); elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; - qDebug("usleep(15000) ms: %f", elapsedUsecs / 1000.0f); + qCDebug(interfaceapp, "usleep(15000) ms: %f", elapsedUsecs / 1000.0f); // Random number generation startTime.start(); @@ -180,7 +181,7 @@ void runTimingTests() { iResults[i] = rand(); } elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; - qDebug("rand() stored in array usecs: %f, first result:%d", elapsedUsecs / (float) numTests, iResults[0]); + qCDebug(interfaceapp, "rand() stored in array usecs: %f, first result:%d", elapsedUsecs / (float) numTests, iResults[0]); // Random number generation using randFloat() startTime.start(); @@ -188,7 +189,7 @@ void runTimingTests() { fResults[i] = randFloat(); } elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; - qDebug("randFloat() stored in array usecs: %f, first result: %f", elapsedUsecs / (float) numTests, fResults[0]); + qCDebug(interfaceapp, "randFloat() stored in array usecs: %f, first result: %f", elapsedUsecs / (float) numTests, fResults[0]); free(iResults); free(fResults); @@ -200,7 +201,7 @@ void runTimingTests() { fTest = powf(fTest, 0.5f); } elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; - qDebug("powf(f, 0.5) usecs: %f", elapsedUsecs / (float) numTests); + qCDebug(interfaceapp, "powf(f, 0.5) usecs: %f", elapsedUsecs / (float) numTests); // Vector Math float distance; @@ -212,7 +213,7 @@ void runTimingTests() { distance = glm::distance(pointA, pointB); } elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; - qDebug("vector math usecs: %f [%f usecs total for %d tests], last result:%f", + qCDebug(interfaceapp, "vector math usecs: %f [%f usecs total for %d tests], last result:%f", elapsedUsecs / (float) numTests, elapsedUsecs, numTests, distance); // Vec3 test @@ -225,7 +226,7 @@ void runTimingTests() { result = glm::dot(temp,temp); } elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC; - qDebug("vec3 assign and dot() usecs: %f, last result:%f", elapsedUsecs / (float) numTests, result); + qCDebug(interfaceapp, "vec3 assign and dot() usecs: %f, last result:%f", elapsedUsecs / (float) numTests, result); } bool rayIntersectsSphere(const glm::vec3& rayStarting, const glm::vec3& rayNormalizedDirection, diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index cfce0bd80e..63dd884bc6 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -46,6 +46,7 @@ #include "Util.h" #include "world.h" #include "devices/OculusManager.h" +#include "InterfaceLogging.h" using namespace std; @@ -138,7 +139,7 @@ void Avatar::simulate(float deltaTime) { this); break; default: - qDebug() << "[WARNING] Avatar::simulate(): Unknown referential type."; + qCDebug(interfaceapp) << "[WARNING] Avatar::simulate(): Unknown referential type."; break; } } diff --git a/interface/src/avatar/ModelReferential.cpp b/interface/src/avatar/ModelReferential.cpp index b8acf78cd3..80e9098916 100644 --- a/interface/src/avatar/ModelReferential.cpp +++ b/interface/src/avatar/ModelReferential.cpp @@ -13,6 +13,7 @@ #include #include +#include "InterfaceLogging.h" #include "ModelReferential.h" ModelReferential::ModelReferential(Referential* referential, EntityTree* tree, AvatarData* avatar) : @@ -25,7 +26,7 @@ ModelReferential::ModelReferential(Referential* referential, EntityTree* tree, A referential->getExtraData().size()); if (!isValid()) { - qDebug() << "ModelReferential::copyConstructor(): Not Valid"; + qCDebug(interfaceapp) << "ModelReferential::copyConstructor(): Not Valid"; return; } @@ -45,7 +46,7 @@ ModelReferential::ModelReferential(const QUuid& entityID, EntityTree* tree, Avat { const EntityItem* item = _tree->findEntityByID(_entityID); if (!isValid() || item == NULL) { - qDebug() << "ModelReferential::constructor(): Not Valid"; + qCDebug(interfaceapp) << "ModelReferential::constructor(): Not Valid"; _isValid = false; return; } @@ -100,7 +101,7 @@ JointReferential::JointReferential(Referential* referential, EntityTree* tree, A { _type = JOINT; if (!isValid()) { - qDebug() << "JointReferential::copyConstructor(): Not Valid"; + qCDebug(interfaceapp) << "JointReferential::copyConstructor(): Not Valid"; return; } @@ -122,7 +123,7 @@ JointReferential::JointReferential(uint32_t jointIndex, const QUuid& entityID, E const EntityItem* item = _tree->findEntityByID(_entityID); const Model* model = getModel(item); if (!isValid() || model == NULL || _jointIndex >= (uint32_t)(model->getJointStateCount())) { - qDebug() << "JointReferential::constructor(): Not Valid"; + qCDebug(interfaceapp) << "JointReferential::constructor(): Not Valid"; _isValid = false; return; } diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 95aa42284a..e6048b86dc 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -43,6 +43,7 @@ #include "devices/Faceshift.h" #include "devices/OculusManager.h" #include "Util.h" +#include "InterfaceLogging.h" using namespace std; @@ -308,7 +309,7 @@ void MyAvatar::renderDebugBodyPoints() { glm::vec3 headPosition(getHead()->getEyePosition()); float torsoToHead = glm::length(headPosition - torsoPosition); glm::vec3 position; - qDebug("head-above-torso %.2f, scale = %0.2f", torsoToHead, getScale()); + qCDebug(interfaceapp, "head-above-torso %.2f, scale = %0.2f", torsoToHead, getScale()); // Torso Sphere position = torsoPosition; @@ -447,7 +448,7 @@ void MyAvatar::stopRecording() { void MyAvatar::saveRecording(QString filename) { if (!_recorder) { - qDebug() << "There is no recording to save"; + qCDebug(interfaceapp) << "There is no recording to save"; return; } if (QThread::currentThread() != thread()) { @@ -466,7 +467,7 @@ void MyAvatar::loadLastRecording() { return; } if (!_recorder) { - qDebug() << "There is no recording to load"; + qCDebug(interfaceapp) << "There is no recording to load"; return; } if (!_player) { @@ -780,7 +781,7 @@ AttachmentData MyAvatar::loadAttachmentData(const QUrl& modelURL, const QString& } int MyAvatar::parseDataAtOffset(const QByteArray& packet, int offset) { - qDebug() << "Error: ignoring update packet for MyAvatar" + qCDebug(interfaceapp) << "Error: ignoring update packet for MyAvatar" << " packetLength = " << packet.size() << " offset = " << offset; // this packet is just bad, so we pretend that we unpacked it ALL @@ -1330,33 +1331,33 @@ void MyAvatar::maybeUpdateBillboard() { void MyAvatar::increaseSize() { if ((1.0f + SCALING_RATIO) * _targetScale < MAX_AVATAR_SCALE) { _targetScale *= (1.0f + SCALING_RATIO); - qDebug("Changed scale to %f", _targetScale); + qCDebug(interfaceapp, "Changed scale to %f", _targetScale); } } void MyAvatar::decreaseSize() { if (MIN_AVATAR_SCALE < (1.0f - SCALING_RATIO) * _targetScale) { _targetScale *= (1.0f - SCALING_RATIO); - qDebug("Changed scale to %f", _targetScale); + qCDebug(interfaceapp, "Changed scale to %f", _targetScale); } } void MyAvatar::resetSize() { _targetScale = 1.0f; - qDebug("Reseted scale to %f", _targetScale); + qCDebug(interfaceapp, "Reseted scale to %f", _targetScale); } void MyAvatar::goToLocation(const glm::vec3& newPosition, bool hasOrientation, const glm::quat& newOrientation, bool shouldFaceLocation) { - qDebug().nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - moving to " << newPosition.x << ", " << newPosition.y << ", " << newPosition.z; glm::vec3 shiftedPosition = newPosition; if (hasOrientation) { - qDebug().nospace() << "MyAvatar goToLocation - new orientation is " + qCDebug(interfaceapp).nospace() << "MyAvatar goToLocation - new orientation is " << newOrientation.x << ", " << newOrientation.y << ", " << newOrientation.z << ", " << newOrientation.w; // orient the user to face the target diff --git a/interface/src/devices/DdeFaceTracker.cpp b/interface/src/devices/DdeFaceTracker.cpp index 9d753d228d..751739ed24 100644 --- a/interface/src/devices/DdeFaceTracker.cpp +++ b/interface/src/devices/DdeFaceTracker.cpp @@ -18,6 +18,8 @@ #include "DdeFaceTracker.h" #include "FaceshiftConstants.h" +#include "InterfaceLogging.h" + static const QHostAddress DDE_FEATURE_POINT_SERVER_ADDR("127.0.0.1"); static const quint16 DDE_FEATURE_POINT_SERVER_PORT = 5555; @@ -175,7 +177,7 @@ bool DdeFaceTracker::isActive() const { //private slots and methods void DdeFaceTracker::socketErrorOccurred(QAbstractSocket::SocketError socketError) { - qDebug() << "[Error] DDE Face Tracker Socket Error: " << _udpSocket.errorString(); + qCDebug(interfaceapp) << "[Error] DDE Face Tracker Socket Error: " << _udpSocket.errorString(); } void DdeFaceTracker::socketStateChanged(QAbstractSocket::SocketState socketState) { @@ -203,7 +205,7 @@ void DdeFaceTracker::socketStateChanged(QAbstractSocket::SocketState socketState state = "Unconnected"; break; } - qDebug() << "[Info] DDE Face Tracker Socket: " << state; + qCDebug(interfaceapp) << "[Info] DDE Face Tracker Socket: " << state; } void DdeFaceTracker::readPendingDatagrams() { @@ -297,7 +299,7 @@ void DdeFaceTracker::decodePacket(const QByteArray& buffer) { } } else { - qDebug() << "[Error] DDE Face Tracker Decode Error"; + qCDebug(interfaceapp) << "[Error] DDE Face Tracker Decode Error"; } _lastReceiveTimestamp = usecTimestampNow(); } diff --git a/interface/src/devices/Faceshift.cpp b/interface/src/devices/Faceshift.cpp index a2bb4e74a9..4768571bd2 100644 --- a/interface/src/devices/Faceshift.cpp +++ b/interface/src/devices/Faceshift.cpp @@ -18,6 +18,7 @@ #include "Faceshift.h" #include "Menu.h" #include "Util.h" +#include "InterfaceLogging.h" #ifdef HAVE_FACESHIFT using namespace fs; @@ -134,7 +135,7 @@ void Faceshift::setTCPEnabled(bool enabled) { void Faceshift::connectSocket() { if (_tcpEnabled) { if (!_tcpRetryCount) { - qDebug("Faceshift: Connecting..."); + qCDebug(interfaceapp, "Faceshift: Connecting..."); } _tcpSocket.connectToHost(_hostname.get(), FACESHIFT_PORT); @@ -144,7 +145,7 @@ void Faceshift::connectSocket() { void Faceshift::noteConnected() { #ifdef HAVE_FACESHIFT - qDebug("Faceshift: Connected."); + qCDebug(interfaceapp, "Faceshift: Connected."); // request the list of blendshape names string message; fsBinaryStream::encode_message(message, fsMsgSendBlendshapeNames()); @@ -155,7 +156,7 @@ void Faceshift::noteConnected() { void Faceshift::noteError(QAbstractSocket::SocketError error) { if (!_tcpRetryCount) { // Only spam log with fail to connect the first time, so that we can keep waiting for server - qDebug() << "Faceshift: " << _tcpSocket.errorString(); + qCDebug(interfaceapp) << "Faceshift: " << _tcpSocket.errorString(); } // retry connection after a 2 second delay if (_tcpEnabled) { diff --git a/interface/src/devices/MIDIManager.cpp b/interface/src/devices/MIDIManager.cpp index 54428d273d..a21f5d49f5 100644 --- a/interface/src/devices/MIDIManager.cpp +++ b/interface/src/devices/MIDIManager.cpp @@ -11,6 +11,7 @@ #include +#include "InterfaceLogging.h" #include "MIDIManager.h" MIDIManager& MIDIManager::getInstance() { @@ -54,7 +55,7 @@ void MIDIManager::openDefaultPort() { _midiInput = new RtMidiIn(); if (_midiInput->getPortCount() > 0) { - qDebug() << "MIDIManager opening port" << DEFAULT_MIDI_PORT; + qCDebug(interfaceapp) << "MIDIManager opening port" << DEFAULT_MIDI_PORT; _midiInput->openPort(DEFAULT_MIDI_PORT); @@ -63,10 +64,10 @@ void MIDIManager::openDefaultPort() { _midiInput->setCallback(&MIDIManager::midiCallback); } else { - qDebug() << "MIDIManager openDefaultPort called but there are no ports available."; + qCDebug(interfaceapp) << "MIDIManager openDefaultPort called but there are no ports available."; delete _midiInput; _midiInput = NULL; } } #endif -} \ No newline at end of file +} diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 5fbd0b6a0b..3f527c6137 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -32,6 +32,7 @@ #include +#include "InterfaceLogging.h" #include "Application.h" template @@ -128,7 +129,7 @@ void OculusManager::connect() { initSdk(); #endif _calibrationState = UNCALIBRATED; - qDebug() << "Oculus SDK" << OVR_VERSION_STRING; + qCDebug(interfaceapp) << "Oculus SDK" << OVR_VERSION_STRING; if (_ovrHmd) { if (!_isConnected) { UserActivityLogger::getInstance().connectedDevice("hmd", "oculus"); @@ -278,7 +279,7 @@ void OculusManager::calibrate(glm::vec3 position, glm::quat orientation) { _calibrationState = WAITING_FOR_ZERO_HELD; if (!_calibrationMessage) { - qDebug() << "Hold still to calibrate HMD"; + qCDebug(interfaceapp) << "Hold still to calibrate HMD"; billboard = new Text3DOverlay(); billboard->setDimensions(glm::vec2(2.0f, 1.25f)); @@ -305,7 +306,7 @@ void OculusManager::calibrate(glm::vec3 position, glm::quat orientation) { && glm::angle(orientation * glm::inverse(_calibrationOrientation)) < CALIBRATION_ZERO_MAXIMUM_ANGLE) { if ((usecTimestampNow() - _calibrationStartTime) > CALIBRATION_ZERO_HOLD_TIME) { _calibrationState = CALIBRATED; - qDebug() << "HMD calibrated"; + qCDebug(interfaceapp) << "HMD calibrated"; Application::getInstance()->getOverlays().deleteOverlay(_calibrationMessage); _calibrationMessage = NULL; Application::getInstance()->resetSensors(); @@ -346,7 +347,7 @@ void OculusManager::recalibrate() { void OculusManager::abandonCalibration() { _calibrationState = CALIBRATED; if (_calibrationMessage) { - qDebug() << "Abandoned HMD calibration"; + qCDebug(interfaceapp) << "Abandoned HMD calibration"; Application::getInstance()->getOverlays().deleteOverlay(_calibrationMessage); _calibrationMessage = NULL; } @@ -470,7 +471,7 @@ void OculusManager::display(const glm::quat &bodyOrientation, const glm::vec3 &p if (timerActive && timerQuery.isResultAvailable()) { auto result = timerQuery.waitForResult(); - if (result) { qDebug() << "Distortion took " << result << "ns"; }; + if (result) { qCDebug(interfaceapp) << "Distortion took " << result << "ns"; }; timerActive = false; } #endif @@ -683,7 +684,7 @@ void OculusManager::display(const glm::quat &bodyOrientation, const glm::vec3 &p if (nonZero) { - qDebug() << QString().sprintf("M2P Latency: Ren: %4.2fms TWrp: %4.2fms PostPresent: %4.2fms Err: %4.2fms %4.2fms", + qCDebug(interfaceapp) << QString().sprintf("M2P Latency: Ren: %4.2fms TWrp: %4.2fms PostPresent: %4.2fms Err: %4.2fms %4.2fms", latencies[0], latencies[1], latencies[2], latencies[3], latencies[4]); } } diff --git a/interface/src/devices/SixenseManager.cpp b/interface/src/devices/SixenseManager.cpp index 0a89ad0e37..2b85a0906f 100644 --- a/interface/src/devices/SixenseManager.cpp +++ b/interface/src/devices/SixenseManager.cpp @@ -18,6 +18,7 @@ #include "SixenseManager.h" #include "devices/OculusManager.h" #include "UserActivityLogger.h" +#include "InterfaceLogging.h" #ifdef HAVE_SIXENSE @@ -108,9 +109,9 @@ void SixenseManager::initialize() { } if (_sixenseLibrary->load()){ - qDebug() << "Loaded sixense library for hydra support -" << _sixenseLibrary->fileName(); + qCDebug(interfaceapp) << "Loaded sixense library for hydra support -" << _sixenseLibrary->fileName(); } else { - qDebug() << "Sixense library at" << _sixenseLibrary->fileName() << "failed to load." + qCDebug(interfaceapp) << "Sixense library at" << _sixenseLibrary->fileName() << "failed to load." << "Continuing without hydra support."; return; } @@ -206,7 +207,7 @@ void SixenseManager::update(float deltaTime) { hand->getPalms().push_back(newPalm); palm = &(hand->getPalms()[hand->getNumPalms() - 1]); palm->setSixenseID(data->controller_index); - qDebug("Found new Sixense controller, ID %i", data->controller_index); + qCDebug(interfaceapp, "Found new Sixense controller, ID %i", data->controller_index); } // Disable the hands (and return to default pose) if both controllers are at base station @@ -364,11 +365,11 @@ void SixenseManager::updateCalibration(const sixenseControllerData* controllers) glm::vec3 zAxis = glm::normalize(glm::cross(xAxis, yAxis)); xAxis = glm::normalize(glm::cross(yAxis, zAxis)); _orbRotation = glm::inverse(glm::quat_cast(glm::mat3(xAxis, yAxis, zAxis))); - qDebug("succeess: sixense calibration"); + qCDebug(interfaceapp, "succeess: sixense calibration"); } break; default: - qDebug("failed: sixense calibration"); + qCDebug(interfaceapp, "failed: sixense calibration"); break; } @@ -387,7 +388,7 @@ void SixenseManager::updateCalibration(const sixenseControllerData* controllers) if (_calibrationState == CALIBRATION_STATE_IDLE) { float reach = glm::distance(positionLeft, positionRight); if (reach > 2.0f * MINIMUM_ARM_REACH) { - qDebug("started: sixense calibration"); + qCDebug(interfaceapp, "started: sixense calibration"); _averageLeft = positionLeft; _averageRight = positionRight; _reachLeft = _averageLeft; @@ -420,7 +421,7 @@ void SixenseManager::updateCalibration(const sixenseControllerData* controllers) _lastDistance = 0.0f; _reachUp = 0.5f * (_reachLeft + _reachRight); _calibrationState = CALIBRATION_STATE_Y; - qDebug("success: sixense calibration: left"); + qCDebug(interfaceapp, "success: sixense calibration: left"); } } else if (_calibrationState == CALIBRATION_STATE_Y) { @@ -439,7 +440,7 @@ void SixenseManager::updateCalibration(const sixenseControllerData* controllers) _lastDistance = 0.0f; _lockExpiry = now + LOCK_DURATION; _calibrationState = CALIBRATION_STATE_Z; - qDebug("success: sixense calibration: up"); + qCDebug(interfaceapp, "success: sixense calibration: up"); } } } @@ -461,7 +462,7 @@ void SixenseManager::updateCalibration(const sixenseControllerData* controllers) if (fabs(_lastDistance) > 0.05f * MINIMUM_ARM_REACH) { // lock has expired so clamp the data and move on _calibrationState = CALIBRATION_STATE_COMPLETE; - qDebug("success: sixense calibration: forward"); + qCDebug(interfaceapp, "success: sixense calibration: forward"); // TODO: it is theoretically possible to detect that the controllers have been // accidentally switched (left hand is holding right controller) and to swap the order. } diff --git a/interface/src/main.cpp b/interface/src/main.cpp index 9ee8ab3aae..b4486ceb2b 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -19,6 +19,7 @@ #include "AddressManager.h" #include "Application.h" #include "devices/OculusManager.h" +#include "InterfaceLogging.h" #ifdef Q_OS_WIN static BOOL CALLBACK enumWindowsCallback(HWND hWnd, LPARAM lParam) { @@ -91,7 +92,7 @@ int main(int argc, const char* argv[]) { if (clockSkewOption) { int clockSkew = atoi(clockSkewOption); usecTimestampNowForceClockSkew(clockSkew); - qDebug("clockSkewOption=%s clockSkew=%d", clockSkewOption, clockSkew); + qCDebug(interfaceapp, "clockSkewOption=%s clockSkew=%d", clockSkewOption, clockSkew); } // Oculus initialization MUST PRECEDE OpenGL context creation. // The nature of the Application constructor means this has to be either here, @@ -107,7 +108,7 @@ int main(int argc, const char* argv[]) { translator.load("interface_en"); app.installTranslator(&translator); - qDebug( "Created QT Application."); + qCDebug(interfaceapp, "Created QT Application."); exitCode = app.exec(); } @@ -115,6 +116,6 @@ int main(int argc, const char* argv[]) { ReleaseMutex(mutex); #endif - qDebug("Normal exit."); + qCDebug(interfaceapp, "Normal exit."); return exitCode; } diff --git a/interface/src/starfield/Controller.cpp b/interface/src/starfield/Controller.cpp index 2279a68422..d0d46adbdc 100644 --- a/interface/src/starfield/Controller.cpp +++ b/interface/src/starfield/Controller.cpp @@ -11,6 +11,7 @@ #include +#include "InterfaceLogging.h" #include "starfield/Controller.h" using namespace starfield; @@ -25,7 +26,7 @@ bool Controller::computeStars(unsigned numStars, unsigned seed) { double NSEC_TO_MSEC = 1.0 / 1000000.0; double timeDiff = (double)startTime.nsecsElapsed() * NSEC_TO_MSEC; - qDebug() << "Total time to retile and generate stars: " << timeDiff << "msec"; + qCDebug(interfaceapp) << "Total time to retile and generate stars: " << timeDiff << "msec"; return true; } diff --git a/interface/src/ui/ApplicationOverlay.cpp b/interface/src/ui/ApplicationOverlay.cpp index 633eafc202..f08df229cc 100644 --- a/interface/src/ui/ApplicationOverlay.cpp +++ b/interface/src/ui/ApplicationOverlay.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include @@ -28,8 +29,6 @@ #include "Util.h" #include "ui/Stats.h" -// Used to fade the UI -const float FADE_SPEED = 0.08f; // Used to animate the magnification windows const float MAG_SPEED = 0.08f; @@ -428,15 +427,18 @@ void ApplicationOverlay::displayOverlayTexture3DTV(Camera& whichCamera, float as } void ApplicationOverlay::computeOculusPickRay(float x, float y, glm::vec3& origin, glm::vec3& direction) const { + const MyAvatar* myAvatar = DependencyManager::get()->getMyAvatar(); const float pitch = (0.5f - y) * MOUSE_PITCH_RANGE; const float yaw = (0.5f - x) * MOUSE_YAW_RANGE; const glm::quat orientation(glm::vec3(pitch, yaw, 0.0f)); const glm::vec3 localDirection = orientation * IDENTITY_FRONT; - //Rotate the UI pick ray by the avatar orientation - const MyAvatar* myAvatar = DependencyManager::get()->getMyAvatar(); - origin = myAvatar->getDefaultEyePosition(); - direction = myAvatar->getOrientation() * localDirection; + // Get cursor position + const glm::vec3 cursorPos = myAvatar->getDefaultEyePosition() + myAvatar->getOrientation() * localDirection; + + // Ray start where the eye position is and stop where the cursor is + origin = myAvatar->getEyePosition(); + direction = cursorPos - origin; } //Caculate the click location using one of the sixense controllers. Scale is not applied @@ -500,10 +502,10 @@ QPoint ApplicationOverlay::getPalmClickLocation(const PalmData *palm) const { bool ApplicationOverlay::calculateRayUICollisionPoint(const glm::vec3& position, const glm::vec3& direction, glm::vec3& result) const { MyAvatar* myAvatar = DependencyManager::get()->getMyAvatar(); - glm::quat orientation = myAvatar->getOrientation(); + glm::quat inverseOrientation = glm::inverse(myAvatar->getOrientation()); - glm::vec3 relativePosition = orientation * (position - myAvatar->getDefaultEyePosition()); - glm::vec3 relativeDirection = orientation * direction; + glm::vec3 relativePosition = inverseOrientation * (position - myAvatar->getDefaultEyePosition()); + glm::vec3 relativeDirection = glm::normalize(inverseOrientation * direction); float t; if (raySphereIntersect(relativeDirection, relativePosition, _oculusUIRadius * myAvatar->getScale(), &t)){ @@ -514,8 +516,6 @@ bool ApplicationOverlay::calculateRayUICollisionPoint(const glm::vec3& position, return false; } - - //Renders optional pointers void ApplicationOverlay::renderPointers() { auto glCanvas = Application::getInstance()->getGLWidget(); @@ -540,12 +540,23 @@ void ApplicationOverlay::renderPointers() { if (_reticlePosition[MOUSE] != position) { _lastMouseMove = usecTimestampNow(); } else if (usecTimestampNow() - _lastMouseMove > MAX_IDLE_TIME * USECS_PER_SECOND) { - float pitch, yaw, roll; + float pitch = 0.0f, yaw = 0.0f, roll = 0.0f; // radians OculusManager::getEulerAngles(yaw, pitch, roll); - glm::vec2 screenPos = sphericalToScreen(glm::vec2(yaw, -pitch)); + glm::quat orientation(glm::vec3(pitch, yaw, roll)); + glm::vec3 result; - position = QPoint(screenPos.x, screenPos.y); - glCanvas->cursor().setPos(glCanvas->mapToGlobal(position)); + MyAvatar* myAvatar = DependencyManager::get()->getMyAvatar(); + if (calculateRayUICollisionPoint(myAvatar->getEyePosition(), + myAvatar->getOrientation() * orientation * IDENTITY_FRONT, + result)) { + glm::vec3 lookAtDirection = glm::inverse(myAvatar->getOrientation()) * (result - myAvatar->getDefaultEyePosition()); + glm::vec2 spericalPos = directionToSpherical(glm::normalize(lookAtDirection)); + glm::vec2 screenPos = sphericalToScreen(spericalPos); + position = QPoint(screenPos.x, screenPos.y); + glCanvas->cursor().setPos(glCanvas->mapToGlobal(position)); + } else { + qDebug() << "No collision point"; + } } _reticlePosition[MOUSE] = position; @@ -1126,6 +1137,26 @@ void ApplicationOverlay::TexturedHemisphere::render() { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } +glm::vec2 ApplicationOverlay::directionToSpherical(glm::vec3 direction) const { + glm::vec2 result; + // Compute yaw + glm::vec3 normalProjection = glm::normalize(glm::vec3(direction.x, 0.0f, direction.z)); + result.x = glm::acos(glm::dot(IDENTITY_FRONT, normalProjection)); + if (glm::dot(IDENTITY_RIGHT, normalProjection) > 0.0f) { + result.x = -glm::abs(result.x); + } else { + result.x = glm::abs(result.x); + } + // Compute pitch + result.y = angleBetween(IDENTITY_UP, direction) - PI_OVER_TWO; + + return result; +} + +glm::vec3 ApplicationOverlay::sphericalToDirection(glm::vec2 sphericalPos) const { + glm::quat rotation(glm::vec3(sphericalPos.y, sphericalPos.x, 0.0f)); + return rotation * IDENTITY_FRONT; +} glm::vec2 ApplicationOverlay::screenToSpherical(glm::vec2 screenPos) const { QSize screenSize = Application::getInstance()->getGLWidget()->getDeviceSize(); diff --git a/interface/src/ui/ApplicationOverlay.h b/interface/src/ui/ApplicationOverlay.h index 58b79adcda..cc424d0c8f 100644 --- a/interface/src/ui/ApplicationOverlay.h +++ b/interface/src/ui/ApplicationOverlay.h @@ -45,11 +45,14 @@ public: // Converter from one frame of reference to another. // Frame of reference: + // Direction: Ray that represents the spherical values // Screen: Position on the screen (x,y) // Spherical: Pitch and yaw that gives the position on the sphere we project on (yaw,pitch) // Overlay: Position on the overlay (x,y) // (x,y) in Overlay are similar than (x,y) in Screen except they can be outside of the bound of te screen. // This allows for picking outside of the screen projection in 3D. + glm::vec2 directionToSpherical(glm::vec3 direction) const; + glm::vec3 sphericalToDirection(glm::vec2 sphericalPos) const; glm::vec2 screenToSpherical(glm::vec2 screenPos) const; glm::vec2 sphericalToScreen(glm::vec2 sphericalPos) const; glm::vec2 sphericalToOverlay(glm::vec2 sphericalPos) const; diff --git a/libraries/audio-client/src/AudioClient.cpp b/libraries/audio-client/src/AudioClient.cpp index 94470f48e4..a02dc912f7 100644 --- a/libraries/audio-client/src/AudioClient.cpp +++ b/libraries/audio-client/src/AudioClient.cpp @@ -50,6 +50,7 @@ extern "C" { #include "AudioInjector.h" #include "AudioConstants.h" #include "PositionalAudioStream.h" +#include "AudioClientLogging.h" #include "AudioClient.h" @@ -240,7 +241,7 @@ QAudioDeviceInfo defaultAudioDeviceForMode(QAudio::Mode mode) { waveInGetDevCaps(WAVE_MAPPER, &wic, sizeof(wic)); //Use the received manufacturer id to get the device's real name waveInGetDevCaps(wic.wMid, &wic, sizeof(wic)); - qDebug() << "input device:" << wic.szPname; + qCDebug(audioclient) << "input device:" << wic.szPname; deviceName = wic.szPname; } else { WAVEOUTCAPS woc; @@ -248,7 +249,7 @@ QAudioDeviceInfo defaultAudioDeviceForMode(QAudio::Mode mode) { waveOutGetDevCaps(WAVE_MAPPER, &woc, sizeof(woc)); //Use the received manufacturer id to get the device's real name waveOutGetDevCaps(woc.wMid, &woc, sizeof(woc)); - qDebug() << "output device:" << woc.szPname; + qCDebug(audioclient) << "output device:" << woc.szPname; deviceName = woc.szPname; } } else { @@ -277,7 +278,7 @@ QAudioDeviceInfo defaultAudioDeviceForMode(QAudio::Mode mode) { const DWORD QT_WIN7_MAX_AUDIO_DEVICENAME_LEN = 31; deviceName = deviceName.left(QT_WIN7_MAX_AUDIO_DEVICENAME_LEN); } - qDebug() << (mode == QAudio::AudioOutput ? "output" : "input") << " device:" << deviceName; + qCDebug(audioclient) << (mode == QAudio::AudioOutput ? "output" : "input") << " device:" << deviceName; PropVariantClear(&pv); } pMMDeviceEnumerator->Release(); @@ -285,7 +286,7 @@ QAudioDeviceInfo defaultAudioDeviceForMode(QAudio::Mode mode) { CoUninitialize(); } - qDebug() << "DEBUG [" << deviceName << "] [" << getNamedAudioDeviceForMode(mode, deviceName).deviceName() << "]"; + qCDebug(audioclient) << "DEBUG [" << deviceName << "] [" << getNamedAudioDeviceForMode(mode, deviceName).deviceName() << "]"; return getNamedAudioDeviceForMode(mode, deviceName); #endif @@ -299,8 +300,8 @@ bool adjustedFormatForAudioDevice(const QAudioDeviceInfo& audioDevice, const QAudioFormat& desiredAudioFormat, QAudioFormat& adjustedAudioFormat) { if (!audioDevice.isFormatSupported(desiredAudioFormat)) { - qDebug() << "The desired format for audio I/O is" << desiredAudioFormat; - qDebug("The desired audio format is not supported by this device"); + qCDebug(audioclient) << "The desired format for audio I/O is" << desiredAudioFormat; + qCDebug(audioclient, "The desired audio format is not supported by this device"); if (desiredAudioFormat.channelCount() == 1) { adjustedAudioFormat = desiredAudioFormat; @@ -445,7 +446,7 @@ soxr_t soxrResamplerFromInputFormatToOutputFormat(const QAudioFormat& sourceAudi &soxrError, &inputToNetworkSpec, &qualitySpec, 0); if (soxrError) { - qDebug() << "There was an error setting up the soxr resampler -" << "soxr error code was " << soxrError; + qCDebug(audioclient) << "There was an error setting up the soxr resampler -" << "soxr error code was " << soxrError; soxr_delete(newResampler); @@ -469,20 +470,20 @@ void AudioClient::start() { _desiredOutputFormat.setChannelCount(2); QAudioDeviceInfo inputDeviceInfo = defaultAudioDeviceForMode(QAudio::AudioInput); - qDebug() << "The default audio input device is" << inputDeviceInfo.deviceName(); + qCDebug(audioclient) << "The default audio input device is" << inputDeviceInfo.deviceName(); bool inputFormatSupported = switchInputToAudioDevice(inputDeviceInfo); QAudioDeviceInfo outputDeviceInfo = defaultAudioDeviceForMode(QAudio::AudioOutput); - qDebug() << "The default audio output device is" << outputDeviceInfo.deviceName(); + qCDebug(audioclient) << "The default audio output device is" << outputDeviceInfo.deviceName(); bool outputFormatSupported = switchOutputToAudioDevice(outputDeviceInfo); if (!inputFormatSupported) { - qDebug() << "Unable to set up audio input because of a problem with input format."; - qDebug() << "The closest format available is" << inputDeviceInfo.nearestFormat(_desiredInputFormat); + qCDebug(audioclient) << "Unable to set up audio input because of a problem with input format."; + qCDebug(audioclient) << "The closest format available is" << inputDeviceInfo.nearestFormat(_desiredInputFormat); } if (!outputFormatSupported) { - qDebug() << "Unable to set up audio output because of a problem with output format."; - qDebug() << "The closest format available is" << outputDeviceInfo.nearestFormat(_desiredOutputFormat); + qCDebug(audioclient) << "Unable to set up audio output because of a problem with output format."; + qCDebug(audioclient) << "The closest format available is" << outputDeviceInfo.nearestFormat(_desiredOutputFormat); } if (_audioInput) { @@ -527,12 +528,12 @@ QVector AudioClient::getDeviceNames(QAudio::Mode mode) { } bool AudioClient::switchInputToAudioDevice(const QString& inputDeviceName) { - qDebug() << "DEBUG [" << inputDeviceName << "] [" << getNamedAudioDeviceForMode(QAudio::AudioInput, inputDeviceName).deviceName() << "]"; + qCDebug(audioclient) << "DEBUG [" << inputDeviceName << "] [" << getNamedAudioDeviceForMode(QAudio::AudioInput, inputDeviceName).deviceName() << "]"; return switchInputToAudioDevice(getNamedAudioDeviceForMode(QAudio::AudioInput, inputDeviceName)); } bool AudioClient::switchOutputToAudioDevice(const QString& outputDeviceName) { - qDebug() << "DEBUG [" << outputDeviceName << "] [" << getNamedAudioDeviceForMode(QAudio::AudioOutput, outputDeviceName).deviceName() << "]"; + qCDebug(audioclient) << "DEBUG [" << outputDeviceName << "] [" << getNamedAudioDeviceForMode(QAudio::AudioOutput, outputDeviceName).deviceName() << "]"; return switchOutputToAudioDevice(getNamedAudioDeviceForMode(QAudio::AudioOutput, outputDeviceName)); } @@ -674,7 +675,7 @@ void AudioClient::handleLocalEchoAndReverb(QByteArray& inputByteArray) { // do we need to setup a resampler? if (_inputFormat.sampleRate() != _outputFormat.sampleRate() && !_loopbackResampler) { - qDebug() << "Attemping to create a resampler for input format to output format for audio loopback."; + qCDebug(audioclient) << "Attemping to create a resampler for input format to output format for audio loopback."; _loopbackResampler = soxrResamplerFromInputFormatToOutputFormat(_inputFormat, _outputFormat); if (!_loopbackResampler) { @@ -1003,7 +1004,7 @@ bool AudioClient::outputLocalInjector(bool isStereo, qreal volume, AudioInjector connect(injector->getLocalBuffer(), &AudioInjectorLocalBuffer::bufferEmpty, localOutput, &QAudioOutput::stop); connect(injector->getLocalBuffer(), &QIODevice::aboutToClose, localOutput, &QAudioOutput::stop); - qDebug() << "Starting QAudioOutput for local injector" << localOutput; + qCDebug(audioclient) << "Starting QAudioOutput for local injector" << localOutput; localOutput->start(injector->getLocalBuffer()); return localOutput->state() == QAudio::ActiveState; @@ -1043,24 +1044,24 @@ bool AudioClient::switchInputToAudioDevice(const QAudioDeviceInfo& inputDeviceIn } if (!inputDeviceInfo.isNull()) { - qDebug() << "The audio input device " << inputDeviceInfo.deviceName() << "is available."; + qCDebug(audioclient) << "The audio input device " << inputDeviceInfo.deviceName() << "is available."; _inputAudioDeviceName = inputDeviceInfo.deviceName().trimmed(); if (adjustedFormatForAudioDevice(inputDeviceInfo, _desiredInputFormat, _inputFormat)) { - qDebug() << "The format to be used for audio input is" << _inputFormat; + qCDebug(audioclient) << "The format to be used for audio input is" << _inputFormat; // we've got the best we can get for input // if required, setup a soxr resampler for this input to our desired network format if (_inputFormat != _desiredInputFormat && _inputFormat.sampleRate() != _desiredInputFormat.sampleRate()) { - qDebug() << "Attemping to create a soxr resampler for input format to network format."; + qCDebug(audioclient) << "Attemping to create a soxr resampler for input format to network format."; _inputToNetworkResampler = soxrResamplerFromInputFormatToOutputFormat(_inputFormat, _desiredInputFormat); if (!_inputToNetworkResampler) { return false; } } else { - qDebug() << "No resampling required for audio input to match desired network format."; + qCDebug(audioclient) << "No resampling required for audio input to match desired network format."; } // if the user wants stereo but this device can't provide then bail @@ -1079,7 +1080,7 @@ bool AudioClient::switchInputToAudioDevice(const QAudioDeviceInfo& inputDeviceIn connect(_inputDevice, SIGNAL(readyRead()), this, SLOT(handleAudioInput())); supportedFormat = true; } else { - qDebug() << "Error starting audio input -" << _audioInput->error(); + qCDebug(audioclient) << "Error starting audio input -" << _audioInput->error(); } } } @@ -1108,7 +1109,7 @@ void AudioClient::outputNotify() { setOutputBufferSize(newOutputBufferSizeFrames); newOutputBufferSizeFrames = _outputBufferSizeFrames.get(); if (newOutputBufferSizeFrames > oldOutputBufferSizeFrames) { - qDebug() << "Starve detection threshold met, increasing buffer size to " << newOutputBufferSizeFrames; + qCDebug(audioclient) << "Starve detection threshold met, increasing buffer size to " << newOutputBufferSizeFrames; } } } @@ -1144,24 +1145,24 @@ bool AudioClient::switchOutputToAudioDevice(const QAudioDeviceInfo& outputDevice } if (!outputDeviceInfo.isNull()) { - qDebug() << "The audio output device " << outputDeviceInfo.deviceName() << "is available."; + qCDebug(audioclient) << "The audio output device " << outputDeviceInfo.deviceName() << "is available."; _outputAudioDeviceName = outputDeviceInfo.deviceName().trimmed(); if (adjustedFormatForAudioDevice(outputDeviceInfo, _desiredOutputFormat, _outputFormat)) { - qDebug() << "The format to be used for audio output is" << _outputFormat; + qCDebug(audioclient) << "The format to be used for audio output is" << _outputFormat; // we've got the best we can get for input // if required, setup a soxr resampler for this input to our desired network format if (_desiredOutputFormat != _outputFormat && _desiredOutputFormat.sampleRate() != _outputFormat.sampleRate()) { - qDebug() << "Attemping to create a resampler for network format to output format."; + qCDebug(audioclient) << "Attemping to create a resampler for network format to output format."; _networkToOutputResampler = soxrResamplerFromInputFormatToOutputFormat(_desiredOutputFormat, _outputFormat); if (!_networkToOutputResampler) { return false; } } else { - qDebug() << "No resampling required for network output to match actual output format."; + qCDebug(audioclient) << "No resampling required for network output to match actual output format."; } outputFormatChanged(); @@ -1172,7 +1173,7 @@ bool AudioClient::switchOutputToAudioDevice(const QAudioDeviceInfo& outputDevice connect(_audioOutput, &QAudioOutput::notify, this, &AudioClient::outputNotify); - qDebug() << "Output Buffer capacity in frames: " << _audioOutput->bufferSize() / sizeof(int16_t) / (float)_outputFrameSize; + qCDebug(audioclient) << "Output Buffer capacity in frames: " << _audioOutput->bufferSize() / sizeof(int16_t) / (float)_outputFrameSize; _audioOutputIODevice.start(); _audioOutput->start(&_audioOutputIODevice); @@ -1193,7 +1194,7 @@ bool AudioClient::switchOutputToAudioDevice(const QAudioDeviceInfo& outputDevice void AudioClient::setOutputBufferSize(int numFrames) { numFrames = std::min(std::max(numFrames, MIN_AUDIO_OUTPUT_BUFFER_SIZE_FRAMES), MAX_AUDIO_OUTPUT_BUFFER_SIZE_FRAMES); if (numFrames != _outputBufferSizeFrames.get()) { - qDebug() << "Audio output buffer size (frames): " << numFrames; + qCDebug(audioclient) << "Audio output buffer size (frames): " << numFrames; _outputBufferSizeFrames.set(numFrames); if (_audioOutput) { diff --git a/libraries/audio-client/src/AudioClientLogging.cpp b/libraries/audio-client/src/AudioClientLogging.cpp new file mode 100644 index 0000000000..f497e84c4c --- /dev/null +++ b/libraries/audio-client/src/AudioClientLogging.cpp @@ -0,0 +1,14 @@ +// +// AudioClientLogging.cpp +// libraries/audio-client/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "AudioClientLogging.h" + +Q_LOGGING_CATEGORY(audioclient, "hifi.audioclient") diff --git a/libraries/audio-client/src/AudioClientLogging.h b/libraries/audio-client/src/AudioClientLogging.h new file mode 100644 index 0000000000..462f8108ac --- /dev/null +++ b/libraries/audio-client/src/AudioClientLogging.h @@ -0,0 +1,20 @@ +// +// AudioClientLogging.h +// libraries/audio-client/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_AudioClientLogging_h +#define hifi_AudioClientLogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(audioclient) + +#endif // hifi_AudioClientLogging_h + diff --git a/libraries/audio/src/AudioInjector.cpp b/libraries/audio/src/AudioInjector.cpp index 9981e0fba7..95db7e6d0b 100644 --- a/libraries/audio/src/AudioInjector.cpp +++ b/libraries/audio/src/AudioInjector.cpp @@ -19,6 +19,7 @@ #include "AbstractAudioInterface.h" #include "AudioRingBuffer.h" +#include "AudioLogging.h" #include "AudioInjector.h" @@ -58,7 +59,7 @@ void AudioInjector::setIsFinished(bool isFinished) { if (_shouldDeleteAfterFinish) { // we've been asked to delete after finishing, trigger a queued deleteLater here - qDebug() << "AudioInjector triggering delete from setIsFinished"; + qCDebug(audio) << "AudioInjector triggering delete from setIsFinished"; QMetaObject::invokeMethod(this, "deleteLater", Qt::QueuedConnection); } } @@ -84,12 +85,12 @@ void AudioInjector::injectAudio() { injectToMixer(); } } else { - qDebug() << "AudioInjector::injectAudio called but already started."; + qCDebug(audio) << "AudioInjector::injectAudio called but already started."; } } void AudioInjector::restart() { - qDebug() << "Restarting an AudioInjector by stopping and starting over."; + qCDebug(audio) << "Restarting an AudioInjector by stopping and starting over."; stop(); setIsFinished(false); QMetaObject::invokeMethod(this, "injectAudio", Qt::QueuedConnection); @@ -114,14 +115,14 @@ void AudioInjector::injectLocally() { connect(_localBuffer, &AudioInjectorLocalBuffer::bufferEmpty, this, &AudioInjector::stop); if (!success) { - qDebug() << "AudioInjector::injectLocally could not output locally via _localAudioInterface"; + qCDebug(audio) << "AudioInjector::injectLocally could not output locally via _localAudioInterface"; } } else { - qDebug() << "AudioInjector::injectLocally called without any data in Sound QByteArray"; + qCDebug(audio) << "AudioInjector::injectLocally called without any data in Sound QByteArray"; } } else { - qDebug() << "AudioInjector::injectLocally cannot inject locally with no local audio interface present."; + qCDebug(audio) << "AudioInjector::injectLocally cannot inject locally with no local audio interface present."; } if (!success) { diff --git a/libraries/audio/src/AudioLogging.cpp b/libraries/audio/src/AudioLogging.cpp new file mode 100644 index 0000000000..f01b8ce846 --- /dev/null +++ b/libraries/audio/src/AudioLogging.cpp @@ -0,0 +1,14 @@ +// +// AudioLogging.cpp +// libraries/audio/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "AudioLogging.h" + +Q_LOGGING_CATEGORY(audio, "hifi.audio") diff --git a/libraries/audio/src/AudioLogging.h b/libraries/audio/src/AudioLogging.h new file mode 100644 index 0000000000..c15e53be41 --- /dev/null +++ b/libraries/audio/src/AudioLogging.h @@ -0,0 +1,19 @@ +// +// AudioLogging.h +// libraries/audio/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_AudioLogging_h +#define hifi_AudioLogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(audio) + +#endif // hifi_AudioLogging_h diff --git a/libraries/audio/src/AudioRingBuffer.cpp b/libraries/audio/src/AudioRingBuffer.cpp index 31a09dd93e..9231601ec6 100644 --- a/libraries/audio/src/AudioRingBuffer.cpp +++ b/libraries/audio/src/AudioRingBuffer.cpp @@ -17,6 +17,8 @@ #include +#include "AudioLogging.h" + #include "AudioRingBuffer.h" AudioRingBuffer::AudioRingBuffer(int numFrameSamples, bool randomAccessMode, int numFramesCapacity) : @@ -126,7 +128,7 @@ int AudioRingBuffer::writeData(const char* data, int maxSize) { int samplesToDelete = samplesToCopy - samplesRoomFor; _nextOutput = shiftedPositionAccomodatingWrap(_nextOutput, samplesToDelete); _overflowCount++; - qDebug() << "Overflowed ring buffer! Overwriting old data"; + qCDebug(audio) << "Overflowed ring buffer! Overwriting old data"; } if (_endOfLastWrite + samplesToCopy <= _buffer + _bufferLength) { @@ -172,7 +174,7 @@ int AudioRingBuffer::addSilentSamples(int silentSamples) { if (silentSamples > samplesRoomFor) { // there's not enough room for this write. write as many silent samples as we have room for silentSamples = samplesRoomFor; - qDebug() << "Dropping some silent samples to prevent ring buffer overflow"; + qCDebug(audio) << "Dropping some silent samples to prevent ring buffer overflow"; } // memset zeroes into the buffer, accomodate a wrap around the end @@ -236,7 +238,7 @@ int AudioRingBuffer::writeSamples(ConstIterator source, int maxSamples) { int samplesToDelete = samplesToCopy - samplesRoomFor; _nextOutput = shiftedPositionAccomodatingWrap(_nextOutput, samplesToDelete); _overflowCount++; - qDebug() << "Overflowed ring buffer! Overwriting old data"; + qCDebug(audio) << "Overflowed ring buffer! Overwriting old data"; } int16_t* bufferLast = _buffer + _bufferLength - 1; @@ -257,7 +259,7 @@ int AudioRingBuffer::writeSamplesWithFade(ConstIterator source, int maxSamples, int samplesToDelete = samplesToCopy - samplesRoomFor; _nextOutput = shiftedPositionAccomodatingWrap(_nextOutput, samplesToDelete); _overflowCount++; - qDebug() << "Overflowed ring buffer! Overwriting old data"; + qCDebug(audio) << "Overflowed ring buffer! Overwriting old data"; } int16_t* bufferLast = _buffer + _bufferLength - 1; diff --git a/libraries/audio/src/Sound.cpp b/libraries/audio/src/Sound.cpp index 834c6a531f..577328ee18 100644 --- a/libraries/audio/src/Sound.cpp +++ b/libraries/audio/src/Sound.cpp @@ -27,6 +27,7 @@ #include "AudioFormat.h" #include "AudioBuffer.h" #include "AudioEditBuffer.h" +#include "AudioLogging.h" #include "Sound.h" static int soundMetaTypeId = qRegisterMetaType(); @@ -77,7 +78,7 @@ void Sound::downloadFinished(QNetworkReply* reply) { // since it's raw the only way for us to know that is if the file was called .stereo.raw if (reply->url().fileName().toLower().endsWith("stereo.raw")) { _isStereo = true; - qDebug() << "Processing sound of" << rawAudioByteArray.size() << "bytes from" << reply->url() << "as stereo audio file."; + qCDebug(audio) << "Processing sound of" << rawAudioByteArray.size() << "bytes from" << reply->url() << "as stereo audio file."; } // Process as RAW file @@ -85,7 +86,7 @@ void Sound::downloadFinished(QNetworkReply* reply) { } trimFrames(); } else { - qDebug() << "Network reply without 'Content-Type'."; + qCDebug(audio) << "Network reply without 'Content-Type'."; } _isReady = true; @@ -216,34 +217,34 @@ void Sound::interpretAsWav(const QByteArray& inputAudioByteArray, QByteArray& ou } else { // descriptor.id == "RIFX" also signifies BigEndian file // waveStream.setByteOrder(QDataStream::BigEndian); - qDebug() << "Currently not supporting big-endian audio files."; + qCDebug(audio) << "Currently not supporting big-endian audio files."; return; } if (strncmp(fileHeader.riff.type, "WAVE", 4) != 0 || strncmp(fileHeader.wave.descriptor.id, "fmt", 3) != 0) { - qDebug() << "Not a WAVE Audio file."; + qCDebug(audio) << "Not a WAVE Audio file."; return; } // added the endianess check as an extra level of security if (qFromLittleEndian(fileHeader.wave.audioFormat) != 1) { - qDebug() << "Currently not supporting non PCM audio files."; + qCDebug(audio) << "Currently not supporting non PCM audio files."; return; } if (qFromLittleEndian(fileHeader.wave.numChannels) == 2) { _isStereo = true; } else if (qFromLittleEndian(fileHeader.wave.numChannels) > 2) { - qDebug() << "Currently not support audio files with more than 2 channels."; + qCDebug(audio) << "Currently not support audio files with more than 2 channels."; } if (qFromLittleEndian(fileHeader.wave.bitsPerSample) != 16) { - qDebug() << "Currently not supporting non 16bit audio files."; + qCDebug(audio) << "Currently not supporting non 16bit audio files."; return; } if (qFromLittleEndian(fileHeader.wave.sampleRate) != 48000) { - qDebug() << "Currently not supporting non 48KHz audio files."; + qCDebug(audio) << "Currently not supporting non 48KHz audio files."; return; } @@ -260,7 +261,7 @@ void Sound::interpretAsWav(const QByteArray& inputAudioByteArray, QByteArray& ou } waveStream.skipRawData(dataHeader.descriptor.size); } else { - qDebug() << "Could not read wav audio data header."; + qCDebug(audio) << "Could not read wav audio data header."; return; } } @@ -269,11 +270,11 @@ void Sound::interpretAsWav(const QByteArray& inputAudioByteArray, QByteArray& ou quint32 outputAudioByteArraySize = qFromLittleEndian(dataHeader.descriptor.size); outputAudioByteArray.resize(outputAudioByteArraySize); if (waveStream.readRawData(outputAudioByteArray.data(), outputAudioByteArraySize) != (int)outputAudioByteArraySize) { - qDebug() << "Error reading WAV file"; + qCDebug(audio) << "Error reading WAV file"; } } else { - qDebug() << "Could not read wav audio file header."; + qCDebug(audio) << "Could not read wav audio file header."; return; } } diff --git a/libraries/audio/src/SoundCache.cpp b/libraries/audio/src/SoundCache.cpp index 2949a6c70a..a7af1bdda2 100644 --- a/libraries/audio/src/SoundCache.cpp +++ b/libraries/audio/src/SoundCache.cpp @@ -11,6 +11,7 @@ #include +#include "AudioLogging.h" #include "SoundCache.h" static int soundPointerMetaTypeId = qRegisterMetaType(); @@ -34,6 +35,6 @@ SharedSoundPointer SoundCache::getSound(const QUrl& url) { QSharedPointer SoundCache::createResource(const QUrl& url, const QSharedPointer& fallback, bool delayLoad, const void* extra) { - qDebug() << "Requesting sound at" << url.toString(); + qCDebug(audio) << "Requesting sound at" << url.toString(); return QSharedPointer(new Sound(url), &Resource::allReferencesCleared); -} \ No newline at end of file +} diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index 6d7395754c..bc49fb3514 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -26,6 +26,7 @@ #include #include +#include "AvatarLogging.h" #include "AvatarData.h" quint64 DEFAULT_FILTERED_LOG_EXPIRY = 2 * USECS_PER_SECOND; @@ -118,7 +119,7 @@ void AvatarData::setClampedTargetScale(float targetScale, bool overideReferentia targetScale = glm::clamp(targetScale, MIN_AVATAR_SCALE, MAX_AVATAR_SCALE); setTargetScale(targetScale, overideReferential); - qDebug() << "Changed scale to " << _targetScale; + qCDebug(avatars) << "Changed scale to " << _targetScale; } glm::vec3 AvatarData::getHandPosition() const { @@ -304,7 +305,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { int maxAvailableSize = packet.size() - offset; if (minPossibleSize > maxAvailableSize) { if (shouldLogError(now)) { - qDebug() << "Malformed AvatarData packet at the start; " + qCDebug(avatars) << "Malformed AvatarData packet at the start; " << " displayName = '" << _displayName << "'" << " minPossibleSize = " << minPossibleSize << " maxAvailableSize = " << maxAvailableSize; @@ -321,7 +322,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { if (glm::isnan(position.x) || glm::isnan(position.y) || glm::isnan(position.z)) { if (shouldLogError(now)) { - qDebug() << "Discard nan AvatarData::position; displayName = '" << _displayName << "'"; + qCDebug(avatars) << "Discard nan AvatarData::position; displayName = '" << _displayName << "'"; } return maxAvailableSize; } @@ -334,7 +335,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { sourceBuffer += unpackFloatAngleFromTwoByte((uint16_t*) sourceBuffer, &roll); if (glm::isnan(yaw) || glm::isnan(pitch) || glm::isnan(roll)) { if (shouldLogError(now)) { - qDebug() << "Discard nan AvatarData::yaw,pitch,roll; displayName = '" << _displayName << "'"; + qCDebug(avatars) << "Discard nan AvatarData::yaw,pitch,roll; displayName = '" << _displayName << "'"; } return maxAvailableSize; } @@ -350,7 +351,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { sourceBuffer += unpackFloatRatioFromTwoByte(sourceBuffer, scale); if (glm::isnan(scale)) { if (shouldLogError(now)) { - qDebug() << "Discard nan AvatarData::scale; displayName = '" << _displayName << "'"; + qCDebug(avatars) << "Discard nan AvatarData::scale; displayName = '" << _displayName << "'"; } return maxAvailableSize; } @@ -365,7 +366,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { sourceBuffer += unpackFloatAngleFromTwoByte((uint16_t*) sourceBuffer, &headRoll); if (glm::isnan(headYaw) || glm::isnan(headPitch) || glm::isnan(headRoll)) { if (shouldLogError(now)) { - qDebug() << "Discard nan AvatarData::headYaw,headPitch,headRoll; displayName = '" << _displayName << "'"; + qCDebug(avatars) << "Discard nan AvatarData::headYaw,headPitch,headRoll; displayName = '" << _displayName << "'"; } return maxAvailableSize; } @@ -380,7 +381,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { sourceBuffer += sizeof(lookAt); if (glm::isnan(lookAt.x) || glm::isnan(lookAt.y) || glm::isnan(lookAt.z)) { if (shouldLogError(now)) { - qDebug() << "Discard nan AvatarData::lookAt; displayName = '" << _displayName << "'"; + qCDebug(avatars) << "Discard nan AvatarData::lookAt; displayName = '" << _displayName << "'"; } return maxAvailableSize; } @@ -394,7 +395,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { sourceBuffer += sizeof(float); if (glm::isnan(audioLoudness)) { if (shouldLogError(now)) { - qDebug() << "Discard nan AvatarData::audioLoudness; displayName = '" << _displayName << "'"; + qCDebug(avatars) << "Discard nan AvatarData::audioLoudness; displayName = '" << _displayName << "'"; } return maxAvailableSize; } @@ -441,7 +442,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { minPossibleSize++; // one byte for blendDataSize if (minPossibleSize > maxAvailableSize) { if (shouldLogError(now)) { - qDebug() << "Malformed AvatarData packet after BitItems;" + qCDebug(avatars) << "Malformed AvatarData packet after BitItems;" << " displayName = '" << _displayName << "'" << " minPossibleSize = " << minPossibleSize << " maxAvailableSize = " << maxAvailableSize; @@ -464,7 +465,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { if (glm::isnan(leftEyeBlink) || glm::isnan(rightEyeBlink) || glm::isnan(averageLoudness) || glm::isnan(browAudioLift)) { if (shouldLogError(now)) { - qDebug() << "Discard nan AvatarData::faceData; displayName = '" << _displayName << "'"; + qCDebug(avatars) << "Discard nan AvatarData::faceData; displayName = '" << _displayName << "'"; } return maxAvailableSize; } @@ -478,7 +479,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { minPossibleSize += blendDataSize; if (minPossibleSize > maxAvailableSize) { if (shouldLogError(now)) { - qDebug() << "Malformed AvatarData packet after Blendshapes;" + qCDebug(avatars) << "Malformed AvatarData packet after Blendshapes;" << " displayName = '" << _displayName << "'" << " minPossibleSize = " << minPossibleSize << " maxAvailableSize = " << maxAvailableSize; @@ -504,7 +505,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { minPossibleSize += bytesOfValidity; if (minPossibleSize > maxAvailableSize) { if (shouldLogError(now)) { - qDebug() << "Malformed AvatarData packet after JointValidityBits;" + qCDebug(avatars) << "Malformed AvatarData packet after JointValidityBits;" << " displayName = '" << _displayName << "'" << " minPossibleSize = " << minPossibleSize << " maxAvailableSize = " << maxAvailableSize; @@ -535,7 +536,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { minPossibleSize += numValidJoints * COMPONENTS_PER_QUATERNION * sizeof(uint16_t); if (minPossibleSize > maxAvailableSize) { if (shouldLogError(now)) { - qDebug() << "Malformed AvatarData packet after JointData;" + qCDebug(avatars) << "Malformed AvatarData packet after JointData;" << " displayName = '" << _displayName << "'" << " minPossibleSize = " << minPossibleSize << " maxAvailableSize = " << maxAvailableSize; @@ -915,13 +916,13 @@ bool AvatarData::hasBillboardChangedAfterParsing(const QByteArray& packet) { void AvatarData::setFaceModelURL(const QUrl& faceModelURL) { _faceModelURL = faceModelURL; - qDebug() << "Changing face model for avatar to" << _faceModelURL.toString(); + qCDebug(avatars) << "Changing face model for avatar to" << _faceModelURL.toString(); } void AvatarData::setSkeletonModelURL(const QUrl& skeletonModelURL) { _skeletonModelURL = skeletonModelURL.isEmpty() ? DEFAULT_BODY_MODEL_URL : skeletonModelURL; - qDebug() << "Changing skeleton model for avatar to" << _skeletonModelURL.toString(); + qCDebug(avatars) << "Changing skeleton model for avatar to" << _skeletonModelURL.toString(); updateJointMappings(); } @@ -929,7 +930,7 @@ void AvatarData::setSkeletonModelURL(const QUrl& skeletonModelURL) { void AvatarData::setDisplayName(const QString& displayName) { _displayName = displayName; - qDebug() << "Changing display name for avatar to" << displayName; + qCDebug(avatars) << "Changing display name for avatar to" << displayName; } QVector AvatarData::getAttachmentData() const { @@ -1010,14 +1011,14 @@ void AvatarData::detachAll(const QString& modelURL, const QString& jointName) { void AvatarData::setBillboard(const QByteArray& billboard) { _billboard = billboard; - qDebug() << "Changing billboard for avatar."; + qCDebug(avatars) << "Changing billboard for avatar."; } void AvatarData::setBillboardFromURL(const QString &billboardURL) { _billboardURL = billboardURL; - qDebug() << "Changing billboard for avatar to PNG at" << qPrintable(billboardURL); + qCDebug(avatars) << "Changing billboard for avatar to PNG at" << qPrintable(billboardURL); QNetworkRequest billboardRequest; billboardRequest.setHeader(QNetworkRequest::UserAgentHeader, HIGH_FIDELITY_USER_AGENT); diff --git a/libraries/avatars/src/AvatarHashMap.cpp b/libraries/avatars/src/AvatarHashMap.cpp index 7af13269f0..ae3a8c3e5c 100644 --- a/libraries/avatars/src/AvatarHashMap.cpp +++ b/libraries/avatars/src/AvatarHashMap.cpp @@ -12,6 +12,7 @@ #include #include +#include "AvatarLogging.h" #include "AvatarHashMap.h" AvatarHashMap::AvatarHashMap() { @@ -20,7 +21,7 @@ AvatarHashMap::AvatarHashMap() { AvatarHash::iterator AvatarHashMap::erase(const AvatarHash::iterator& iterator) { - qDebug() << "Removing Avatar with UUID" << iterator.key() << "from AvatarHashMap."; + qCDebug(avatars) << "Removing Avatar with UUID" << iterator.key() << "from AvatarHashMap."; return _avatarHash.erase(iterator); } @@ -84,7 +85,7 @@ AvatarSharedPointer AvatarHashMap::matchingOrNewAvatar(const QUuid& sessionUUID, // insert the new avatar into our hash matchingAvatar = newSharedAvatar(); - qDebug() << "Adding avatar with sessionUUID " << sessionUUID << "to AvatarHashMap."; + qCDebug(avatars) << "Adding avatar with sessionUUID " << sessionUUID << "to AvatarHashMap."; matchingAvatar->setSessionUUID(sessionUUID); matchingAvatar->setOwningAvatarMixer(mixerWeakPointer); @@ -180,4 +181,4 @@ void AvatarHashMap::processKillAvatar(const QByteArray& datagram) { void AvatarHashMap::sessionUUIDChanged(const QUuid& sessionUUID, const QUuid& oldUUID) { _lastOwnerSessionUUID = oldUUID; -} \ No newline at end of file +} diff --git a/libraries/avatars/src/AvatarLogging.cpp b/libraries/avatars/src/AvatarLogging.cpp new file mode 100644 index 0000000000..86a6327beb --- /dev/null +++ b/libraries/avatars/src/AvatarLogging.cpp @@ -0,0 +1,14 @@ +// +// AvatarLogging.cpp +// libraries/avatars/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "AvatarLogging.h" + +Q_LOGGING_CATEGORY(avatars, "hifi.avatars") diff --git a/libraries/avatars/src/AvatarLogging.h b/libraries/avatars/src/AvatarLogging.h new file mode 100644 index 0000000000..698a59fcdf --- /dev/null +++ b/libraries/avatars/src/AvatarLogging.h @@ -0,0 +1,20 @@ +// +// AvatarLogging.h +// libraries/avatars/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_AvatarLogging_h +#define hifi_AvatarLogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(avatars) + +#endif // hifi_AvatarLogging_h + diff --git a/libraries/avatars/src/Player.cpp b/libraries/avatars/src/Player.cpp index b5cca61461..d3f33ca7c8 100644 --- a/libraries/avatars/src/Player.cpp +++ b/libraries/avatars/src/Player.cpp @@ -15,6 +15,7 @@ #include #include "AvatarData.h" +#include "AvatarLogging.h" #include "Player.h" static const int INVALID_FRAME = -1; @@ -90,35 +91,35 @@ void Player::startPlaying() { bool wantDebug = false; if (wantDebug) { - qDebug() << "Player::startPlaying(): Recording Context"; - qDebug() << "Domain:" << _currentContext.domain; - qDebug() << "Position:" << _currentContext.position; - qDebug() << "Orientation:" << _currentContext.orientation; - qDebug() << "Scale:" << _currentContext.scale; - qDebug() << "Head URL:" << _currentContext.headModel; - qDebug() << "Skeleton URL:" << _currentContext.skeletonModel; - qDebug() << "Display Name:" << _currentContext.displayName; - qDebug() << "Num Attachments:" << _currentContext.attachments.size(); + qCDebug(avatars) << "Player::startPlaying(): Recording Context"; + qCDebug(avatars) << "Domain:" << _currentContext.domain; + qCDebug(avatars) << "Position:" << _currentContext.position; + qCDebug(avatars) << "Orientation:" << _currentContext.orientation; + qCDebug(avatars) << "Scale:" << _currentContext.scale; + qCDebug(avatars) << "Head URL:" << _currentContext.headModel; + qCDebug(avatars) << "Skeleton URL:" << _currentContext.skeletonModel; + qCDebug(avatars) << "Display Name:" << _currentContext.displayName; + qCDebug(avatars) << "Num Attachments:" << _currentContext.attachments.size(); for (int i = 0; i < _currentContext.attachments.size(); ++i) { - qDebug() << "Model URL:" << _currentContext.attachments[i].modelURL; - qDebug() << "Joint Name:" << _currentContext.attachments[i].jointName; - qDebug() << "Translation:" << _currentContext.attachments[i].translation; - qDebug() << "Rotation:" << _currentContext.attachments[i].rotation; - qDebug() << "Scale:" << _currentContext.attachments[i].scale; + qCDebug(avatars) << "Model URL:" << _currentContext.attachments[i].modelURL; + qCDebug(avatars) << "Joint Name:" << _currentContext.attachments[i].jointName; + qCDebug(avatars) << "Translation:" << _currentContext.attachments[i].translation; + qCDebug(avatars) << "Rotation:" << _currentContext.attachments[i].rotation; + qCDebug(avatars) << "Scale:" << _currentContext.attachments[i].scale; } } // Fake faceshift connection _avatar->setForceFaceTrackerConnected(true); - qDebug() << "Recorder::startPlaying()"; + qCDebug(avatars) << "Recorder::startPlaying()"; setupAudioThread(); _currentFrame = 0; _timerOffset = 0; _timer.start(); } else { - qDebug() << "Recorder::startPlaying(): Unpause"; + qCDebug(avatars) << "Recorder::startPlaying(): Unpause"; setupAudioThread(); _timer.start(); @@ -152,7 +153,7 @@ void Player::stopPlaying() { _avatar->setSkeletonModelURL(_currentContext.skeletonModel); } - qDebug() << "Recorder::stopPlaying()"; + qCDebug(avatars) << "Recorder::stopPlaying()"; } void Player::pausePlayer() { @@ -161,7 +162,7 @@ void Player::pausePlayer() { cleanupAudioThread(); _pausedFrame = _currentFrame; - qDebug() << "Recorder::pausePlayer()"; + qCDebug(avatars) << "Recorder::pausePlayer()"; } void Player::setupAudioThread() { @@ -292,7 +293,7 @@ void Player::play() { _frameInterpolationFactor); head->setLookAtPosition(context->position + context->orientation * lookAt); } else { - qDebug() << "WARNING: Player couldn't find head data."; + qCDebug(avatars) << "WARNING: Player couldn't find head data."; } _options.position = _avatar->getPosition(); @@ -359,7 +360,7 @@ void Player::setVolume(float volume) { if (_injector) { _injector->setOptions(_options); } - qDebug() << "New volume: " << volume; + qCDebug(avatars) << "New volume: " << volume; } void Player::setAudioOffset(int audioOffset) { @@ -410,7 +411,7 @@ bool Player::computeCurrentFrame() { if (_frameInterpolationFactor < 0.0f || _frameInterpolationFactor > 1.0f) { _frameInterpolationFactor = 0.0f; - qDebug() << "Invalid frame interpolation value: overriding"; + qCDebug(avatars) << "Invalid frame interpolation value: overriding"; } return true; } diff --git a/libraries/avatars/src/Recorder.cpp b/libraries/avatars/src/Recorder.cpp index 364afb9211..8a90500f00 100644 --- a/libraries/avatars/src/Recorder.cpp +++ b/libraries/avatars/src/Recorder.cpp @@ -15,6 +15,7 @@ #include #include "AvatarData.h" +#include "AvatarLogging.h" #include "Recorder.h" Recorder::Recorder(AvatarData* avatar) : @@ -37,7 +38,7 @@ qint64 Recorder::elapsed() const { } void Recorder::startRecording() { - qDebug() << "Recorder::startRecording()"; + qCDebug(avatars) << "Recorder::startRecording()"; _recording->clear(); RecordingContext& context = _recording->getContext(); @@ -55,23 +56,23 @@ void Recorder::startRecording() { bool wantDebug = false; if (wantDebug) { - qDebug() << "Recorder::startRecording(): Recording Context"; - qDebug() << "Global timestamp:" << context.globalTimestamp; - qDebug() << "Domain:" << context.domain; - qDebug() << "Position:" << context.position; - qDebug() << "Orientation:" << context.orientation; - qDebug() << "Scale:" << context.scale; - qDebug() << "Head URL:" << context.headModel; - qDebug() << "Skeleton URL:" << context.skeletonModel; - qDebug() << "Display Name:" << context.displayName; - qDebug() << "Num Attachments:" << context.attachments.size(); + qCDebug(avatars) << "Recorder::startRecording(): Recording Context"; + qCDebug(avatars) << "Global timestamp:" << context.globalTimestamp; + qCDebug(avatars) << "Domain:" << context.domain; + qCDebug(avatars) << "Position:" << context.position; + qCDebug(avatars) << "Orientation:" << context.orientation; + qCDebug(avatars) << "Scale:" << context.scale; + qCDebug(avatars) << "Head URL:" << context.headModel; + qCDebug(avatars) << "Skeleton URL:" << context.skeletonModel; + qCDebug(avatars) << "Display Name:" << context.displayName; + qCDebug(avatars) << "Num Attachments:" << context.attachments.size(); for (int i = 0; i < context.attachments.size(); ++i) { - qDebug() << "Model URL:" << context.attachments[i].modelURL; - qDebug() << "Joint Name:" << context.attachments[i].jointName; - qDebug() << "Translation:" << context.attachments[i].translation; - qDebug() << "Rotation:" << context.attachments[i].rotation; - qDebug() << "Scale:" << context.attachments[i].scale; + qCDebug(avatars) << "Model URL:" << context.attachments[i].modelURL; + qCDebug(avatars) << "Joint Name:" << context.attachments[i].jointName; + qCDebug(avatars) << "Translation:" << context.attachments[i].translation; + qCDebug(avatars) << "Rotation:" << context.attachments[i].rotation; + qCDebug(avatars) << "Scale:" << context.attachments[i].scale; } } @@ -80,15 +81,15 @@ void Recorder::startRecording() { } void Recorder::stopRecording() { - qDebug() << "Recorder::stopRecording()"; + qCDebug(avatars) << "Recorder::stopRecording()"; _timer.invalidate(); - qDebug().nospace() << "Recorded " << _recording->getFrameNumber() << " during " << _recording->getLength() << " msec (" << _recording->getFrameNumber() / (_recording->getLength() / 1000.0f) << " fps)"; + qCDebug(avatars).nospace() << "Recorded " << _recording->getFrameNumber() << " during " << _recording->getLength() << " msec (" << _recording->getFrameNumber() / (_recording->getLength() / 1000.0f) << " fps)"; } void Recorder::saveToFile(const QString& file) { if (_recording->isEmpty()) { - qDebug() << "Cannot save recording to file, recording is empty."; + qCDebug(avatars) << "Cannot save recording to file, recording is empty."; } writeRecordingToFile(_recording, file); @@ -120,16 +121,16 @@ void Recorder::record() { bool wantDebug = false; if (wantDebug) { - qDebug() << "Recording frame #" << _recording->getFrameNumber(); - qDebug() << "Blendshapes:" << frame.getBlendshapeCoefficients().size(); - qDebug() << "JointRotations:" << frame.getJointRotations().size(); - qDebug() << "Translation:" << frame.getTranslation(); - qDebug() << "Rotation:" << frame.getRotation(); - qDebug() << "Scale:" << frame.getScale(); - qDebug() << "Head rotation:" << frame.getHeadRotation(); - qDebug() << "Lean Forward:" << frame.getLeanForward(); - qDebug() << "Lean Sideways:" << frame.getLeanSideways(); - qDebug() << "LookAtPosition:" << frame.getLookAtPosition(); + qCDebug(avatars) << "Recording frame #" << _recording->getFrameNumber(); + qCDebug(avatars) << "Blendshapes:" << frame.getBlendshapeCoefficients().size(); + qCDebug(avatars) << "JointRotations:" << frame.getJointRotations().size(); + qCDebug(avatars) << "Translation:" << frame.getTranslation(); + qCDebug(avatars) << "Rotation:" << frame.getRotation(); + qCDebug(avatars) << "Scale:" << frame.getScale(); + qCDebug(avatars) << "Head rotation:" << frame.getHeadRotation(); + qCDebug(avatars) << "Lean Forward:" << frame.getLeanForward(); + qCDebug(avatars) << "Lean Sideways:" << frame.getLeanSideways(); + qCDebug(avatars) << "LookAtPosition:" << frame.getLookAtPosition(); } _recording->addFrame(_timer.elapsed(), frame); diff --git a/libraries/avatars/src/Recording.cpp b/libraries/avatars/src/Recording.cpp index 6901e5e10d..ce0855462b 100644 --- a/libraries/avatars/src/Recording.cpp +++ b/libraries/avatars/src/Recording.cpp @@ -24,6 +24,7 @@ #include #include "AvatarData.h" +#include "AvatarLogging.h" #include "Recording.h" // HFR file format magic number (Inspired by PNG) @@ -128,18 +129,18 @@ bool readFloat(QDataStream& stream, float& value, int radix) { void writeRecordingToFile(RecordingPointer recording, const QString& filename) { if (!recording || recording->getFrameNumber() < 1) { - qDebug() << "Can't save empty recording"; + qCDebug(avatars) << "Can't save empty recording"; return; } QElapsedTimer timer; QFile file(filename); if (!file.open(QIODevice::ReadWrite | QIODevice::Truncate)){ - qDebug() << "Couldn't open " << filename; + qCDebug(avatars) << "Couldn't open " << filename; return; } timer.start(); - qDebug() << "Writing recording to " << filename << "."; + qCDebug(avatars) << "Writing recording to " << filename << "."; QDataStream fileStream(&file); @@ -333,38 +334,38 @@ void writeRecordingToFile(RecordingPointer recording, const QString& filename) { bool wantDebug = true; if (wantDebug) { - qDebug() << "[DEBUG] WRITE recording"; - qDebug() << "Header:"; - qDebug() << "File Format version:" << VERSION; - qDebug() << "Data length:" << dataLength; - qDebug() << "Data offset:" << dataOffset; - qDebug() << "CRC-16:" << crc16; + qCDebug(avatars) << "[DEBUG] WRITE recording"; + qCDebug(avatars) << "Header:"; + qCDebug(avatars) << "File Format version:" << VERSION; + qCDebug(avatars) << "Data length:" << dataLength; + qCDebug(avatars) << "Data offset:" << dataOffset; + qCDebug(avatars) << "CRC-16:" << crc16; - qDebug() << "Context block:"; - qDebug() << "Global timestamp:" << context.globalTimestamp; - qDebug() << "Domain:" << context.domain; - qDebug() << "Position:" << context.position; - qDebug() << "Orientation:" << context.orientation; - qDebug() << "Scale:" << context.scale; - qDebug() << "Head Model:" << context.headModel; - qDebug() << "Skeleton Model:" << context.skeletonModel; - qDebug() << "Display Name:" << context.displayName; - qDebug() << "Num Attachments:" << context.attachments.size(); + qCDebug(avatars) << "Context block:"; + qCDebug(avatars) << "Global timestamp:" << context.globalTimestamp; + qCDebug(avatars) << "Domain:" << context.domain; + qCDebug(avatars) << "Position:" << context.position; + qCDebug(avatars) << "Orientation:" << context.orientation; + qCDebug(avatars) << "Scale:" << context.scale; + qCDebug(avatars) << "Head Model:" << context.headModel; + qCDebug(avatars) << "Skeleton Model:" << context.skeletonModel; + qCDebug(avatars) << "Display Name:" << context.displayName; + qCDebug(avatars) << "Num Attachments:" << context.attachments.size(); for (int i = 0; i < context.attachments.size(); ++i) { - qDebug() << "Model URL:" << context.attachments[i].modelURL; - qDebug() << "Joint Name:" << context.attachments[i].jointName; - qDebug() << "Translation:" << context.attachments[i].translation; - qDebug() << "Rotation:" << context.attachments[i].rotation; - qDebug() << "Scale:" << context.attachments[i].scale; + qCDebug(avatars) << "Model URL:" << context.attachments[i].modelURL; + qCDebug(avatars) << "Joint Name:" << context.attachments[i].jointName; + qCDebug(avatars) << "Translation:" << context.attachments[i].translation; + qCDebug(avatars) << "Rotation:" << context.attachments[i].rotation; + qCDebug(avatars) << "Scale:" << context.attachments[i].scale; } - qDebug() << "Recording:"; - qDebug() << "Total frames:" << recording->getFrameNumber(); - qDebug() << "Audio array:" << recording->getAudioData().size(); + qCDebug(avatars) << "Recording:"; + qCDebug(avatars) << "Total frames:" << recording->getFrameNumber(); + qCDebug(avatars) << "Audio array:" << recording->getAudioData().size(); } qint64 checksumTime = timer.elapsed(); - qDebug() << "Wrote" << file.size() << "bytes in" << writingTime + checksumTime << "ms. (" << checksumTime << "ms for checksum)"; + qCDebug(avatars) << "Wrote" << file.size() << "bytes in" << writingTime + checksumTime << "ms. (" << checksumTime << "ms for checksum)"; } RecordingPointer readRecordingFromFile(RecordingPointer recording, const QString& filename) { @@ -377,7 +378,7 @@ RecordingPointer readRecordingFromFile(RecordingPointer recording, const QString // Return if data unavailable if (url.scheme() == "http" || url.scheme() == "https" || url.scheme() == "ftp") { // Download file if necessary - qDebug() << "Downloading recording at" << url; + qCDebug(avatars) << "Downloading recording at" << url; QNetworkAccessManager& networkAccessManager = NetworkAccessManager::getInstance(); QNetworkRequest networkRequest = QNetworkRequest(url); networkRequest.setHeader(QNetworkRequest::UserAgentHeader, HIGH_FIDELITY_USER_AGENT); @@ -386,20 +387,20 @@ RecordingPointer readRecordingFromFile(RecordingPointer recording, const QString QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); // wait for file if (reply->error() != QNetworkReply::NoError) { - qDebug() << "Error while downloading recording: " << reply->error(); + qCDebug(avatars) << "Error while downloading recording: " << reply->error(); reply->deleteLater(); return recording; } byteArray = reply->readAll(); reply->deleteLater(); // print debug + restart timer - qDebug() << "Downloaded " << byteArray.size() << " bytes in " << timer.restart() << " ms."; + qCDebug(avatars) << "Downloaded " << byteArray.size() << " bytes in " << timer.restart() << " ms."; } else { // If local file, just read it. - qDebug() << "Reading recording from " << filename << "."; + qCDebug(avatars) << "Reading recording from " << filename << "."; QFile file(filename); if (!file.open(QIODevice::ReadOnly)){ - qDebug() << "Could not open local file: " << url; + qCDebug(avatars) << "Could not open local file: " << url; return recording; } byteArray = file.readAll(); @@ -407,11 +408,11 @@ RecordingPointer readRecordingFromFile(RecordingPointer recording, const QString } if (filename.endsWith(".rec") || filename.endsWith(".REC")) { - qDebug() << "Old .rec format"; + qCDebug(avatars) << "Old .rec format"; readRecordingFromRecFile(recording, filename, byteArray); return recording; } else if (!filename.endsWith(".hfr") && !filename.endsWith(".HFR")) { - qDebug() << "File extension not recognized"; + qCDebug(avatars) << "File extension not recognized"; } // Reset the recording passed in the arguments @@ -424,7 +425,7 @@ RecordingPointer readRecordingFromFile(RecordingPointer recording, const QString // HEADER QByteArray magicNumber(MAGIC_NUMBER, MAGIC_NUMBER_SIZE); if (!byteArray.startsWith(magicNumber)) { - qDebug() << "ERROR: This is not a .HFR file. (Magic Number incorrect)"; + qCDebug(avatars) << "ERROR: This is not a .HFR file. (Magic Number incorrect)"; return recording; } fileStream.skipRawData(MAGIC_NUMBER_SIZE); @@ -432,7 +433,7 @@ RecordingPointer readRecordingFromFile(RecordingPointer recording, const QString QPair version; fileStream >> version; // File format version if (version != VERSION && version != QPair(0,1)) { - qDebug() << "ERROR: This file format version is not supported."; + qCDebug(avatars) << "ERROR: This file format version is not supported."; return recording; } @@ -447,7 +448,7 @@ RecordingPointer readRecordingFromFile(RecordingPointer recording, const QString // Check checksum quint16 computedCRC16 = qChecksum(byteArray.constData() + dataOffset, dataLength); if (computedCRC16 != crc16) { - qDebug() << "Checksum does not match. Bailling!"; + qCDebug(avatars) << "Checksum does not match. Bailling!"; recording.clear(); return recording; } @@ -465,13 +466,13 @@ RecordingPointer readRecordingFromFile(RecordingPointer recording, const QString fileStream >> context.domain; // Position if (!readVec3(fileStream, context.position)) { - qDebug() << "Couldn't read file correctly. (Invalid vec3)"; + qCDebug(avatars) << "Couldn't read file correctly. (Invalid vec3)"; recording.clear(); return recording; } // Orientation if (!readQuat(fileStream, context.orientation)) { - qDebug() << "Couldn't read file correctly. (Invalid quat)"; + qCDebug(avatars) << "Couldn't read file correctly. (Invalid quat)"; recording.clear(); return recording; } @@ -502,12 +503,12 @@ RecordingPointer readRecordingFromFile(RecordingPointer recording, const QString fileStream >> data.jointName; // Translation if (!readVec3(fileStream, data.translation)) { - qDebug() << "Couldn't read attachment correctly. (Invalid vec3)"; + qCDebug(avatars) << "Couldn't read attachment correctly. (Invalid vec3)"; continue; } // Rotation if (!readQuat(fileStream, data.rotation)) { - qDebug() << "Couldn't read attachment correctly. (Invalid quat)"; + qCDebug(avatars) << "Couldn't read attachment correctly. (Invalid quat)"; continue; } @@ -610,38 +611,38 @@ RecordingPointer readRecordingFromFile(RecordingPointer recording, const QString bool wantDebug = true; if (wantDebug) { - qDebug() << "[DEBUG] READ recording"; - qDebug() << "Header:"; - qDebug() << "File Format version:" << VERSION; - qDebug() << "Data length:" << dataLength; - qDebug() << "Data offset:" << dataOffset; - qDebug() << "CRC-16:" << crc16; + qCDebug(avatars) << "[DEBUG] READ recording"; + qCDebug(avatars) << "Header:"; + qCDebug(avatars) << "File Format version:" << VERSION; + qCDebug(avatars) << "Data length:" << dataLength; + qCDebug(avatars) << "Data offset:" << dataOffset; + qCDebug(avatars) << "CRC-16:" << crc16; - qDebug() << "Context block:"; - qDebug() << "Global timestamp:" << context.globalTimestamp; - qDebug() << "Domain:" << context.domain; - qDebug() << "Position:" << context.position; - qDebug() << "Orientation:" << context.orientation; - qDebug() << "Scale:" << context.scale; - qDebug() << "Head Model:" << context.headModel; - qDebug() << "Skeleton Model:" << context.skeletonModel; - qDebug() << "Display Name:" << context.displayName; - qDebug() << "Num Attachments:" << numAttachments; + qCDebug(avatars) << "Context block:"; + qCDebug(avatars) << "Global timestamp:" << context.globalTimestamp; + qCDebug(avatars) << "Domain:" << context.domain; + qCDebug(avatars) << "Position:" << context.position; + qCDebug(avatars) << "Orientation:" << context.orientation; + qCDebug(avatars) << "Scale:" << context.scale; + qCDebug(avatars) << "Head Model:" << context.headModel; + qCDebug(avatars) << "Skeleton Model:" << context.skeletonModel; + qCDebug(avatars) << "Display Name:" << context.displayName; + qCDebug(avatars) << "Num Attachments:" << numAttachments; for (int i = 0; i < numAttachments; ++i) { - qDebug() << "Model URL:" << context.attachments[i].modelURL; - qDebug() << "Joint Name:" << context.attachments[i].jointName; - qDebug() << "Translation:" << context.attachments[i].translation; - qDebug() << "Rotation:" << context.attachments[i].rotation; - qDebug() << "Scale:" << context.attachments[i].scale; + qCDebug(avatars) << "Model URL:" << context.attachments[i].modelURL; + qCDebug(avatars) << "Joint Name:" << context.attachments[i].jointName; + qCDebug(avatars) << "Translation:" << context.attachments[i].translation; + qCDebug(avatars) << "Rotation:" << context.attachments[i].rotation; + qCDebug(avatars) << "Scale:" << context.attachments[i].scale; } - qDebug() << "Recording:"; - qDebug() << "Total frames:" << recording->getFrameNumber(); - qDebug() << "Audio array:" << recording->getAudioData().size(); + qCDebug(avatars) << "Recording:"; + qCDebug(avatars) << "Total frames:" << recording->getFrameNumber(); + qCDebug(avatars) << "Audio array:" << recording->getAudioData().size(); } - qDebug() << "Read " << byteArray.size() << " bytes in " << timer.elapsed() << " ms."; + qCDebug(avatars) << "Read " << byteArray.size() << " bytes in " << timer.elapsed() << " ms."; return recording; } @@ -787,7 +788,7 @@ RecordingPointer readRecordingFromRecFile(RecordingPointer recording, const QStr recording->addAudioPacket(audioArray); - qDebug() << "Read " << byteArray.size() << " bytes in " << timer.elapsed() << " ms."; + qCDebug(avatars) << "Read " << byteArray.size() << " bytes in " << timer.elapsed() << " ms."; // Set new filename QString newFilename = filename; @@ -802,6 +803,6 @@ RecordingPointer readRecordingFromRecFile(RecordingPointer recording, const QStr // Set recording to new format writeRecordingToFile(recording, newFilename); - qDebug() << "Recording has been successfully converted at" << newFilename; + qCDebug(avatars) << "Recording has been successfully converted at" << newFilename; return recording; } diff --git a/libraries/avatars/src/Referential.cpp b/libraries/avatars/src/Referential.cpp index f5f1d47324..0683580093 100644 --- a/libraries/avatars/src/Referential.cpp +++ b/libraries/avatars/src/Referential.cpp @@ -12,6 +12,7 @@ #include #include "AvatarData.h" +#include "AvatarLogging.h" #include "Referential.h" Referential::Referential(Type type, AvatarData* avatar) : @@ -62,7 +63,7 @@ int Referential::unpackReferential(const unsigned char* sourceBuffer) { _isValid = (bytesRead == expectedSize); if (!_isValid) { // Will occur if the new instance unpacking is of the wrong type - qDebug() << "[ERROR] Referential extra data overflow"; + qCDebug(avatars) << "[ERROR] Referential extra data overflow"; } sourceBuffer += expectedSize; return sourceBuffer - startPosition; diff --git a/libraries/embedded-webserver/src/EmbeddedWebserverLogging.cpp b/libraries/embedded-webserver/src/EmbeddedWebserverLogging.cpp new file mode 100644 index 0000000000..a2444c3a70 --- /dev/null +++ b/libraries/embedded-webserver/src/EmbeddedWebserverLogging.cpp @@ -0,0 +1,14 @@ +// +// EmbeddedWebserverLogging.cpp +// libraries/embedded-webserver/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "EmbeddedWebserverLogging.h" + +Q_LOGGING_CATEGORY(embeddedwebserver, "hifi.embeddedwebserver") diff --git a/libraries/embedded-webserver/src/EmbeddedWebserverLogging.h b/libraries/embedded-webserver/src/EmbeddedWebserverLogging.h new file mode 100644 index 0000000000..e8720fb630 --- /dev/null +++ b/libraries/embedded-webserver/src/EmbeddedWebserverLogging.h @@ -0,0 +1,19 @@ +// +// EmbeddedWebserverLogging.h +// libraries/embedded-webserver/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_EmbeddedWebserverLogging_h +#define hifi_EmbeddedWebserverLogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(embeddedwebserver) + +#endif // hifi_EmbeddedWebserverLogging_h diff --git a/libraries/embedded-webserver/src/HTTPConnection.cpp b/libraries/embedded-webserver/src/HTTPConnection.cpp index 82d3d7eba6..fb69499059 100644 --- a/libraries/embedded-webserver/src/HTTPConnection.cpp +++ b/libraries/embedded-webserver/src/HTTPConnection.cpp @@ -15,6 +15,7 @@ #include #include "HTTPConnection.h" +#include "EmbeddedWebserverLogging.h" #include "HTTPManager.h" const char* HTTPConnection::StatusCode200 = "200 OK"; @@ -45,7 +46,7 @@ HTTPConnection::~HTTPConnection() { // log the destruction if (_socket->error() != QAbstractSocket::UnknownSocketError && _socket->error() != QAbstractSocket::RemoteHostClosedError) { - qDebug() << _socket->errorString() << "-" << _socket->error(); + qCDebug(embeddedwebserver) << _socket->errorString() << "-" << _socket->error(); } } diff --git a/libraries/embedded-webserver/src/HTTPManager.cpp b/libraries/embedded-webserver/src/HTTPManager.cpp index 702d709f72..19443e01da 100644 --- a/libraries/embedded-webserver/src/HTTPManager.cpp +++ b/libraries/embedded-webserver/src/HTTPManager.cpp @@ -16,6 +16,7 @@ #include #include "HTTPConnection.h" +#include "EmbeddedWebserverLogging.h" #include "HTTPManager.h" HTTPManager::HTTPManager(quint16 port, const QString& documentRoot, HTTPRequestHandler* requestHandler, QObject* parent) : @@ -25,7 +26,7 @@ HTTPManager::HTTPManager(quint16 port, const QString& documentRoot, HTTPRequestH { // start listening on the passed port if (!listen(QHostAddress("0.0.0.0"), port)) { - qDebug() << "Failed to open HTTP server socket:" << errorString(); + qCDebug(embeddedwebserver) << "Failed to open HTTP server socket:" << errorString(); return; } } @@ -127,7 +128,7 @@ bool HTTPManager::handleHTTPRequest(HTTPConnection* connection, const QUrl& url, replacementString = QString(includedFile.readAll()); } else { - qDebug() << "SSI include directive referenced a missing file:" << includeFilePath; + qCDebug(embeddedwebserver) << "SSI include directive referenced a missing file:" << includeFilePath; } // replace the match with the contents of the file, or an empty string if the file was not found @@ -155,4 +156,4 @@ bool HTTPManager::handleHTTPRequest(HTTPConnection* connection, const QUrl& url, bool HTTPManager::requestHandledByRequestHandler(HTTPConnection* connection, const QUrl& url) { return _requestHandler && _requestHandler->handleHTTPRequest(connection, url); -} \ No newline at end of file +} diff --git a/libraries/embedded-webserver/src/HTTPSConnection.cpp b/libraries/embedded-webserver/src/HTTPSConnection.cpp index 54893d91c2..7af14ce0a7 100644 --- a/libraries/embedded-webserver/src/HTTPSConnection.cpp +++ b/libraries/embedded-webserver/src/HTTPSConnection.cpp @@ -9,6 +9,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include "EmbeddedWebserverLogging.h" #include "HTTPSConnection.h" HTTPSConnection::HTTPSConnection(QSslSocket* sslSocket, HTTPSManager* parentManager) : @@ -19,5 +20,5 @@ HTTPSConnection::HTTPSConnection(QSslSocket* sslSocket, HTTPSManager* parentMana } void HTTPSConnection::handleSSLErrors(const QList& errors) { - qDebug() << "SSL errors:" << errors; -} \ No newline at end of file + qCDebug(embeddedwebserver) << "SSL errors:" << errors; +} diff --git a/libraries/entities-renderer/src/EntitiesRendererLogging.cpp b/libraries/entities-renderer/src/EntitiesRendererLogging.cpp new file mode 100644 index 0000000000..7fbbb3b1bd --- /dev/null +++ b/libraries/entities-renderer/src/EntitiesRendererLogging.cpp @@ -0,0 +1,14 @@ +// +// EntitiesRendererLogging.cpp +// libraries/entities-renderer/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "EntitiesRendererLogging.h" + +Q_LOGGING_CATEGORY(entitiesrenderer, "hifi.entitiesrenderer") diff --git a/libraries/entities-renderer/src/EntitiesRendererLogging.h b/libraries/entities-renderer/src/EntitiesRendererLogging.h new file mode 100644 index 0000000000..b33949877b --- /dev/null +++ b/libraries/entities-renderer/src/EntitiesRendererLogging.h @@ -0,0 +1,20 @@ +// +// EntitiesRendererLogging.h +// libraries/entities-renderer/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_EntitiesRendererLogging_h +#define hifi_EntitiesRendererLogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(entitiesrenderer) + +#endif // hifi_EntitiesRendererLogging_h + diff --git a/libraries/entities-renderer/src/EntityTreeRenderer.cpp b/libraries/entities-renderer/src/EntityTreeRenderer.cpp index 606825bb5d..da972b3843 100644 --- a/libraries/entities-renderer/src/EntityTreeRenderer.cpp +++ b/libraries/entities-renderer/src/EntityTreeRenderer.cpp @@ -33,6 +33,7 @@ #include "RenderableSphereEntityItem.h" #include "RenderableTextEntityItem.h" #include "RenderableParticleEffectEntityItem.h" +#include "EntitiesRendererLogging.h" EntityTreeRenderer::EntityTreeRenderer(bool wantScripts, AbstractViewStateInterface* viewState, @@ -159,11 +160,11 @@ QString EntityTreeRenderer::loadScriptContents(const QString& scriptMaybeURLorTe QString fileName = url.toLocalFile(); QFile scriptFile(fileName); if (scriptFile.open(QFile::ReadOnly | QFile::Text)) { - qDebug() << "Loading file:" << fileName; + qCDebug(entitiesrenderer) << "Loading file:" << fileName; QTextStream in(&scriptFile); scriptContents = in.readAll(); } else { - qDebug() << "ERROR Loading file:" << fileName; + qCDebug(entitiesrenderer) << "ERROR Loading file:" << fileName; } } else { auto scriptCache = DependencyManager::get(); @@ -232,10 +233,10 @@ QScriptValue EntityTreeRenderer::loadEntityScript(EntityItem* entity, bool isPre QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(scriptContents); if (syntaxCheck.state() != QScriptSyntaxCheckResult::Valid) { - qDebug() << "EntityTreeRenderer::loadEntityScript() entity:" << entityID; - qDebug() << " " << syntaxCheck.errorMessage() << ":" + qCDebug(entitiesrenderer) << "EntityTreeRenderer::loadEntityScript() entity:" << entityID; + qCDebug(entitiesrenderer) << " " << syntaxCheck.errorMessage() << ":" << syntaxCheck.errorLineNumber() << syntaxCheck.errorColumnNumber(); - qDebug() << " SCRIPT:" << entityScript; + qCDebug(entitiesrenderer) << " SCRIPT:" << entityScript; scriptCache->addScriptToBadScriptList(url); @@ -248,9 +249,9 @@ QScriptValue EntityTreeRenderer::loadEntityScript(EntityItem* entity, bool isPre QScriptValue entityScriptConstructor = _sandboxScriptEngine->evaluate(scriptContents); if (!entityScriptConstructor.isFunction()) { - qDebug() << "EntityTreeRenderer::loadEntityScript() entity:" << entityID; - qDebug() << " NOT CONSTRUCTOR"; - qDebug() << " SCRIPT:" << entityScript; + qCDebug(entitiesrenderer) << "EntityTreeRenderer::loadEntityScript() entity:" << entityID; + qCDebug(entitiesrenderer) << " NOT CONSTRUCTOR"; + qCDebug(entitiesrenderer) << " SCRIPT:" << entityScript; scriptCache->addScriptToBadScriptList(url); @@ -781,7 +782,7 @@ void EntityTreeRenderer::mousePressEvent(QMouseEvent* event, unsigned int device bool precisionPicking = !_dontDoPrecisionPicking; RayToEntityIntersectionResult rayPickResult = findRayIntersectionWorker(ray, Octree::Lock, precisionPicking); if (rayPickResult.intersects) { - //qDebug() << "mousePressEvent over entity:" << rayPickResult.entityID; + //qCDebug(entitiesrenderer) << "mousePressEvent over entity:" << rayPickResult.entityID; emit mousePressOnEntity(rayPickResult.entityID, MouseEvent(*event, deviceID)); QScriptValueList entityScriptArgs = createMouseEventArgs(rayPickResult.entityID, event, deviceID); @@ -811,7 +812,7 @@ void EntityTreeRenderer::mouseReleaseEvent(QMouseEvent* event, unsigned int devi bool precisionPicking = !_dontDoPrecisionPicking; RayToEntityIntersectionResult rayPickResult = findRayIntersectionWorker(ray, Octree::Lock, precisionPicking); if (rayPickResult.intersects) { - //qDebug() << "mouseReleaseEvent over entity:" << rayPickResult.entityID; + //qCDebug(entitiesrenderer) << "mouseReleaseEvent over entity:" << rayPickResult.entityID; emit mouseReleaseOnEntity(rayPickResult.entityID, MouseEvent(*event, deviceID)); QScriptValueList entityScriptArgs = createMouseEventArgs(rayPickResult.entityID, event, deviceID); @@ -860,7 +861,7 @@ void EntityTreeRenderer::mouseMoveEvent(QMouseEvent* event, unsigned int deviceI entityScript.property("mouseMoveEvent").call(entityScript, entityScriptArgs); } - //qDebug() << "mouseMoveEvent over entity:" << rayPickResult.entityID; + //qCDebug(entitiesrenderer) << "mouseMoveEvent over entity:" << rayPickResult.entityID; emit mouseMoveOnEntity(rayPickResult.entityID, MouseEvent(*event, deviceID)); if (entityScript.property("mouseMoveOnEntity").isValid()) { entityScript.property("mouseMoveOnEntity").call(entityScript, entityScriptArgs); diff --git a/libraries/entities-renderer/src/RenderableModelEntityItem.cpp b/libraries/entities-renderer/src/RenderableModelEntityItem.cpp index bf5ce62ff8..4cd625c93f 100644 --- a/libraries/entities-renderer/src/RenderableModelEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderableModelEntityItem.cpp @@ -20,6 +20,7 @@ #include #include "EntityTreeRenderer.h" +#include "EntitiesRendererLogging.h" #include "RenderableModelEntityItem.h" EntityItem* RenderableModelEntityItem::factory(const EntityItemID& entityID, const EntityItemProperties& properties) { @@ -92,7 +93,7 @@ void RenderableModelEntityItem::remapTextures() { // contain this texture, then remove it by setting the URL to null if (!textureMap.contains(key)) { QUrl noURL; - qDebug() << "Removing texture named" << key << "by replacing it with no URL"; + qCDebug(entitiesrenderer) << "Removing texture named" << key << "by replacing it with no URL"; _model->setTextureWithNameToURL(key, noURL); } } @@ -100,7 +101,7 @@ void RenderableModelEntityItem::remapTextures() { // here's where we remap any textures if needed... foreach(const QString& key, textureMap.keys()) { QUrl newTextureURL = textureMap[key].toUrl(); - qDebug() << "Updating texture named" << key << "to texture at URL" << newTextureURL; + qCDebug(entitiesrenderer) << "Updating texture named" << key << "to texture at URL" << newTextureURL; _model->setTextureWithNameToURL(key, newTextureURL); } @@ -260,7 +261,7 @@ bool RenderableModelEntityItem::findDetailedRayIntersection(const glm::vec3& ori if (!_model) { return true; } - //qDebug() << "RenderableModelEntityItem::findDetailedRayIntersection() precisionPicking:" << precisionPicking; + //qCDebug(entitiesrenderer) << "RenderableModelEntityItem::findDetailedRayIntersection() precisionPicking:" << precisionPicking; QString extraInfo; return _model->findRayIntersectionAgainstSubMeshes(origin, direction, distance, face, extraInfo, precisionPicking); @@ -374,7 +375,7 @@ void RenderableModelEntityItem::computeShapeInfo(ShapeInfo& info) { } if (pointsInPart.size() == 0) { - qDebug() << "Warning -- meshPart has no faces"; + qCDebug(entitiesrenderer) << "Warning -- meshPart has no faces"; continue; } diff --git a/libraries/entities-renderer/src/RenderableTextEntityItem.cpp b/libraries/entities-renderer/src/RenderableTextEntityItem.cpp index 3586a8c8c5..895b2f9b54 100644 --- a/libraries/entities-renderer/src/RenderableTextEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderableTextEntityItem.cpp @@ -37,7 +37,7 @@ void RenderableTextEntityItem::render(RenderArgs* args) { float leftMargin = 0.1f; float topMargin = 0.1f; - //qDebug() << "RenderableTextEntityItem::render() id:" << getEntityItemID() << "text:" << getText(); + //qCDebug(entitytree) << "RenderableTextEntityItem::render() id:" << getEntityItemID() << "text:" << getText(); glPushMatrix(); { diff --git a/libraries/entities/src/BoxEntityItem.cpp b/libraries/entities/src/BoxEntityItem.cpp index 1e8c811122..92861b3793 100644 --- a/libraries/entities/src/BoxEntityItem.cpp +++ b/libraries/entities/src/BoxEntityItem.cpp @@ -16,6 +16,7 @@ #include "BoxEntityItem.h" #include "EntityTree.h" +#include "EntitiesLogging.h" #include "EntityTreeElement.h" @@ -55,7 +56,7 @@ bool BoxEntityItem::setProperties(const EntityItemProperties& properties) { if (wantDebug) { uint64_t now = usecTimestampNow(); int elapsed = now - getLastEdited(); - qDebug() << "BoxEntityItem::setProperties() AFTER update... edited AGO=" << elapsed << + qCDebug(entities) << "BoxEntityItem::setProperties() AFTER update... edited AGO=" << elapsed << "now=" << now << " getLastEdited()=" << getLastEdited(); } setLastEdited(properties._lastEdited); @@ -98,10 +99,10 @@ void BoxEntityItem::appendSubclassData(OctreePacketData* packetData, EncodeBitst void BoxEntityItem::debugDump() const { quint64 now = usecTimestampNow(); - qDebug() << " BOX EntityItem id:" << getEntityItemID() << "---------------------------------------------"; - qDebug() << " color:" << _color[0] << "," << _color[1] << "," << _color[2]; - qDebug() << " position:" << debugTreeVector(_position); - qDebug() << " dimensions:" << debugTreeVector(_dimensions); - qDebug() << " getLastEdited:" << debugTime(getLastEdited(), now); + qCDebug(entities) << " BOX EntityItem id:" << getEntityItemID() << "---------------------------------------------"; + qCDebug(entities) << " color:" << _color[0] << "," << _color[1] << "," << _color[2]; + qCDebug(entities) << " position:" << debugTreeVector(_position); + qCDebug(entities) << " dimensions:" << debugTreeVector(_dimensions); + qCDebug(entities) << " getLastEdited:" << debugTime(getLastEdited(), now); } diff --git a/libraries/entities/src/DeleteEntityOperator.cpp b/libraries/entities/src/DeleteEntityOperator.cpp index d17e1c66d6..1d1be55a9b 100644 --- a/libraries/entities/src/DeleteEntityOperator.cpp +++ b/libraries/entities/src/DeleteEntityOperator.cpp @@ -13,6 +13,7 @@ #include "EntityTree.h" #include "EntityTreeElement.h" +#include "EntitiesLogging.h" #include "DeleteEntityOperator.h" DeleteEntityOperator::DeleteEntityOperator(EntityTree* tree, const EntityItemID& searchEntityID) : @@ -43,7 +44,7 @@ void DeleteEntityOperator::addEntityIDToDeleteList(const EntityItemID& searchEnt details.entity = details.containingElement->getEntityWithEntityItemID(searchEntityID); if (!details.entity) { //assert(false); - qDebug() << "that's UNEXPECTED, we got a _containingElement, but couldn't find the oldEntity!"; + qCDebug(entities) << "that's UNEXPECTED, we got a _containingElement, but couldn't find the oldEntity!"; } else { details.cube = details.containingElement->getAACube(); _entitiesToDelete << details; diff --git a/libraries/entities/src/EntitiesLogging.cpp b/libraries/entities/src/EntitiesLogging.cpp new file mode 100644 index 0000000000..de8981dde1 --- /dev/null +++ b/libraries/entities/src/EntitiesLogging.cpp @@ -0,0 +1,14 @@ +// +// EntitiesLogging.cpp +// libraries/entities/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "EntitiesLogging.h" + +Q_LOGGING_CATEGORY(entities, "hifi.entities") diff --git a/libraries/entities/src/EntitiesLogging.h b/libraries/entities/src/EntitiesLogging.h new file mode 100644 index 0000000000..393c7f0e9f --- /dev/null +++ b/libraries/entities/src/EntitiesLogging.h @@ -0,0 +1,19 @@ +// +// EntitiesLogging.h +// libraries/entities/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_EntitiesLogging_h +#define hifi_EntitiesLogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(entities) + +#endif // hifi_EntitiesLogging_h diff --git a/libraries/entities/src/EntityEditPacketSender.cpp b/libraries/entities/src/EntityEditPacketSender.cpp index a04e07ebb3..e94725782d 100644 --- a/libraries/entities/src/EntityEditPacketSender.cpp +++ b/libraries/entities/src/EntityEditPacketSender.cpp @@ -14,6 +14,7 @@ #include #include #include "EntityEditPacketSender.h" +#include "EntitiesLogging.h" #include "EntityItem.h" @@ -37,9 +38,9 @@ void EntityEditPacketSender::queueEditEntityMessage(PacketType type, EntityItemI if (EntityItemProperties::encodeEntityEditPacket(type, modelID, properties, &bufferOut[0], _maxPacketSize, sizeOut)) { #ifdef WANT_DEBUG - qDebug() << "calling queueOctreeEditMessage()..."; - qDebug() << " id:" << modelID; - qDebug() << " properties:" << properties; + qCDebug(entities) << "calling queueOctreeEditMessage()..."; + qCDebug(entities) << " id:" << modelID; + qCDebug(entities) << " properties:" << properties; #endif queueOctreeEditMessage(type, bufferOut, sizeOut); } diff --git a/libraries/entities/src/EntityItem.cpp b/libraries/entities/src/EntityItem.cpp index dc9c27e093..71081ec93d 100644 --- a/libraries/entities/src/EntityItem.cpp +++ b/libraries/entities/src/EntityItem.cpp @@ -20,6 +20,7 @@ #include "EntityScriptingInterface.h" #include "EntityItem.h" +#include "EntitiesLogging.h" #include "EntityTree.h" bool EntityItem::_sendPhysicsUpdates = true; @@ -169,7 +170,7 @@ OctreeElement::AppendState EntityItem::appendEntityData(OctreePacketData* packet #ifdef WANT_DEBUG float editedAgo = getEditedAgo(); QString agoAsString = formatSecondsElapsed(editedAgo); - qDebug() << "Writing entity " << getEntityItemID() << " to buffer, lastEdited =" << lastEdited + qCDebug(entities) << "Writing entity " << getEntityItemID() << " to buffer, lastEdited =" << lastEdited << " ago=" << editedAgo << "seconds - " << agoAsString; #endif @@ -309,7 +310,7 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef // NOTE: This shouldn't happen. The only versions of the bit stream that didn't support split mtu buffers should // be handled by the model subclass and shouldn't call this routine. - qDebug() << "EntityItem::readEntityDataFromBuffer()... " + qCDebug(entities) << "EntityItem::readEntityDataFromBuffer()... " "ERROR CASE...args.bitstreamVersion < VERSION_ENTITIES_SUPPORT_SPLIT_MTU"; return 0; } @@ -373,15 +374,15 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef float editedAgo = getEditedAgo(); QString agoAsString = formatSecondsElapsed(editedAgo); QString ageAsString = formatSecondsElapsed(getAge()); - qDebug() << "------------------------------------------"; - qDebug() << "Loading entity " << getEntityItemID() << " from buffer..."; - qDebug() << "------------------------------------------"; + qCDebug(entities) << "------------------------------------------"; + qCDebug(entities) << "Loading entity " << getEntityItemID() << " from buffer..."; + qCDebug(entities) << "------------------------------------------"; debugDump(); - qDebug() << "------------------------------------------"; - qDebug() << " _created =" << _created; - qDebug() << " age=" << getAge() << "seconds - " << ageAsString; - qDebug() << " lastEdited =" << lastEdited; - qDebug() << " ago=" << editedAgo << "seconds - " << agoAsString; + qCDebug(entities) << "------------------------------------------"; + qCDebug(entities) << " _created =" << _created; + qCDebug(entities) << " age=" << getAge() << "seconds - " << ageAsString; + qCDebug(entities) << " lastEdited =" << lastEdited; + qCDebug(entities) << " ago=" << editedAgo << "seconds - " << agoAsString; #endif quint64 lastEditedFromBuffer = 0; @@ -400,16 +401,16 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef bool fromSameServerEdit = (lastEditedFromBuffer == _lastEditedFromRemoteInRemoteTime); #ifdef WANT_DEBUG - qDebug() << "data from server **************** "; - qDebug() << " entityItemID:" << getEntityItemID(); - qDebug() << " now:" << now; - qDebug() << " getLastEdited:" << debugTime(getLastEdited(), now); - qDebug() << " lastEditedFromBuffer:" << debugTime(lastEditedFromBuffer, now); - qDebug() << " clockSkew:" << debugTimeOnly(clockSkew); - qDebug() << " lastEditedFromBufferAdjusted:" << debugTime(lastEditedFromBufferAdjusted, now); - qDebug() << " _lastEditedFromRemote:" << debugTime(_lastEditedFromRemote, now); - qDebug() << " _lastEditedFromRemoteInRemoteTime:" << debugTime(_lastEditedFromRemoteInRemoteTime, now); - qDebug() << " fromSameServerEdit:" << fromSameServerEdit; + qCDebug(entities) << "data from server **************** "; + qCDebug(entities) << " entityItemID:" << getEntityItemID(); + qCDebug(entities) << " now:" << now; + qCDebug(entities) << " getLastEdited:" << debugTime(getLastEdited(), now); + qCDebug(entities) << " lastEditedFromBuffer:" << debugTime(lastEditedFromBuffer, now); + qCDebug(entities) << " clockSkew:" << debugTimeOnly(clockSkew); + qCDebug(entities) << " lastEditedFromBufferAdjusted:" << debugTime(lastEditedFromBufferAdjusted, now); + qCDebug(entities) << " _lastEditedFromRemote:" << debugTime(_lastEditedFromRemote, now); + qCDebug(entities) << " _lastEditedFromRemoteInRemoteTime:" << debugTime(_lastEditedFromRemoteInRemoteTime, now); + qCDebug(entities) << " fromSameServerEdit:" << fromSameServerEdit; #endif bool ignoreServerPacket = false; // assume we'll use this server packet @@ -434,13 +435,13 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef if (ignoreServerPacket) { overwriteLocalData = false; #ifdef WANT_DEBUG - qDebug() << "IGNORING old data from server!!! ****************"; + qCDebug(entities) << "IGNORING old data from server!!! ****************"; debugDump(); #endif } else { #ifdef WANT_DEBUG - qDebug() << "USING NEW data from server!!! ****************"; + qCDebug(entities) << "USING NEW data from server!!! ****************"; debugDump(); #endif @@ -461,9 +462,9 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef if (overwriteLocalData) { _lastUpdated = lastEditedFromBufferAdjusted + updateDelta; // don't adjust for clock skew since we already did that #ifdef WANT_DEBUG - qDebug() << " _lastUpdated:" << debugTime(_lastUpdated, now); - qDebug() << " _lastEdited:" << debugTime(_lastEdited, now); - qDebug() << " lastEditedFromBufferAdjusted:" << debugTime(lastEditedFromBufferAdjusted, now); + qCDebug(entities) << " _lastUpdated:" << debugTime(_lastUpdated, now); + qCDebug(entities) << " _lastEdited:" << debugTime(_lastEdited, now); + qCDebug(entities) << " lastEditedFromBufferAdjusted:" << debugTime(lastEditedFromBufferAdjusted, now); #endif } encodedUpdateDelta = updateDeltaCoder; // determine true length @@ -479,9 +480,9 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef if (overwriteLocalData) { _lastSimulated = lastEditedFromBufferAdjusted + simulatedDelta; // don't adjust for clock skew since we already did that #ifdef WANT_DEBUG - qDebug() << " _lastSimulated:" << debugTime(_lastSimulated, now); - qDebug() << " _lastEdited:" << debugTime(_lastEdited, now); - qDebug() << " lastEditedFromBufferAdjusted:" << debugTime(lastEditedFromBufferAdjusted, now); + qCDebug(entities) << " _lastSimulated:" << debugTime(_lastSimulated, now); + qCDebug(entities) << " _lastEdited:" << debugTime(_lastEdited, now); + qCDebug(entities) << " lastEditedFromBufferAdjusted:" << debugTime(lastEditedFromBufferAdjusted, now); #endif } encodedSimulatedDelta = simulatedDeltaCoder; // determine true length @@ -491,10 +492,10 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef #ifdef WANT_DEBUG if (overwriteLocalData) { - qDebug() << "EntityItem::readEntityDataFromBuffer()... changed entity:" << getEntityItemID(); - qDebug() << " getLastEdited:" << debugTime(getLastEdited(), now); - qDebug() << " getLastSimulated:" << debugTime(getLastSimulated(), now); - qDebug() << " getLastUpdated:" << debugTime(getLastUpdated(), now); + qCDebug(entities) << "EntityItem::readEntityDataFromBuffer()... changed entity:" << getEntityItemID(); + qCDebug(entities) << " getLastEdited:" << debugTime(getLastEdited(), now); + qCDebug(entities) << " getLastSimulated:" << debugTime(getLastSimulated(), now); + qCDebug(entities) << " getLastUpdated:" << debugTime(getLastUpdated(), now); } #endif @@ -584,7 +585,7 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef MIN_TIME_SKIP, MAX_TIME_SKIP); if (skipTimeForward > 0.0f) { #ifdef WANT_DEBUG - qDebug() << "skipTimeForward:" << skipTimeForward; + qCDebug(entities) << "skipTimeForward:" << skipTimeForward; #endif simulateKinematicMotion(skipTimeForward); } @@ -595,10 +596,10 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef } void EntityItem::debugDump() const { - qDebug() << "EntityItem id:" << getEntityItemID(); - qDebug(" edited ago:%f", getEditedAgo()); - qDebug(" position:%f,%f,%f", _position.x, _position.y, _position.z); - qDebug() << " dimensions:" << _dimensions; + qCDebug(entities) << "EntityItem id:" << getEntityItemID(); + qCDebug(entities, " edited ago:%f", getEditedAgo()); + qCDebug(entities, " position:%f,%f,%f", _position.x, _position.y, _position.z); + qCDebug(entities) << " dimensions:" << _dimensions; } // adjust any internal timestamps to fix clock skew for this server @@ -614,10 +615,10 @@ void EntityItem::adjustEditPacketForClockSkew(unsigned char* editPacketBuffer, s quint64 lastEditedInServerTime = lastEditedInLocalTime + clockSkew; memcpy(dataAt, &lastEditedInServerTime, sizeof(lastEditedInServerTime)); #ifdef WANT_DEBUG - qDebug("EntityItem::adjustEditPacketForClockSkew()..."); - qDebug() << " lastEditedInLocalTime: " << lastEditedInLocalTime; - qDebug() << " clockSkew: " << clockSkew; - qDebug() << " lastEditedInServerTime: " << lastEditedInServerTime; + qCDebug(entities, "EntityItem::adjustEditPacketForClockSkew()..."); + qCDebug(entities) << " lastEditedInLocalTime: " << lastEditedInLocalTime; + qCDebug(entities) << " clockSkew: " << clockSkew; + qCDebug(entities) << " lastEditedInServerTime: " << lastEditedInServerTime; #endif } @@ -663,39 +664,39 @@ void EntityItem::simulate(const quint64& now) { float timeElapsed = (float)(now - _lastSimulated) / (float)(USECS_PER_SECOND); #ifdef WANT_DEBUG - qDebug() << "********** EntityItem::simulate()"; - qDebug() << " entity ID=" << getEntityItemID(); - qDebug() << " now=" << now; - qDebug() << " _lastSimulated=" << _lastSimulated; - qDebug() << " timeElapsed=" << timeElapsed; - qDebug() << " hasVelocity=" << hasVelocity(); - qDebug() << " hasGravity=" << hasGravity(); - qDebug() << " hasAngularVelocity=" << hasAngularVelocity(); - qDebug() << " getAngularVelocity=" << getAngularVelocity(); - qDebug() << " isMortal=" << isMortal(); - qDebug() << " getAge()=" << getAge(); - qDebug() << " getLifetime()=" << getLifetime(); + qCDebug(entities) << "********** EntityItem::simulate()"; + qCDebug(entities) << " entity ID=" << getEntityItemID(); + qCDebug(entities) << " now=" << now; + qCDebug(entities) << " _lastSimulated=" << _lastSimulated; + qCDebug(entities) << " timeElapsed=" << timeElapsed; + qCDebug(entities) << " hasVelocity=" << hasVelocity(); + qCDebug(entities) << " hasGravity=" << hasGravity(); + qCDebug(entities) << " hasAngularVelocity=" << hasAngularVelocity(); + qCDebug(entities) << " getAngularVelocity=" << getAngularVelocity(); + qCDebug(entities) << " isMortal=" << isMortal(); + qCDebug(entities) << " getAge()=" << getAge(); + qCDebug(entities) << " getLifetime()=" << getLifetime(); if (hasVelocity() || hasGravity()) { - qDebug() << " MOVING...="; - qDebug() << " hasVelocity=" << hasVelocity(); - qDebug() << " hasGravity=" << hasGravity(); - qDebug() << " hasAngularVelocity=" << hasAngularVelocity(); - qDebug() << " getAngularVelocity=" << getAngularVelocity(); + qCDebug(entities) << " MOVING...="; + qCDebug(entities) << " hasVelocity=" << hasVelocity(); + qCDebug(entities) << " hasGravity=" << hasGravity(); + qCDebug(entities) << " hasAngularVelocity=" << hasAngularVelocity(); + qCDebug(entities) << " getAngularVelocity=" << getAngularVelocity(); } if (hasAngularVelocity()) { - qDebug() << " CHANGING...="; - qDebug() << " hasAngularVelocity=" << hasAngularVelocity(); - qDebug() << " getAngularVelocity=" << getAngularVelocity(); + qCDebug(entities) << " CHANGING...="; + qCDebug(entities) << " hasAngularVelocity=" << hasAngularVelocity(); + qCDebug(entities) << " getAngularVelocity=" << getAngularVelocity(); } if (isMortal()) { - qDebug() << " MORTAL...="; - qDebug() << " isMortal=" << isMortal(); - qDebug() << " getAge()=" << getAge(); - qDebug() << " getLifetime()=" << getLifetime(); + qCDebug(entities) << " MORTAL...="; + qCDebug(entities) << " isMortal=" << isMortal(); + qCDebug(entities) << " getAge()=" << getAge(); + qCDebug(entities) << " getLifetime()=" << getLifetime(); } - qDebug() << " ********** EntityItem::simulate() .... SETTING _lastSimulated=" << _lastSimulated; + qCDebug(entities) << " ********** EntityItem::simulate() .... SETTING _lastSimulated=" << _lastSimulated; #endif simulateKinematicMotion(timeElapsed); @@ -708,8 +709,8 @@ void EntityItem::simulateKinematicMotion(float timeElapsed) { if (_angularDamping > 0.0f) { _angularVelocity *= powf(1.0f - _angularDamping, timeElapsed); #ifdef WANT_DEBUG - qDebug() << " angularDamping :" << _angularDamping; - qDebug() << " newAngularVelocity:" << _angularVelocity; + qCDebug(entities) << " angularDamping :" << _angularDamping; + qCDebug(entities) << " newAngularVelocity:" << _angularVelocity; #endif } @@ -747,10 +748,10 @@ void EntityItem::simulateKinematicMotion(float timeElapsed) { if (_damping > 0.0f) { velocity *= powf(1.0f - _damping, timeElapsed); #ifdef WANT_DEBUG - qDebug() << " damping:" << _damping; - qDebug() << " velocity AFTER dampingResistance:" << velocity; - qDebug() << " glm::length(velocity):" << glm::length(velocity); - qDebug() << " velocityEspilon :" << ENTITY_ITEM_EPSILON_VELOCITY_LENGTH; + qCDebug(entities) << " damping:" << _damping; + qCDebug(entities) << " velocity AFTER dampingResistance:" << velocity; + qCDebug(entities) << " glm::length(velocity):" << glm::length(velocity); + qCDebug(entities) << " velocityEspilon :" << ENTITY_ITEM_EPSILON_VELOCITY_LENGTH; #endif } @@ -759,14 +760,14 @@ void EntityItem::simulateKinematicMotion(float timeElapsed) { glm::vec3 newPosition = position + (velocity * timeElapsed); #ifdef WANT_DEBUG - qDebug() << " EntityItem::simulate()...."; - qDebug() << " timeElapsed:" << timeElapsed; - qDebug() << " old AACube:" << getMaximumAACube(); - qDebug() << " old position:" << position; - qDebug() << " old velocity:" << velocity; - qDebug() << " old getAABox:" << getAABox(); - qDebug() << " newPosition:" << newPosition; - qDebug() << " glm::distance(newPosition, position):" << glm::distance(newPosition, position); + qCDebug(entities) << " EntityItem::simulate()...."; + qCDebug(entities) << " timeElapsed:" << timeElapsed; + qCDebug(entities) << " old AACube:" << getMaximumAACube(); + qCDebug(entities) << " old position:" << position; + qCDebug(entities) << " old velocity:" << velocity; + qCDebug(entities) << " old getAABox:" << getAABox(); + qCDebug(entities) << " newPosition:" << newPosition; + qCDebug(entities) << " glm::distance(newPosition, position):" << glm::distance(newPosition, position); #endif position = newPosition; @@ -791,10 +792,10 @@ void EntityItem::simulateKinematicMotion(float timeElapsed) { } #ifdef WANT_DEBUG - qDebug() << " new position:" << position; - qDebug() << " new velocity:" << velocity; - qDebug() << " new AACube:" << getMaximumAACube(); - qDebug() << " old getAABox:" << getAABox(); + qCDebug(entities) << " new position:" << position; + qCDebug(entities) << " new velocity:" << velocity; + qCDebug(entities) << " new AACube:" << getMaximumAACube(); + qCDebug(entities) << " old getAABox:" << getAABox(); #endif } } @@ -874,7 +875,7 @@ bool EntityItem::setProperties(const EntityItemProperties& properties) { uint64_t now = usecTimestampNow(); #ifdef WANT_DEBUG int elapsed = now - getLastEdited(); - qDebug() << "EntityItem::setProperties() AFTER update... edited AGO=" << elapsed << + qCDebug(entities) << "EntityItem::setProperties() AFTER update... edited AGO=" << elapsed << "now=" << now << " getLastEdited()=" << getLastEdited(); #endif if (_created != UNKNOWN_CREATED_TIME) { diff --git a/libraries/entities/src/EntityItemProperties.cpp b/libraries/entities/src/EntityItemProperties.cpp index 6e6e897230..0d69bd51ce 100644 --- a/libraries/entities/src/EntityItemProperties.cpp +++ b/libraries/entities/src/EntityItemProperties.cpp @@ -23,6 +23,7 @@ #include "EntityItemPropertiesDefaults.h" #include "ModelEntityItem.h" #include "TextEntityItem.h" +#include "EntitiesLogging.h" #include "ParticleEffectEntityItem.h" @@ -153,15 +154,15 @@ QString EntityItemProperties::getAnimationSettings() const { } void EntityItemProperties::debugDump() const { - qDebug() << "EntityItemProperties..."; - qDebug() << " _type=" << EntityTypes::getEntityTypeName(_type); - qDebug() << " _id=" << _id; - qDebug() << " _idSet=" << _idSet; - qDebug() << " _position=" << _position.x << "," << _position.y << "," << _position.z; - qDebug() << " _dimensions=" << getDimensions(); - qDebug() << " _modelURL=" << _modelURL; - qDebug() << " _collisionModelURL=" << _collisionModelURL; - qDebug() << " changed properties..."; + qCDebug(entities) << "EntityItemProperties..."; + qCDebug(entities) << " _type=" << EntityTypes::getEntityTypeName(_type); + qCDebug(entities) << " _id=" << _id; + qCDebug(entities) << " _idSet=" << _idSet; + qCDebug(entities) << " _position=" << _position.x << "," << _position.y << "," << _position.z; + qCDebug(entities) << " _dimensions=" << getDimensions(); + qCDebug(entities) << " _modelURL=" << _modelURL; + qCDebug(entities) << " _collisionModelURL=" << _collisionModelURL; + qCDebug(entities) << " changed properties..."; EntityPropertyFlags props = getChangedProperties(); props.debugDumpBits(); } @@ -643,7 +644,7 @@ bool EntityItemProperties::encodeEntityEditPacket(PacketType command, EntityItem memcpy(bufferOut, finalizedData, finalizedSize); sizeOut = finalizedSize; } else { - qDebug() << "ERROR - encoded edit message doesn't fit in output buffer."; + qCDebug(entities) << "ERROR - encoded edit message doesn't fit in output buffer."; sizeOut = 0; success = false; } @@ -838,7 +839,7 @@ bool EntityItemProperties::encodeEraseEntityMessage(const EntityItemID& entityIt uint16_t numberOfIds = 1; // only one entity ID in this message if (maxLength < sizeof(numberOfIds) + NUM_BYTES_RFC4122_UUID) { - qDebug() << "ERROR - encodeEraseEntityMessage() called with buffer that is too small!"; + qCDebug(entities) << "ERROR - encodeEraseEntityMessage() called with buffer that is too small!"; outputLength = 0; return false; } diff --git a/libraries/entities/src/EntitySimulation.cpp b/libraries/entities/src/EntitySimulation.cpp index b093dbe4f4..a390521ed8 100644 --- a/libraries/entities/src/EntitySimulation.cpp +++ b/libraries/entities/src/EntitySimulation.cpp @@ -12,6 +12,7 @@ #include #include "EntitySimulation.h" +#include "EntitiesLogging.h" #include "MovingEntitiesOperator.h" void EntitySimulation::setEntityTree(EntityTree* tree) { @@ -94,7 +95,7 @@ void EntitySimulation::sortEntitiesThatMoved() { // check to see if this movement has sent the entity outside of the domain. AACube newCube = entity->getMaximumAACube(); if (!domainBounds.touches(newCube)) { - qDebug() << "Entity " << entity->getEntityItemID() << " moved out of domain bounds."; + qCDebug(entities) << "Entity " << entity->getEntityItemID() << " moved out of domain bounds."; _entitiesToDelete.insert(entity); _mortalEntities.remove(entity); _updateableEntities.remove(entity); @@ -154,7 +155,7 @@ void EntitySimulation::entityChanged(EntityItem* entity) { AACube domainBounds(glm::vec3(0.0f,0.0f,0.0f), (float)TREE_SCALE); AACube newCube = entity->getMaximumAACube(); if (!domainBounds.touches(newCube)) { - qDebug() << "Entity " << entity->getEntityItemID() << " moved out of domain bounds."; + qCDebug(entities) << "Entity " << entity->getEntityItemID() << " moved out of domain bounds."; _entitiesToDelete.insert(entity); _mortalEntities.remove(entity); _updateableEntities.remove(entity); diff --git a/libraries/entities/src/EntityTree.cpp b/libraries/entities/src/EntityTree.cpp index 446c5ab22f..ea811389cb 100644 --- a/libraries/entities/src/EntityTree.cpp +++ b/libraries/entities/src/EntityTree.cpp @@ -21,6 +21,7 @@ #include "MovingEntitiesOperator.h" #include "UpdateEntityOperator.h" #include "QVariantGLM.h" +#include "EntitiesLogging.h" #include "RecurseOctreeToMapOperator.h" EntityTree::EntityTree(bool shouldReaverage) : @@ -103,13 +104,13 @@ void EntityTree::postAddEntity(EntityItem* entity) { bool EntityTree::updateEntity(const EntityItemID& entityID, const EntityItemProperties& properties, bool allowLockChange) { EntityTreeElement* containingElement = getContainingElement(entityID); if (!containingElement) { - qDebug() << "UNEXPECTED!!!! EntityTree::updateEntity() entityID doesn't exist!!! entityID=" << entityID; + qCDebug(entities) << "UNEXPECTED!!!! EntityTree::updateEntity() entityID doesn't exist!!! entityID=" << entityID; return false; } EntityItem* existingEntity = containingElement->getEntityWithEntityItemID(entityID); if (!existingEntity) { - qDebug() << "UNEXPECTED!!!! don't call updateEntity() on entity items that don't exist. entityID=" << entityID; + qCDebug(entities) << "UNEXPECTED!!!! don't call updateEntity() on entity items that don't exist. entityID=" << entityID; return false; } @@ -119,7 +120,7 @@ bool EntityTree::updateEntity(const EntityItemID& entityID, const EntityItemProp bool EntityTree::updateEntity(EntityItem* entity, const EntityItemProperties& properties, bool allowLockChange) { EntityTreeElement* containingElement = getContainingElement(entity->getEntityItemID()); if (!containingElement) { - qDebug() << "UNEXPECTED!!!! EntityTree::updateEntity() entity-->element lookup failed!!! entityID=" + qCDebug(entities) << "UNEXPECTED!!!! EntityTree::updateEntity() entity-->element lookup failed!!! entityID=" << entity->getEntityItemID(); return false; } @@ -130,7 +131,7 @@ bool EntityTree::updateEntityWithElement(EntityItem* entity, const EntityItemPro EntityTreeElement* containingElement, bool allowLockChange) { if (!allowLockChange && (entity->getLocked() != properties.getLocked())) { - qDebug() << "Refusing disallowed lock adjustment."; + qCDebug(entities) << "Refusing disallowed lock adjustment."; return false; } @@ -177,7 +178,7 @@ bool EntityTree::updateEntityWithElement(EntityItem* entity, const EntityItemPro // TODO: this final containingElement check should eventually be removed (or wrapped in an #ifdef DEBUG). containingElement = getContainingElement(entity->getEntityItemID()); if (!containingElement) { - qDebug() << "UNEXPECTED!!!! after updateEntity() we no longer have a containing element??? entityID=" + qCDebug(entities) << "UNEXPECTED!!!! after updateEntity() we no longer have a containing element??? entityID=" << entity->getEntityItemID(); return false; } @@ -193,7 +194,7 @@ EntityItem* EntityTree::addEntity(const EntityItemID& entityID, const EntityItem bool recordCreationTime = false; if (!entityID.isKnownID) { if (getIsServer()) { - qDebug() << "UNEXPECTED!!! ----- EntityTree::addEntity()... (getIsSever() && !entityID.isKnownID)"; + qCDebug(entities) << "UNEXPECTED!!! ----- EntityTree::addEntity()... (getIsSever() && !entityID.isKnownID)"; return result; } if (properties.getCreated() == UNKNOWN_CREATED_TIME) { @@ -206,7 +207,7 @@ EntityItem* EntityTree::addEntity(const EntityItemID& entityID, const EntityItem // You should not call this on existing entities that are already part of the tree! Call updateEntity() EntityTreeElement* containingElement = getContainingElement(entityID); if (containingElement) { - qDebug() << "UNEXPECTED!!! ----- don't call addEntity() on existing entity items. entityID=" << entityID + qCDebug(entities) << "UNEXPECTED!!! ----- don't call addEntity() on existing entity items. entityID=" << entityID << "containingElement=" << containingElement; return result; } @@ -251,7 +252,7 @@ void EntityTree::deleteEntity(const EntityItemID& entityID, bool force, bool ign EntityTreeElement* containingElement = getContainingElement(entityID); if (!containingElement) { if (!ignoreWarnings) { - qDebug() << "UNEXPECTED!!!! EntityTree::deleteEntity() entityID doesn't exist!!! entityID=" << entityID; + qCDebug(entities) << "UNEXPECTED!!!! EntityTree::deleteEntity() entityID doesn't exist!!! entityID=" << entityID; } return; } @@ -259,7 +260,7 @@ void EntityTree::deleteEntity(const EntityItemID& entityID, bool force, bool ign EntityItem* existingEntity = containingElement->getEntityWithEntityItemID(entityID); if (!existingEntity) { if (!ignoreWarnings) { - qDebug() << "UNEXPECTED!!!! don't call EntityTree::deleteEntity() on entity items that don't exist. " + qCDebug(entities) << "UNEXPECTED!!!! don't call EntityTree::deleteEntity() on entity items that don't exist. " "entityID=" << entityID; } return; @@ -267,7 +268,7 @@ void EntityTree::deleteEntity(const EntityItemID& entityID, bool force, bool ign if (existingEntity->getLocked() && !force) { if (!ignoreWarnings) { - qDebug() << "ERROR! EntityTree::deleteEntity() trying to delete locked entity. entityID=" << entityID; + qCDebug(entities) << "ERROR! EntityTree::deleteEntity() trying to delete locked entity. entityID=" << entityID; } return; } @@ -288,7 +289,7 @@ void EntityTree::deleteEntities(QSet entityIDs, bool force, bool i EntityTreeElement* containingElement = getContainingElement(entityID); if (!containingElement) { if (!ignoreWarnings) { - qDebug() << "UNEXPECTED!!!! EntityTree::deleteEntities() entityID doesn't exist!!! entityID=" << entityID; + qCDebug(entities) << "UNEXPECTED!!!! EntityTree::deleteEntities() entityID doesn't exist!!! entityID=" << entityID; } continue; } @@ -296,7 +297,7 @@ void EntityTree::deleteEntities(QSet entityIDs, bool force, bool i EntityItem* existingEntity = containingElement->getEntityWithEntityItemID(entityID); if (!existingEntity) { if (!ignoreWarnings) { - qDebug() << "UNEXPECTED!!!! don't call EntityTree::deleteEntities() on entity items that don't exist. " + qCDebug(entities) << "UNEXPECTED!!!! don't call EntityTree::deleteEntities() on entity items that don't exist. " "entityID=" << entityID; } continue; @@ -304,7 +305,7 @@ void EntityTree::deleteEntities(QSet entityIDs, bool force, bool i if (existingEntity->getLocked() && !force) { if (!ignoreWarnings) { - qDebug() << "ERROR! EntityTree::deleteEntities() trying to delete locked entity. entityID=" << entityID; + qCDebug(entities) << "ERROR! EntityTree::deleteEntities() trying to delete locked entity. entityID=" << entityID; } continue; } @@ -376,7 +377,7 @@ void EntityTree::processRemovedEntities(const DeleteEntityOperator& theOperator) void EntityTree::handleAddEntityResponse(const QByteArray& packet) { if (!getIsClient()) { - qDebug() << "UNEXPECTED!!! EntityTree::handleAddEntityResponse() with !getIsClient() ***"; + qCDebug(entities) << "UNEXPECTED!!! EntityTree::handleAddEntityResponse() with !getIsClient() ***"; return; } @@ -602,12 +603,12 @@ EntityItem* EntityTree::findEntityByEntityItemID(const EntityItemID& entityID) / EntityItemID EntityTree::assignEntityID(const EntityItemID& entityItemID) { if (!getIsServer()) { - qDebug() << "UNEXPECTED!!! assignEntityID should only be called on a server tree. entityItemID:" << entityItemID; + qCDebug(entities) << "UNEXPECTED!!! assignEntityID should only be called on a server tree. entityItemID:" << entityItemID; return entityItemID; } if (getContainingElement(entityItemID)) { - qDebug() << "UNEXPECTED!!! don't call assignEntityID() for existing entityIDs. entityItemID:" << entityItemID; + qCDebug(entities) << "UNEXPECTED!!! don't call assignEntityID() for existing entityIDs. entityItemID:" << entityItemID; return entityItemID; } @@ -619,7 +620,7 @@ int EntityTree::processEditPacketData(PacketType packetType, const unsigned char const unsigned char* editData, int maxLength, const SharedNodePointer& senderNode) { if (!getIsServer()) { - qDebug() << "UNEXPECTED!!! processEditPacketData() should only be called on a server tree."; + qCDebug(entities) << "UNEXPECTED!!! processEditPacketData() should only be called on a server tree."; return 0; } @@ -650,35 +651,35 @@ int EntityTree::processEditPacketData(PacketType packetType, const unsigned char // if the EntityItem exists, then update it if (existingEntity) { if (wantEditLogging()) { - qDebug() << "User [" << senderNode->getUUID() << "] editing entity. ID:" << entityItemID; - qDebug() << " properties:" << properties; + qCDebug(entities) << "User [" << senderNode->getUUID() << "] editing entity. ID:" << entityItemID; + qCDebug(entities) << " properties:" << properties; } updateEntity(entityItemID, properties, senderNode->getCanAdjustLocks()); existingEntity->markAsChangedOnServer(); } else { - qDebug() << "User attempted to edit an unknown entity. ID:" << entityItemID; + qCDebug(entities) << "User attempted to edit an unknown entity. ID:" << entityItemID; } } else { if (senderNode->getCanRez()) { // this is a new entity... assign a new entityID entityItemID = assignEntityID(entityItemID); if (wantEditLogging()) { - qDebug() << "User [" << senderNode->getUUID() << "] adding entity."; - qDebug() << " properties:" << properties; + qCDebug(entities) << "User [" << senderNode->getUUID() << "] adding entity."; + qCDebug(entities) << " properties:" << properties; } EntityItem* newEntity = addEntity(entityItemID, properties); if (newEntity) { newEntity->markAsChangedOnServer(); notifyNewlyCreatedEntity(*newEntity, senderNode); if (wantEditLogging()) { - qDebug() << "User [" << senderNode->getUUID() << "] added entity. ID:" + qCDebug(entities) << "User [" << senderNode->getUUID() << "] added entity. ID:" << newEntity->getEntityItemID(); - qDebug() << " properties:" << properties; + qCDebug(entities) << " properties:" << properties; } } } else { - qDebug() << "User without 'rez rights' [" << senderNode->getUUID() << "] attempted to add an entity."; + qCDebug(entities) << "User without 'rez rights' [" << senderNode->getUUID() << "] attempted to add an entity."; } } } @@ -909,7 +910,7 @@ int EntityTree::processEraseMessage(const QByteArray& dataByteArray, const Share for (size_t i = 0; i < numberOfIds; i++) { if (processedBytes + NUM_BYTES_RFC4122_UUID > packetLength) { - qDebug() << "EntityTree::processEraseMessage().... bailing because not enough bytes in buffer"; + qCDebug(entities) << "EntityTree::processEraseMessage().... bailing because not enough bytes in buffer"; break; // bail to prevent buffer overflow } @@ -922,7 +923,7 @@ int EntityTree::processEraseMessage(const QByteArray& dataByteArray, const Share entityItemIDsToDelete << entityItemID; if (wantEditLogging()) { - qDebug() << "User [" << sourceNode->getUUID() << "] deleting entity. ID:" << entityItemID; + qCDebug(entities) << "User [" << sourceNode->getUUID() << "] deleting entity. ID:" << entityItemID; } } @@ -953,7 +954,7 @@ int EntityTree::processEraseMessageDetails(const QByteArray& dataByteArray, cons if (processedBytes + NUM_BYTES_RFC4122_UUID > packetLength) { - qDebug() << "EntityTree::processEraseMessageDetails().... bailing because not enough bytes in buffer"; + qCDebug(entities) << "EntityTree::processEraseMessageDetails().... bailing because not enough bytes in buffer"; break; // bail to prevent buffer overflow } @@ -966,7 +967,7 @@ int EntityTree::processEraseMessageDetails(const QByteArray& dataByteArray, cons entityItemIDsToDelete << entityItemID; if (wantEditLogging()) { - qDebug() << "User [" << sourceNode->getUUID() << "] deleting entity. ID:" << entityItemID; + qCDebug(entities) << "User [" << sourceNode->getUUID() << "] deleting entity. ID:" << entityItemID; } } @@ -999,17 +1000,17 @@ EntityTreeElement* EntityTree::getContainingElement(const EntityItemID& entityIt void EntityTree::resetContainingElement(const EntityItemID& entityItemID, EntityTreeElement* element) { if (entityItemID.id == UNKNOWN_ENTITY_ID) { //assert(entityItemID.id != UNKNOWN_ENTITY_ID); - qDebug() << "UNEXPECTED! resetContainingElement() called with UNKNOWN_ENTITY_ID. entityItemID:" << entityItemID; + qCDebug(entities) << "UNEXPECTED! resetContainingElement() called with UNKNOWN_ENTITY_ID. entityItemID:" << entityItemID; return; } if (entityItemID.creatorTokenID == UNKNOWN_ENTITY_TOKEN) { //assert(entityItemID.creatorTokenID != UNKNOWN_ENTITY_TOKEN); - qDebug() << "UNEXPECTED! resetContainingElement() called with UNKNOWN_ENTITY_TOKEN. entityItemID:" << entityItemID; + qCDebug(entities) << "UNEXPECTED! resetContainingElement() called with UNKNOWN_ENTITY_TOKEN. entityItemID:" << entityItemID; return; } if (!element) { //assert(element); - qDebug() << "UNEXPECTED! resetContainingElement() called with NULL element. entityItemID:" << entityItemID; + qCDebug(entities) << "UNEXPECTED! resetContainingElement() called with NULL element. entityItemID:" << entityItemID; return; } @@ -1042,13 +1043,13 @@ void EntityTree::setContainingElement(const EntityItemID& entityItemID, EntityTr } void EntityTree::debugDumpMap() { - qDebug() << "EntityTree::debugDumpMap() --------------------------"; + qCDebug(entities) << "EntityTree::debugDumpMap() --------------------------"; QHashIterator i(_entityToElementMap); while (i.hasNext()) { i.next(); - qDebug() << i.key() << ": " << i.value(); + qCDebug(entities) << i.key() << ": " << i.value(); } - qDebug() << "-----------------------------------------------------"; + qCDebug(entities) << "-----------------------------------------------------"; } class DebugOperator : public RecurseOctreeOperator { @@ -1059,7 +1060,7 @@ public: bool DebugOperator::preRecursion(OctreeElement* element) { EntityTreeElement* entityTreeElement = static_cast(element); - qDebug() << "EntityTreeElement [" << entityTreeElement << "]"; + qCDebug(entities) << "EntityTreeElement [" << entityTreeElement << "]"; entityTreeElement->debugDump(); return true; } @@ -1157,7 +1158,7 @@ bool EntityTree::readFromMap(QVariantMap& map) { EntityItem* entity = addEntity(entityItemID, properties); if (!entity) { - qDebug() << "adding Entity failed:" << entityItemID << entity->getType(); + qCDebug(entities) << "adding Entity failed:" << entityItemID << entity->getType(); } } diff --git a/libraries/entities/src/EntityTreeElement.cpp b/libraries/entities/src/EntityTreeElement.cpp index 223a4eb478..51648c4fa6 100644 --- a/libraries/entities/src/EntityTreeElement.cpp +++ b/libraries/entities/src/EntityTreeElement.cpp @@ -15,6 +15,7 @@ #include #include "EntityTree.h" +#include "EntitiesLogging.h" #include "EntityTreeElement.h" EntityTreeElement::EntityTreeElement(unsigned char* octalCode) : OctreeElement(), _entityItems(NULL) { @@ -49,8 +50,8 @@ EntityTreeElement* EntityTreeElement::addChildAtIndex(int index) { } void EntityTreeElement::debugExtraEncodeData(EncodeBitstreamParams& params) const { - qDebug() << "EntityTreeElement::debugExtraEncodeData()... "; - qDebug() << " element:" << _cube; + qCDebug(entities) << "EntityTreeElement::debugExtraEncodeData()... "; + qCDebug(entities) << " element:" << _cube; OctreeElementExtraEncodeData* extraEncodeData = params.extraEncodeData; assert(extraEncodeData); // EntityTrees always require extra encode data on their encoding passes @@ -58,9 +59,9 @@ void EntityTreeElement::debugExtraEncodeData(EncodeBitstreamParams& params) cons if (extraEncodeData->contains(this)) { EntityTreeElementExtraEncodeData* entityTreeElementExtraEncodeData = static_cast(extraEncodeData->value(this)); - qDebug() << " encode data:" << entityTreeElementExtraEncodeData; + qCDebug(entities) << " encode data:" << entityTreeElementExtraEncodeData; } else { - qDebug() << " encode data: MISSING!!"; + qCDebug(entities) << " encode data: MISSING!!"; } } @@ -159,7 +160,7 @@ void EntityTreeElement::elementEncodeComplete(EncodeBitstreamParams& params, Oct const bool wantDebug = false; if (wantDebug) { - qDebug() << "EntityTreeElement::elementEncodeComplete() element:" << _cube; + qCDebug(entities) << "EntityTreeElement::elementEncodeComplete() element:" << _cube; } OctreeElementExtraEncodeData* extraEncodeData = params.extraEncodeData; @@ -194,15 +195,15 @@ void EntityTreeElement::elementEncodeComplete(EncodeBitstreamParams& params, Oct = static_cast(extraEncodeData->value(childElement)); if (wantDebug) { - qDebug() << "checking child: " << childElement->_cube; - qDebug() << " childElement->isLeaf():" << childElement->isLeaf(); - qDebug() << " childExtraEncodeData->elementCompleted:" << childExtraEncodeData->elementCompleted; - qDebug() << " childExtraEncodeData->subtreeCompleted:" << childExtraEncodeData->subtreeCompleted; + qCDebug(entities) << "checking child: " << childElement->_cube; + qCDebug(entities) << " childElement->isLeaf():" << childElement->isLeaf(); + qCDebug(entities) << " childExtraEncodeData->elementCompleted:" << childExtraEncodeData->elementCompleted; + qCDebug(entities) << " childExtraEncodeData->subtreeCompleted:" << childExtraEncodeData->subtreeCompleted; } if (childElement->isLeaf() && childExtraEncodeData->elementCompleted) { if (wantDebug) { - qDebug() << " CHILD IS LEAF -- AND CHILD ELEMENT DATA COMPLETED!!!"; + qCDebug(entities) << " CHILD IS LEAF -- AND CHILD ELEMENT DATA COMPLETED!!!"; } childExtraEncodeData->subtreeCompleted = true; } @@ -215,19 +216,19 @@ void EntityTreeElement::elementEncodeComplete(EncodeBitstreamParams& params, Oct } if (wantDebug) { - qDebug() << "for this element: " << _cube; - qDebug() << " WAS elementCompleted:" << thisExtraEncodeData->elementCompleted; - qDebug() << " WAS subtreeCompleted:" << thisExtraEncodeData->subtreeCompleted; + qCDebug(entities) << "for this element: " << _cube; + qCDebug(entities) << " WAS elementCompleted:" << thisExtraEncodeData->elementCompleted; + qCDebug(entities) << " WAS subtreeCompleted:" << thisExtraEncodeData->subtreeCompleted; } thisExtraEncodeData->subtreeCompleted = !someChildTreeNotComplete; if (wantDebug) { - qDebug() << " NOW elementCompleted:" << thisExtraEncodeData->elementCompleted; - qDebug() << " NOW subtreeCompleted:" << thisExtraEncodeData->subtreeCompleted; + qCDebug(entities) << " NOW elementCompleted:" << thisExtraEncodeData->elementCompleted; + qCDebug(entities) << " NOW subtreeCompleted:" << thisExtraEncodeData->subtreeCompleted; if (thisExtraEncodeData->subtreeCompleted) { - qDebug() << " YEAH!!!!! >>>>>>>>>>>>>> NOW subtreeCompleted:" << thisExtraEncodeData->subtreeCompleted; + qCDebug(entities) << " YEAH!!!!! >>>>>>>>>>>>>> NOW subtreeCompleted:" << thisExtraEncodeData->subtreeCompleted; } } } @@ -821,19 +822,19 @@ bool EntityTreeElement::pruneChildren() { void EntityTreeElement::debugDump() { - qDebug() << "EntityTreeElement..."; - qDebug() << " cube:" << _cube; - qDebug() << " has child elements:" << getChildCount(); + qCDebug(entities) << "EntityTreeElement..."; + qCDebug(entities) << " cube:" << _cube; + qCDebug(entities) << " has child elements:" << getChildCount(); if (_entityItems->size()) { - qDebug() << " has entities:" << _entityItems->size(); - qDebug() << "--------------------------------------------------"; + qCDebug(entities) << " has entities:" << _entityItems->size(); + qCDebug(entities) << "--------------------------------------------------"; for (uint16_t i = 0; i < _entityItems->size(); i++) { EntityItem* entity = (*_entityItems)[i]; entity->debugDump(); } - qDebug() << "--------------------------------------------------"; + qCDebug(entities) << "--------------------------------------------------"; } else { - qDebug() << " NO entities!"; + qCDebug(entities) << " NO entities!"; } } diff --git a/libraries/entities/src/LightEntityItem.cpp b/libraries/entities/src/LightEntityItem.cpp index 996677141a..c5f5be829b 100644 --- a/libraries/entities/src/LightEntityItem.cpp +++ b/libraries/entities/src/LightEntityItem.cpp @@ -17,6 +17,7 @@ #include "EntityItemID.h" #include "EntityTree.h" #include "EntityTreeElement.h" +#include "EntitiesLogging.h" #include "LightEntityItem.h" bool LightEntityItem::_lightsArePickable = false; @@ -107,7 +108,7 @@ bool LightEntityItem::setProperties(const EntityItemProperties& properties) { if (wantDebug) { uint64_t now = usecTimestampNow(); int elapsed = now - getLastEdited(); - qDebug() << "LightEntityItem::setProperties() AFTER update... edited AGO=" << elapsed << + qCDebug(entities) << "LightEntityItem::setProperties() AFTER update... edited AGO=" << elapsed << "now=" << now << " getLastEdited()=" << getLastEdited(); } setLastEdited(properties.getLastEdited()); diff --git a/libraries/entities/src/ModelEntityItem.cpp b/libraries/entities/src/ModelEntityItem.cpp index 55d809e70e..cdbc3d9441 100644 --- a/libraries/entities/src/ModelEntityItem.cpp +++ b/libraries/entities/src/ModelEntityItem.cpp @@ -16,8 +16,9 @@ #include "EntityTree.h" #include "EntityTreeElement.h" -#include "ModelEntityItem.h" +#include "EntitiesLogging.h" #include "ResourceCache.h" +#include "ModelEntityItem.h" const QString ModelEntityItem::DEFAULT_MODEL_URL = QString(""); const QString ModelEntityItem::DEFAULT_COLLISION_MODEL_URL = QString(""); @@ -78,7 +79,7 @@ bool ModelEntityItem::setProperties(const EntityItemProperties& properties) { if (wantDebug) { uint64_t now = usecTimestampNow(); int elapsed = now - getLastEdited(); - qDebug() << "ModelEntityItem::setProperties() AFTER update... edited AGO=" << elapsed << + qCDebug(entities) << "ModelEntityItem::setProperties() AFTER update... edited AGO=" << elapsed << "now=" << now << " getLastEdited()=" << getLastEdited(); } setLastEdited(properties._lastEdited); @@ -266,12 +267,12 @@ void ModelEntityItem::update(const quint64& now) { } void ModelEntityItem::debugDump() const { - qDebug() << "ModelEntityItem id:" << getEntityItemID(); - qDebug() << " edited ago:" << getEditedAgo(); - qDebug() << " position:" << getPosition(); - qDebug() << " dimensions:" << getDimensions(); - qDebug() << " model URL:" << getModelURL(); - qDebug() << " collision model URL:" << getCollisionModelURL(); + qCDebug(entities) << "ModelEntityItem id:" << getEntityItemID(); + qCDebug(entities) << " edited ago:" << getEditedAgo(); + qCDebug(entities) << " position:" << getPosition(); + qCDebug(entities) << " dimensions:" << getDimensions(); + qCDebug(entities) << " model URL:" << getModelURL(); + qCDebug(entities) << " collision model URL:" << getCollisionModelURL(); } void ModelEntityItem::updateShapeType(ShapeType type) { @@ -296,11 +297,11 @@ void ModelEntityItem::setAnimationURL(const QString& url) { void ModelEntityItem::setAnimationFrameIndex(float value) { #ifdef WANT_DEBUG if (isAnimatingSomething()) { - qDebug() << "ModelEntityItem::setAnimationFrameIndex()"; - qDebug() << " value:" << value; - qDebug() << " was:" << _animationLoop.getFrameIndex(); - qDebug() << " model URL:" << getModelURL(); - qDebug() << " animation URL:" << getAnimationURL(); + qCDebug(entities) << "ModelEntityItem::setAnimationFrameIndex()"; + qCDebug(entities) << " value:" << value; + qCDebug(entities) << " was:" << _animationLoop.getFrameIndex(); + qCDebug(entities) << " model URL:" << getModelURL(); + qCDebug(entities) << " animation URL:" << getAnimationURL(); } #endif _animationLoop.setFrameIndex(value); @@ -323,12 +324,12 @@ void ModelEntityItem::setAnimationSettings(const QString& value) { float frameIndex = settingsMap["frameIndex"].toFloat(); #ifdef WANT_DEBUG if (isAnimatingSomething()) { - qDebug() << "ModelEntityItem::setAnimationSettings() calling setAnimationFrameIndex()..."; - qDebug() << " model URL:" << getModelURL(); - qDebug() << " animation URL:" << getAnimationURL(); - qDebug() << " settings:" << value; - qDebug() << " settingsMap[frameIndex]:" << settingsMap["frameIndex"]; - qDebug(" frameIndex: %20.5f", frameIndex); + qCDebug(entities) << "ModelEntityItem::setAnimationSettings() calling setAnimationFrameIndex()..."; + qCDebug(entities) << " model URL:" << getModelURL(); + qCDebug(entities) << " animation URL:" << getAnimationURL(); + qCDebug(entities) << " settings:" << value; + qCDebug(entities) << " settingsMap[frameIndex]:" << settingsMap["frameIndex"]; + qCDebug(entities" frameIndex: %20.5f", frameIndex); } #endif diff --git a/libraries/entities/src/MovingEntitiesOperator.cpp b/libraries/entities/src/MovingEntitiesOperator.cpp index 7cace205e1..1418f107bb 100644 --- a/libraries/entities/src/MovingEntitiesOperator.cpp +++ b/libraries/entities/src/MovingEntitiesOperator.cpp @@ -12,6 +12,7 @@ #include "EntityItem.h" #include "EntityTree.h" #include "EntityTreeElement.h" +#include "EntitiesLogging.h" #include "MovingEntitiesOperator.h" @@ -28,19 +29,19 @@ MovingEntitiesOperator::MovingEntitiesOperator(EntityTree* tree) : MovingEntitiesOperator::~MovingEntitiesOperator() { if (_wantDebug) { bool stopExecution = false; - qDebug() << "MovingEntitiesOperator::~MovingEntitiesOperator() -----------------------------"; - qDebug() << " _lookingCount:" << _lookingCount; - qDebug() << " _foundOldCount:" << _foundOldCount; - qDebug() << " _foundNewCount:" << _foundNewCount; + qCDebug(entities) << "MovingEntitiesOperator::~MovingEntitiesOperator() -----------------------------"; + qCDebug(entities) << " _lookingCount:" << _lookingCount; + qCDebug(entities) << " _foundOldCount:" << _foundOldCount; + qCDebug(entities) << " _foundNewCount:" << _foundNewCount; if (_foundOldCount < _lookingCount) { - qDebug() << " FAILURE: **** _foundOldCount < _lookingCount ******"; + qCDebug(entities) << " FAILURE: **** _foundOldCount < _lookingCount ******"; stopExecution = true; } if (_foundNewCount < _lookingCount) { - qDebug() << " FAILURE: **** _foundNewCount < _lookingCount ******"; + qCDebug(entities) << " FAILURE: **** _foundNewCount < _lookingCount ******"; stopExecution = true; } - qDebug() << "--------------------------------------------------------------------------"; + qCDebug(entities) << "--------------------------------------------------------------------------"; if(stopExecution) { debug(); assert(false); @@ -54,20 +55,20 @@ void MovingEntitiesOperator::addEntityToMoveList(EntityItem* entity, const AACub AABox newCubeClamped = newCube.clamp(0.0f, (float)TREE_SCALE); if (_wantDebug) { - qDebug() << "MovingEntitiesOperator::addEntityToMoveList() -----------------------------"; - qDebug() << " newCube:" << newCube; - qDebug() << " newCubeClamped:" << newCubeClamped; + qCDebug(entities) << "MovingEntitiesOperator::addEntityToMoveList() -----------------------------"; + qCDebug(entities) << " newCube:" << newCube; + qCDebug(entities) << " newCubeClamped:" << newCubeClamped; if (oldContainingElement) { - qDebug() << " oldContainingElement:" << oldContainingElement->getAACube(); - qDebug() << " oldContainingElement->bestFitBounds(newCubeClamped):" + qCDebug(entities) << " oldContainingElement:" << oldContainingElement->getAACube(); + qCDebug(entities) << " oldContainingElement->bestFitBounds(newCubeClamped):" << oldContainingElement->bestFitBounds(newCubeClamped); } else { - qDebug() << " WARNING NO OLD CONTAINING ELEMENT!!!"; + qCDebug(entities) << " WARNING NO OLD CONTAINING ELEMENT!!!"; } } if (!oldContainingElement) { - qDebug() << "UNEXPECTED!!!! attempting to move entity "<< entity->getEntityItemID() + qCDebug(entities) << "UNEXPECTED!!!! attempting to move entity "<< entity->getEntityItemID() << "that has no containing element. "; return; // bail without adding. } @@ -88,22 +89,22 @@ void MovingEntitiesOperator::addEntityToMoveList(EntityItem* entity, const AACub _lookingCount++; if (_wantDebug) { - qDebug() << "MovingEntitiesOperator::addEntityToMoveList() -----------------------------"; - qDebug() << " details.entity:" << details.entity->getEntityItemID(); - qDebug() << " details.oldContainingElementCube:" << details.oldContainingElementCube; - qDebug() << " details.newCube:" << details.newCube; - qDebug() << " details.newCubeClamped:" << details.newCubeClamped; - qDebug() << " _lookingCount:" << _lookingCount; - qDebug() << "--------------------------------------------------------------------------"; + qCDebug(entities) << "MovingEntitiesOperator::addEntityToMoveList() -----------------------------"; + qCDebug(entities) << " details.entity:" << details.entity->getEntityItemID(); + qCDebug(entities) << " details.oldContainingElementCube:" << details.oldContainingElementCube; + qCDebug(entities) << " details.newCube:" << details.newCube; + qCDebug(entities) << " details.newCubeClamped:" << details.newCubeClamped; + qCDebug(entities) << " _lookingCount:" << _lookingCount; + qCDebug(entities) << "--------------------------------------------------------------------------"; } } else { if (_wantDebug) { - qDebug() << " oldContainingElement->bestFitBounds(newCubeClamped) IS BEST FIT... NOTHING TO DO"; + qCDebug(entities) << " oldContainingElement->bestFitBounds(newCubeClamped) IS BEST FIT... NOTHING TO DO"; } } if (_wantDebug) { - qDebug() << "--------------------------------------------------------------------------"; + qCDebug(entities) << "--------------------------------------------------------------------------"; } } @@ -119,15 +120,15 @@ bool MovingEntitiesOperator::shouldRecurseSubTree(OctreeElement* element) { foreach(const EntityToMoveDetails& details, _entitiesToMove) { if (_wantDebug) { - qDebug() << "MovingEntitiesOperator::shouldRecurseSubTree() details["<< detailIndex <<"]-----------------------------"; - qDebug() << " element:" << element->getAACube(); - qDebug() << " details.entity:" << details.entity->getEntityItemID(); - qDebug() << " details.oldContainingElementCube:" << details.oldContainingElementCube; - qDebug() << " details.newCube:" << details.newCube; - qDebug() << " details.newCubeClamped:" << details.newCubeClamped; - qDebug() << " elementCube.contains(details.newCube)" << elementCube.contains(details.newCube); - qDebug() << " elementCube.contains(details.newCubeClamped)" << elementCube.contains(details.newCubeClamped); - qDebug() << "--------------------------------------------------------------------------"; + qCDebug(entities) << "MovingEntitiesOperator::shouldRecurseSubTree() details["<< detailIndex <<"]-----------------------------"; + qCDebug(entities) << " element:" << element->getAACube(); + qCDebug(entities) << " details.entity:" << details.entity->getEntityItemID(); + qCDebug(entities) << " details.oldContainingElementCube:" << details.oldContainingElementCube; + qCDebug(entities) << " details.newCube:" << details.newCube; + qCDebug(entities) << " details.newCubeClamped:" << details.newCubeClamped; + qCDebug(entities) << " elementCube.contains(details.newCube)" << elementCube.contains(details.newCube); + qCDebug(entities) << " elementCube.contains(details.newCubeClamped)" << elementCube.contains(details.newCubeClamped); + qCDebug(entities) << "--------------------------------------------------------------------------"; } if (elementCube.contains(details.oldContainingElementCube) || elementCube.contains(details.newCubeClamped)) { @@ -163,17 +164,17 @@ bool MovingEntitiesOperator::preRecursion(OctreeElement* element) { foreach(const EntityToMoveDetails& details, _entitiesToMove) { if (_wantDebug) { - qDebug() << "MovingEntitiesOperator::preRecursion() details["<< detailIndex <<"]-----------------------------"; - qDebug() << " entityTreeElement:" << entityTreeElement->getAACube(); - qDebug() << " entityTreeElement->bestFitBounds(details.newCube):" << entityTreeElement->bestFitBounds(details.newCube); - qDebug() << " details.entity:" << details.entity->getEntityItemID(); - qDebug() << " details.oldContainingElementCube:" << details.oldContainingElementCube; - qDebug() << " entityTreeElement:" << entityTreeElement; - qDebug() << " details.newCube:" << details.newCube; - qDebug() << " details.newCubeClamped:" << details.newCubeClamped; - qDebug() << " _lookingCount:" << _lookingCount; - qDebug() << " _foundOldCount:" << _foundOldCount; - qDebug() << "--------------------------------------------------------------------------"; + qCDebug(entities) << "MovingEntitiesOperator::preRecursion() details["<< detailIndex <<"]-----------------------------"; + qCDebug(entities) << " entityTreeElement:" << entityTreeElement->getAACube(); + qCDebug(entities) << " entityTreeElement->bestFitBounds(details.newCube):" << entityTreeElement->bestFitBounds(details.newCube); + qCDebug(entities) << " details.entity:" << details.entity->getEntityItemID(); + qCDebug(entities) << " details.oldContainingElementCube:" << details.oldContainingElementCube; + qCDebug(entities) << " entityTreeElement:" << entityTreeElement; + qCDebug(entities) << " details.newCube:" << details.newCube; + qCDebug(entities) << " details.newCubeClamped:" << details.newCubeClamped; + qCDebug(entities) << " _lookingCount:" << _lookingCount; + qCDebug(entities) << " _foundOldCount:" << _foundOldCount; + qCDebug(entities) << "--------------------------------------------------------------------------"; } @@ -183,10 +184,10 @@ bool MovingEntitiesOperator::preRecursion(OctreeElement* element) { _foundOldCount++; //details.oldFound = true; // TODO: would be nice to add this optimization if (_wantDebug) { - qDebug() << "MovingEntitiesOperator::preRecursion() -----------------------------"; - qDebug() << " FOUND OLD - REMOVING"; - qDebug() << " entityTreeElement == details.oldContainingElement"; - qDebug() << "--------------------------------------------------------------------------"; + qCDebug(entities) << "MovingEntitiesOperator::preRecursion() -----------------------------"; + qCDebug(entities) << " FOUND OLD - REMOVING"; + qCDebug(entities) << " entityTreeElement == details.oldContainingElement"; + qCDebug(entities) << "--------------------------------------------------------------------------"; } } @@ -205,10 +206,10 @@ bool MovingEntitiesOperator::preRecursion(OctreeElement* element) { _foundNewCount++; //details.newFound = true; // TODO: would be nice to add this optimization if (_wantDebug) { - qDebug() << "MovingEntitiesOperator::preRecursion() -----------------------------"; - qDebug() << " FOUND NEW - ADDING"; - qDebug() << " entityTreeElement->bestFitBounds(details.newCube)"; - qDebug() << "--------------------------------------------------------------------------"; + qCDebug(entities) << "MovingEntitiesOperator::preRecursion() -----------------------------"; + qCDebug(entities) << " FOUND NEW - ADDING"; + qCDebug(entities) << " entityTreeElement->bestFitBounds(details.newCube)"; + qCDebug(entities) << "--------------------------------------------------------------------------"; } } detailIndex++; diff --git a/libraries/entities/src/ParticleEffectEntityItem.cpp b/libraries/entities/src/ParticleEffectEntityItem.cpp index b902dd63b8..45312f465b 100644 --- a/libraries/entities/src/ParticleEffectEntityItem.cpp +++ b/libraries/entities/src/ParticleEffectEntityItem.cpp @@ -42,6 +42,7 @@ #include "EntityTree.h" #include "EntityTreeElement.h" +#include "EntitiesLogging.h" #include "ParticleEffectEntityItem.h" const float ParticleEffectEntityItem::DEFAULT_ANIMATION_FRAME_INDEX = 0.0f; @@ -137,7 +138,7 @@ bool ParticleEffectEntityItem::setProperties(const EntityItemProperties& propert if (wantDebug) { uint64_t now = usecTimestampNow(); int elapsed = now - getLastEdited(); - qDebug() << "ParticleEffectEntityItem::setProperties() AFTER update... edited AGO=" << elapsed << + qCDebug(entities) << "ParticleEffectEntityItem::setProperties() AFTER update... edited AGO=" << elapsed << "now=" << now << " getLastEdited()=" << getLastEdited(); } setLastEdited(properties.getLastEdited()); @@ -278,11 +279,11 @@ void ParticleEffectEntityItem::update(const quint64& now) { void ParticleEffectEntityItem::debugDump() const { quint64 now = usecTimestampNow(); - qDebug() << "PA EFFECT EntityItem id:" << getEntityItemID() << "---------------------------------------------"; - qDebug() << " color:" << _color[0] << "," << _color[1] << "," << _color[2]; - qDebug() << " position:" << debugTreeVector(_position); - qDebug() << " dimensions:" << debugTreeVector(_dimensions); - qDebug() << " getLastEdited:" << debugTime(getLastEdited(), now); + qCDebug(entities) << "PA EFFECT EntityItem id:" << getEntityItemID() << "---------------------------------------------"; + qCDebug(entities) << " color:" << _color[0] << "," << _color[1] << "," << _color[2]; + qCDebug(entities) << " position:" << debugTreeVector(_position); + qCDebug(entities) << " dimensions:" << debugTreeVector(_dimensions); + qCDebug(entities) << " getLastEdited:" << debugTime(getLastEdited(), now); } void ParticleEffectEntityItem::updateShapeType(ShapeType type) { @@ -295,9 +296,9 @@ void ParticleEffectEntityItem::updateShapeType(ShapeType type) { void ParticleEffectEntityItem::setAnimationFrameIndex(float value) { #ifdef WANT_DEBUG if (isAnimatingSomething()) { - qDebug() << "ParticleEffectEntityItem::setAnimationFrameIndex()"; - qDebug() << " value:" << value; - qDebug() << " was:" << _animationLoop.getFrameIndex(); + qCDebug(entities) << "ParticleEffectEntityItem::setAnimationFrameIndex()"; + qCDebug(entities) << " value:" << value; + qCDebug(entities) << " was:" << _animationLoop.getFrameIndex(); } #endif _animationLoop.setFrameIndex(value); @@ -320,10 +321,10 @@ void ParticleEffectEntityItem::setAnimationSettings(const QString& value) { float frameIndex = settingsMap["frameIndex"].toFloat(); #ifdef WANT_DEBUG if (isAnimatingSomething()) { - qDebug() << "ParticleEffectEntityItem::setAnimationSettings() calling setAnimationFrameIndex()..."; - qDebug() << " settings:" << value; - qDebug() << " settingsMap[frameIndex]:" << settingsMap["frameIndex"]; - qDebug(" frameIndex: %20.5f", frameIndex); + qCDebug(entities) << "ParticleEffectEntityItem::setAnimationSettings() calling setAnimationFrameIndex()..."; + qCDebug(entities) << " settings:" << value; + qCDebug(entities) << " settingsMap[frameIndex]:" << settingsMap["frameIndex"]; + qCDebug(entities" frameIndex: %20.5f", frameIndex); } #endif diff --git a/libraries/entities/src/SphereEntityItem.cpp b/libraries/entities/src/SphereEntityItem.cpp index 483323ba4b..132ad43336 100644 --- a/libraries/entities/src/SphereEntityItem.cpp +++ b/libraries/entities/src/SphereEntityItem.cpp @@ -19,6 +19,7 @@ #include "EntityTree.h" #include "EntityTreeElement.h" +#include "EntitiesLogging.h" #include "SphereEntityItem.h" @@ -51,7 +52,7 @@ bool SphereEntityItem::setProperties(const EntityItemProperties& properties) { if (wantDebug) { uint64_t now = usecTimestampNow(); int elapsed = now - getLastEdited(); - qDebug() << "SphereEntityItem::setProperties() AFTER update... edited AGO=" << elapsed << + qCDebug(entities) << "SphereEntityItem::setProperties() AFTER update... edited AGO=" << elapsed << "now=" << now << " getLastEdited()=" << getLastEdited(); } setLastEdited(properties.getLastEdited()); @@ -120,10 +121,10 @@ bool SphereEntityItem::findDetailedRayIntersection(const glm::vec3& origin, cons void SphereEntityItem::debugDump() const { quint64 now = usecTimestampNow(); - qDebug() << "SHPERE EntityItem id:" << getEntityItemID() << "---------------------------------------------"; - qDebug() << " color:" << _color[0] << "," << _color[1] << "," << _color[2]; - qDebug() << " position:" << debugTreeVector(_position); - qDebug() << " dimensions:" << debugTreeVector(_dimensions); - qDebug() << " getLastEdited:" << debugTime(getLastEdited(), now); + qCDebug(entities) << "SHPERE EntityItem id:" << getEntityItemID() << "---------------------------------------------"; + qCDebug(entities) << " color:" << _color[0] << "," << _color[1] << "," << _color[2]; + qCDebug(entities) << " position:" << debugTreeVector(_position); + qCDebug(entities) << " dimensions:" << debugTreeVector(_dimensions); + qCDebug(entities) << " getLastEdited:" << debugTime(getLastEdited(), now); } diff --git a/libraries/entities/src/TextEntityItem.cpp b/libraries/entities/src/TextEntityItem.cpp index 2b35ee9a59..39a4d48d96 100644 --- a/libraries/entities/src/TextEntityItem.cpp +++ b/libraries/entities/src/TextEntityItem.cpp @@ -19,6 +19,7 @@ #include "EntityTree.h" #include "EntityTreeElement.h" +#include "EntitiesLogging.h" #include "TextEntityItem.h" @@ -76,7 +77,7 @@ bool TextEntityItem::setProperties(const EntityItemProperties& properties) { if (wantDebug) { uint64_t now = usecTimestampNow(); int elapsed = now - getLastEdited(); - qDebug() << "TextEntityItem::setProperties() AFTER update... edited AGO=" << elapsed << + qCDebug(entities) << "TextEntityItem::setProperties() AFTER update... edited AGO=" << elapsed << "now=" << now << " getLastEdited()=" << getLastEdited(); } setLastEdited(properties._lastEdited); diff --git a/libraries/entities/src/UpdateEntityOperator.cpp b/libraries/entities/src/UpdateEntityOperator.cpp index f93be2f563..6c1fac1ffc 100644 --- a/libraries/entities/src/UpdateEntityOperator.cpp +++ b/libraries/entities/src/UpdateEntityOperator.cpp @@ -12,6 +12,7 @@ #include "EntityItem.h" #include "EntityTree.h" #include "EntityTreeElement.h" +#include "EntitiesLogging.h" #include "UpdateEntityOperator.h" @@ -38,7 +39,7 @@ UpdateEntityOperator::UpdateEntityOperator(EntityTree* tree, assert(_containingElement && _existingEntity); if (_wantDebug) { - qDebug() << "UpdateEntityOperator::UpdateEntityOperator() -----------------------------"; + qCDebug(entities) << "UpdateEntityOperator::UpdateEntityOperator() -----------------------------"; } // Here we have a choice to make, do we want to "tight fit" the actual minimum for the @@ -63,7 +64,7 @@ UpdateEntityOperator::UpdateEntityOperator(EntityTree* tree, _properties.setDimensions(oldDimensions); if (_wantDebug) { - qDebug() << " ** setting properties dimensions - had position change, no dimension change **"; + qCDebug(entities) << " ** setting properties dimensions - had position change, no dimension change **"; } } @@ -72,7 +73,7 @@ UpdateEntityOperator::UpdateEntityOperator(EntityTree* tree, _properties.setPosition(oldPosition); if (_wantDebug) { - qDebug() << " ** setting properties position - had dimensions change, no position change **"; + qCDebug(entities) << " ** setting properties position - had dimensions change, no position change **"; } } @@ -86,7 +87,7 @@ UpdateEntityOperator::UpdateEntityOperator(EntityTree* tree, oldElementBestFit = _containingElement->bestFitBounds(_oldEntityBox); if (_wantDebug) { - qDebug() << " ** old Element best fit - no dimensions change, no position change **"; + qCDebug(entities) << " ** old Element best fit - no dimensions change, no position change **"; } } @@ -98,7 +99,7 @@ UpdateEntityOperator::UpdateEntityOperator(EntityTree* tree, _removeOld = true; // our properties are going to move us, so remember this for later processing if (_wantDebug) { - qDebug() << " **** UNUSUAL CASE **** no changes, but not best fit... consider it a move.... **"; + qCDebug(entities) << " **** UNUSUAL CASE **** no changes, but not best fit... consider it a move.... **"; } @@ -108,9 +109,9 @@ UpdateEntityOperator::UpdateEntityOperator(EntityTree* tree, _dontMove = true; if (_wantDebug) { - qDebug() << " **** TYPICAL NO MOVE CASE ****"; - qDebug() << " _properties.containsBoundsProperties():" << _properties.containsBoundsProperties(); - qDebug() << " oldElementBestFit:" << oldElementBestFit; + qCDebug(entities) << " **** TYPICAL NO MOVE CASE ****"; + qCDebug(entities) << " _properties.containsBoundsProperties():" << _properties.containsBoundsProperties(); + qCDebug(entities) << " oldElementBestFit:" << oldElementBestFit; } } else { @@ -118,7 +119,7 @@ UpdateEntityOperator::UpdateEntityOperator(EntityTree* tree, _removeOld = true; // our properties are going to move us, so remember this for later processing if (_wantDebug) { - qDebug() << " **** TYPICAL MOVE CASE ****"; + qCDebug(entities) << " **** TYPICAL MOVE CASE ****"; } } @@ -126,13 +127,13 @@ UpdateEntityOperator::UpdateEntityOperator(EntityTree* tree, if (_wantDebug) { - qDebug() << " _entityItemID:" << _entityItemID; - qDebug() << " _containingElementCube:" << _containingElementCube; - qDebug() << " _oldEntityCube:" << _oldEntityCube; - qDebug() << " _oldEntityBox:" << _oldEntityBox; - qDebug() << " _newEntityCube:" << _newEntityCube; - qDebug() << " _newEntityBox:" << _newEntityBox; - qDebug() << "--------------------------------------------------------------------------"; + qCDebug(entities) << " _entityItemID:" << _entityItemID; + qCDebug(entities) << " _containingElementCube:" << _containingElementCube; + qCDebug(entities) << " _oldEntityCube:" << _oldEntityCube; + qCDebug(entities) << " _oldEntityBox:" << _oldEntityBox; + qCDebug(entities) << " _newEntityCube:" << _newEntityCube; + qCDebug(entities) << " _newEntityBox:" << _newEntityBox; + qCDebug(entities) << "--------------------------------------------------------------------------"; } } @@ -151,12 +152,12 @@ bool UpdateEntityOperator::subTreeContainsOldEntity(OctreeElement* element) { if (_wantDebug) { bool elementContainsOldCube = element->getAACube().contains(_oldEntityCube); - qDebug() << "UpdateEntityOperator::subTreeContainsOldEntity()...."; - qDebug() << " element->getAACube()=" << element->getAACube(); - qDebug() << " _oldEntityCube=" << _oldEntityCube; - qDebug() << " _oldEntityBox=" << _oldEntityBox; - qDebug() << " elementContainsOldCube=" << elementContainsOldCube; - qDebug() << " elementContainsOldBox=" << elementContainsOldBox; + qCDebug(entities) << "UpdateEntityOperator::subTreeContainsOldEntity()...."; + qCDebug(entities) << " element->getAACube()=" << element->getAACube(); + qCDebug(entities) << " _oldEntityCube=" << _oldEntityCube; + qCDebug(entities) << " _oldEntityBox=" << _oldEntityBox; + qCDebug(entities) << " elementContainsOldCube=" << elementContainsOldCube; + qCDebug(entities) << " elementContainsOldBox=" << elementContainsOldBox; } return elementContainsOldBox; } @@ -166,12 +167,12 @@ bool UpdateEntityOperator::subTreeContainsNewEntity(OctreeElement* element) { if (_wantDebug) { bool elementContainsNewCube = element->getAACube().contains(_newEntityCube); - qDebug() << "UpdateEntityOperator::subTreeContainsNewEntity()...."; - qDebug() << " element->getAACube()=" << element->getAACube(); - qDebug() << " _newEntityCube=" << _newEntityCube; - qDebug() << " _newEntityBox=" << _newEntityBox; - qDebug() << " elementContainsNewCube=" << elementContainsNewCube; - qDebug() << " elementContainsNewBox=" << elementContainsNewBox; + qCDebug(entities) << "UpdateEntityOperator::subTreeContainsNewEntity()...."; + qCDebug(entities) << " element->getAACube()=" << element->getAACube(); + qCDebug(entities) << " _newEntityCube=" << _newEntityCube; + qCDebug(entities) << " _newEntityBox=" << _newEntityBox; + qCDebug(entities) << " elementContainsNewCube=" << elementContainsNewCube; + qCDebug(entities) << " elementContainsNewBox=" << elementContainsNewBox; } return elementContainsNewBox; @@ -196,12 +197,12 @@ bool UpdateEntityOperator::preRecursion(OctreeElement* element) { bool subtreeContainsNew = subTreeContainsNewEntity(element); if (_wantDebug) { - qDebug() << "---- UpdateEntityOperator::preRecursion().... ----"; - qDebug() << " element=" << element->getAACube(); - qDebug() << " subtreeContainsOld=" << subtreeContainsOld; - qDebug() << " subtreeContainsNew=" << subtreeContainsNew; - qDebug() << " _foundOld=" << _foundOld; - qDebug() << " _foundNew=" << _foundNew; + qCDebug(entities) << "---- UpdateEntityOperator::preRecursion().... ----"; + qCDebug(entities) << " element=" << element->getAACube(); + qCDebug(entities) << " subtreeContainsOld=" << subtreeContainsOld; + qCDebug(entities) << " subtreeContainsNew=" << subtreeContainsNew; + qCDebug(entities) << " _foundOld=" << _foundOld; + qCDebug(entities) << " _foundNew=" << _foundNew; } // If we haven't yet found the old entity, and this subTreeContains our old @@ -209,9 +210,9 @@ bool UpdateEntityOperator::preRecursion(OctreeElement* element) { if (!_foundOld && subtreeContainsOld) { if (_wantDebug) { - qDebug() << " OLD TREE CASE...."; - qDebug() << " entityTreeElement=" << entityTreeElement; - qDebug() << " _containingElement=" << _containingElement; + qCDebug(entities) << " OLD TREE CASE...."; + qCDebug(entities) << " entityTreeElement=" << entityTreeElement; + qCDebug(entities) << " _containingElement=" << _containingElement; } // If this is the element we're looking for, then ask it to remove the old entity @@ -219,7 +220,7 @@ bool UpdateEntityOperator::preRecursion(OctreeElement* element) { if (entityTreeElement == _containingElement) { if (_wantDebug) { - qDebug() << " *** it's the OLD ELEMENT! ***"; + qCDebug(entities) << " *** it's the OLD ELEMENT! ***"; } // If the containgElement IS NOT the best fit for the new entity properties @@ -228,7 +229,7 @@ bool UpdateEntityOperator::preRecursion(OctreeElement* element) { if (_removeOld) { if (_wantDebug) { - qDebug() << " *** REMOVING from ELEMENT ***"; + qCDebug(entities) << " *** REMOVING from ELEMENT ***"; } // the entity knows what element it's in, so we remove it from that one @@ -238,12 +239,12 @@ bool UpdateEntityOperator::preRecursion(OctreeElement* element) { _tree->setContainingElement(_entityItemID, NULL); if (oldElement != _containingElement) { - qDebug() << "WARNING entity moved during UpdateEntityOperator recursion"; + qCDebug(entities) << "WARNING entity moved during UpdateEntityOperator recursion"; _containingElement->removeEntityItem(_existingEntity); } if (_wantDebug) { - qDebug() << " *** REMOVING from MAP ***"; + qCDebug(entities) << " *** REMOVING from MAP ***"; } } _foundOld = true; @@ -258,17 +259,17 @@ bool UpdateEntityOperator::preRecursion(OctreeElement* element) { if (!_foundNew && subtreeContainsNew) { if (_wantDebug) { - qDebug() << " NEW TREE CASE...."; - qDebug() << " entityTreeElement=" << entityTreeElement; - qDebug() << " _containingElement=" << _containingElement; - qDebug() << " entityTreeElement->bestFitBounds(_newEntityBox)=" << entityTreeElement->bestFitBounds(_newEntityBox); + qCDebug(entities) << " NEW TREE CASE...."; + qCDebug(entities) << " entityTreeElement=" << entityTreeElement; + qCDebug(entities) << " _containingElement=" << _containingElement; + qCDebug(entities) << " entityTreeElement->bestFitBounds(_newEntityBox)=" << entityTreeElement->bestFitBounds(_newEntityBox); } // If this element is the best fit for the new entity properties, then add/or update it if (entityTreeElement->bestFitBounds(_newEntityBox)) { if (_wantDebug) { - qDebug() << " *** THIS ELEMENT IS BEST FIT ***"; + qCDebug(entities) << " *** THIS ELEMENT IS BEST FIT ***"; } EntityTreeElement* oldElement = _existingEntity->getElement(); @@ -276,20 +277,20 @@ bool UpdateEntityOperator::preRecursion(OctreeElement* element) { if (entityTreeElement == oldElement) { if (_wantDebug) { - qDebug() << " *** This is the same OLD ELEMENT ***"; + qCDebug(entities) << " *** This is the same OLD ELEMENT ***"; } // set the entity properties and mark our element as changed. _existingEntity->setProperties(_properties); if (_wantDebug) { - qDebug() << " *** set properties ***"; + qCDebug(entities) << " *** set properties ***"; } } else { // otherwise, this is an add case. if (oldElement) { oldElement->removeEntityItem(_existingEntity); if (oldElement != _containingElement) { - qDebug() << "WARNING entity moved during UpdateEntityOperator recursion"; + qCDebug(entities) << "WARNING entity moved during UpdateEntityOperator recursion"; } } entityTreeElement->addEntityItem(_existingEntity); @@ -297,7 +298,7 @@ bool UpdateEntityOperator::preRecursion(OctreeElement* element) { _existingEntity->setProperties(_properties); // still need to update the properties! if (_wantDebug) { - qDebug() << " *** ADDING ENTITY to ELEMENT and MAP and SETTING PROPERTIES ***"; + qCDebug(entities) << " *** ADDING ENTITY to ELEMENT and MAP and SETTING PROPERTIES ***"; } } _foundNew = true; // we found the new element @@ -308,8 +309,8 @@ bool UpdateEntityOperator::preRecursion(OctreeElement* element) { } if (_wantDebug) { - qDebug() << " FINAL --- keepSearching=" << keepSearching; - qDebug() << "--------------------------------------------------"; + qCDebug(entities) << " FINAL --- keepSearching=" << keepSearching; + qCDebug(entities) << "--------------------------------------------------"; } diff --git a/libraries/fbx/src/FBXReader.cpp b/libraries/fbx/src/FBXReader.cpp index 92ede537d1..b9b2f24034 100644 --- a/libraries/fbx/src/FBXReader.cpp +++ b/libraries/fbx/src/FBXReader.cpp @@ -29,7 +29,7 @@ #include #include "FBXReader.h" - +#include "ModelFormatLogging.h" // TOOL: Uncomment the following line to enable the filtering of all the unkwnon fields of a node so we can break point easily while loading a model with problems... //#define DEBUG_FBXREADER @@ -662,7 +662,7 @@ public: void printNode(const FBXNode& node, int indentLevel) { int indentLength = 2; QByteArray spaces(indentLevel * indentLength, ' '); - QDebug nodeDebug = qDebug(); + QDebug nodeDebug = qDebug(modelformat); nodeDebug.nospace() << spaces.data() << node.name.data() << ": "; foreach (const QVariant& property, node.properties) { @@ -971,7 +971,7 @@ ExtractedMesh extractMesh(const FBXNode& object, unsigned int& meshIndex) { data.attributes.push_back(attrib); } else { // WTF same names for different UVs? - qDebug() << "LayerElementUV #" << attrib.index << " is reusing the same name as #" << (*it) << ". Skip this texcoord attribute."; + qCDebug(modelformat) << "LayerElementUV #" << attrib.index << " is reusing the same name as #" << (*it) << ". Skip this texcoord attribute."; } } } else if (child.name == "LayerElementMaterial") { @@ -2191,7 +2191,7 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping, setTangents(extracted.mesh, part.triangleIndices.at(i + 2), part.triangleIndices.at(i)); } if ((part.triangleIndices.size() % 3) != 0){ - qDebug() << "Error in extractFBXGeometry part.triangleIndices.size() is not divisible by three "; + qCDebug(modelformat) << "Error in extractFBXGeometry part.triangleIndices.size() is not divisible by three "; } } } @@ -2212,7 +2212,7 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping, QString jointID = childMap.value(clusterID); fbxCluster.jointIndex = modelIDs.indexOf(jointID); if (fbxCluster.jointIndex == -1) { - qDebug() << "Joint not in model list: " << jointID; + qCDebug(modelformat) << "Joint not in model list: " << jointID; fbxCluster.jointIndex = 0; } fbxCluster.inverseBindMatrix = glm::inverse(cluster.transformLink) * modelTransform; @@ -2234,7 +2234,7 @@ FBXGeometry extractFBXGeometry(const FBXNode& node, const QVariantHash& mapping, FBXCluster cluster; cluster.jointIndex = modelIDs.indexOf(modelID); if (cluster.jointIndex == -1) { - qDebug() << "Model not in model list: " << modelID; + qCDebug(modelformat) << "Model not in model list: " << modelID; cluster.jointIndex = 0; } extracted.mesh.clusters.append(cluster); diff --git a/libraries/fbx/src/ModelFormatLogging.cpp b/libraries/fbx/src/ModelFormatLogging.cpp new file mode 100644 index 0000000000..e720b3c054 --- /dev/null +++ b/libraries/fbx/src/ModelFormatLogging.cpp @@ -0,0 +1,14 @@ +// +// ModelFormatLogging.cpp +// libraries/fbx/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "ModelFormatLogging.h" + +Q_LOGGING_CATEGORY(modelformat, "hifi.modelformat") diff --git a/libraries/fbx/src/ModelFormatLogging.h b/libraries/fbx/src/ModelFormatLogging.h new file mode 100644 index 0000000000..19c7c27322 --- /dev/null +++ b/libraries/fbx/src/ModelFormatLogging.h @@ -0,0 +1,19 @@ +// +// ModelFormatLogging.h +// libraries/fbx/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_ModelFormatLogging_h +#define hifi_ModelFormatLogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(modelformat) + +#endif // hifi_ModelFormatLogging_h diff --git a/libraries/fbx/src/OBJReader.cpp b/libraries/fbx/src/OBJReader.cpp index f7b5a3b10d..ddb2c6ba31 100644 --- a/libraries/fbx/src/OBJReader.cpp +++ b/libraries/fbx/src/OBJReader.cpp @@ -19,9 +19,11 @@ #include "FBXReader.h" #include "OBJReader.h" #include "Shape.h" +#include "ModelFormatLogging.h" -QHash COMMENT_SCALE_HINTS; +QHash COMMENT_SCALE_HINTS = {{"This file uses centimeters as units", 1.0f / 100.0f}, + {"This file uses millimeters as units", 1.0f / 1000.0f}}; class OBJTokenizer { @@ -50,11 +52,6 @@ private: OBJTokenizer::OBJTokenizer(QIODevice* device) : _device(device), _pushedBackToken(-1) { - // This is a list of comments that exports use to hint at scaling - if (COMMENT_SCALE_HINTS.isEmpty()) { - COMMENT_SCALE_HINTS["This file uses centimeters as units"] = 1.0f / 100.0f; - COMMENT_SCALE_HINTS["This file uses millimeters as units"] = 1.0f / 1000.0f; - } } @@ -73,7 +70,6 @@ int OBJTokenizer::nextToken() { switch (ch) { case '#': { _comment = _device->readLine(); // stash comment for a future call to getComment - qDebug() << "COMMENT:" << _comment; return COMMENT_TOKEN; } @@ -299,7 +295,7 @@ bool parseOBJGroup(OBJTokenizer &tokenizer, const QVariantHash& mapping, } } else { // something we don't (yet) care about - // qDebug() << "OBJ parser is skipping a line with" << token; + // qCDebug(modelformat) << "OBJ parser is skipping a line with" << token; tokenizer.skipLine(); } } @@ -436,7 +432,7 @@ FBXGeometry readOBJ(QIODevice* device, const QVariantHash& mapping) { } } catch(const std::exception& e) { - qDebug() << "something went wrong in OBJ reader"; + qCDebug(modelformat) << "something went wrong in OBJ reader"; } return geometry; @@ -445,73 +441,73 @@ FBXGeometry readOBJ(QIODevice* device, const QVariantHash& mapping) { void fbxDebugDump(const FBXGeometry& fbxgeo) { - qDebug() << "---------------- fbxGeometry ----------------"; - qDebug() << " hasSkeletonJoints =" << fbxgeo.hasSkeletonJoints; - qDebug() << " offset =" << fbxgeo.offset; - qDebug() << " attachments.count() = " << fbxgeo.attachments.count(); - qDebug() << " meshes.count() =" << fbxgeo.meshes.count(); + qCDebug(modelformat) << "---------------- fbxGeometry ----------------"; + qCDebug(modelformat) << " hasSkeletonJoints =" << fbxgeo.hasSkeletonJoints; + qCDebug(modelformat) << " offset =" << fbxgeo.offset; + qCDebug(modelformat) << " attachments.count() = " << fbxgeo.attachments.count(); + qCDebug(modelformat) << " meshes.count() =" << fbxgeo.meshes.count(); foreach (FBXMesh mesh, fbxgeo.meshes) { - qDebug() << " vertices.count() =" << mesh.vertices.count(); - qDebug() << " normals.count() =" << mesh.normals.count(); + qCDebug(modelformat) << " vertices.count() =" << mesh.vertices.count(); + qCDebug(modelformat) << " normals.count() =" << mesh.normals.count(); if (mesh.normals.count() == mesh.vertices.count()) { for (int i = 0; i < mesh.normals.count(); i++) { - qDebug() << " " << mesh.vertices[ i ] << mesh.normals[ i ]; + qCDebug(modelformat) << " " << mesh.vertices[ i ] << mesh.normals[ i ]; } } - qDebug() << " tangents.count() =" << mesh.tangents.count(); - qDebug() << " colors.count() =" << mesh.colors.count(); - qDebug() << " texCoords.count() =" << mesh.texCoords.count(); - qDebug() << " texCoords1.count() =" << mesh.texCoords1.count(); - qDebug() << " clusterIndices.count() =" << mesh.clusterIndices.count(); - qDebug() << " clusterWeights.count() =" << mesh.clusterWeights.count(); - qDebug() << " meshExtents =" << mesh.meshExtents; - qDebug() << " modelTransform =" << mesh.modelTransform; - qDebug() << " parts.count() =" << mesh.parts.count(); + qCDebug(modelformat) << " tangents.count() =" << mesh.tangents.count(); + qCDebug(modelformat) << " colors.count() =" << mesh.colors.count(); + qCDebug(modelformat) << " texCoords.count() =" << mesh.texCoords.count(); + qCDebug(modelformat) << " texCoords1.count() =" << mesh.texCoords1.count(); + qCDebug(modelformat) << " clusterIndices.count() =" << mesh.clusterIndices.count(); + qCDebug(modelformat) << " clusterWeights.count() =" << mesh.clusterWeights.count(); + qCDebug(modelformat) << " meshExtents =" << mesh.meshExtents; + qCDebug(modelformat) << " modelTransform =" << mesh.modelTransform; + qCDebug(modelformat) << " parts.count() =" << mesh.parts.count(); foreach (FBXMeshPart meshPart, mesh.parts) { - qDebug() << " quadIndices.count() =" << meshPart.quadIndices.count(); - qDebug() << " triangleIndices.count() =" << meshPart.triangleIndices.count(); - qDebug() << " diffuseColor =" << meshPart.diffuseColor; - qDebug() << " specularColor =" << meshPart.specularColor; - qDebug() << " emissiveColor =" << meshPart.emissiveColor; - qDebug() << " emissiveParams =" << meshPart.emissiveParams; - qDebug() << " shininess =" << meshPart.shininess; - qDebug() << " opacity =" << meshPart.opacity; - qDebug() << " materialID =" << meshPart.materialID; + qCDebug(modelformat) << " quadIndices.count() =" << meshPart.quadIndices.count(); + qCDebug(modelformat) << " triangleIndices.count() =" << meshPart.triangleIndices.count(); + qCDebug(modelformat) << " diffuseColor =" << meshPart.diffuseColor; + qCDebug(modelformat) << " specularColor =" << meshPart.specularColor; + qCDebug(modelformat) << " emissiveColor =" << meshPart.emissiveColor; + qCDebug(modelformat) << " emissiveParams =" << meshPart.emissiveParams; + qCDebug(modelformat) << " shininess =" << meshPart.shininess; + qCDebug(modelformat) << " opacity =" << meshPart.opacity; + qCDebug(modelformat) << " materialID =" << meshPart.materialID; } - qDebug() << " clusters.count() =" << mesh.clusters.count(); + qCDebug(modelformat) << " clusters.count() =" << mesh.clusters.count(); foreach (FBXCluster cluster, mesh.clusters) { - qDebug() << " jointIndex =" << cluster.jointIndex; - qDebug() << " inverseBindMatrix =" << cluster.inverseBindMatrix; + qCDebug(modelformat) << " jointIndex =" << cluster.jointIndex; + qCDebug(modelformat) << " inverseBindMatrix =" << cluster.inverseBindMatrix; } } - qDebug() << " jointIndices =" << fbxgeo.jointIndices; - qDebug() << " joints.count() =" << fbxgeo.joints.count(); + qCDebug(modelformat) << " jointIndices =" << fbxgeo.jointIndices; + qCDebug(modelformat) << " joints.count() =" << fbxgeo.joints.count(); foreach (FBXJoint joint, fbxgeo.joints) { - qDebug() << " isFree =" << joint.isFree; - qDebug() << " freeLineage" << joint.freeLineage; - qDebug() << " parentIndex" << joint.parentIndex; - qDebug() << " distanceToParent" << joint.distanceToParent; - qDebug() << " boneRadius" << joint.boneRadius; - qDebug() << " translation" << joint.translation; - qDebug() << " preTransform" << joint.preTransform; - qDebug() << " preRotation" << joint.preRotation; - qDebug() << " rotation" << joint.rotation; - qDebug() << " postRotation" << joint.postRotation; - qDebug() << " postTransform" << joint.postTransform; - qDebug() << " transform" << joint.transform; - qDebug() << " rotationMin" << joint.rotationMin; - qDebug() << " rotationMax" << joint.rotationMax; - qDebug() << " inverseDefaultRotation" << joint.inverseDefaultRotation; - qDebug() << " inverseBindRotation" << joint.inverseBindRotation; - qDebug() << " bindTransform" << joint.bindTransform; - qDebug() << " name" << joint.name; - qDebug() << " shapePosition" << joint.shapePosition; - qDebug() << " shapeRotation" << joint.shapeRotation; - qDebug() << " shapeType" << joint.shapeType; - qDebug() << " isSkeletonJoint" << joint.isSkeletonJoint; + qCDebug(modelformat) << " isFree =" << joint.isFree; + qCDebug(modelformat) << " freeLineage" << joint.freeLineage; + qCDebug(modelformat) << " parentIndex" << joint.parentIndex; + qCDebug(modelformat) << " distanceToParent" << joint.distanceToParent; + qCDebug(modelformat) << " boneRadius" << joint.boneRadius; + qCDebug(modelformat) << " translation" << joint.translation; + qCDebug(modelformat) << " preTransform" << joint.preTransform; + qCDebug(modelformat) << " preRotation" << joint.preRotation; + qCDebug(modelformat) << " rotation" << joint.rotation; + qCDebug(modelformat) << " postRotation" << joint.postRotation; + qCDebug(modelformat) << " postTransform" << joint.postTransform; + qCDebug(modelformat) << " transform" << joint.transform; + qCDebug(modelformat) << " rotationMin" << joint.rotationMin; + qCDebug(modelformat) << " rotationMax" << joint.rotationMax; + qCDebug(modelformat) << " inverseDefaultRotation" << joint.inverseDefaultRotation; + qCDebug(modelformat) << " inverseBindRotation" << joint.inverseBindRotation; + qCDebug(modelformat) << " bindTransform" << joint.bindTransform; + qCDebug(modelformat) << " name" << joint.name; + qCDebug(modelformat) << " shapePosition" << joint.shapePosition; + qCDebug(modelformat) << " shapeRotation" << joint.shapeRotation; + qCDebug(modelformat) << " shapeType" << joint.shapeType; + qCDebug(modelformat) << " isSkeletonJoint" << joint.isSkeletonJoint; } - qDebug() << "\n"; + qCDebug(modelformat) << "\n"; } diff --git a/libraries/gpu/src/gpu/GLBackend.cpp b/libraries/gpu/src/gpu/GLBackend.cpp index 1199251669..e1eff5f3cd 100644 --- a/libraries/gpu/src/gpu/GLBackend.cpp +++ b/libraries/gpu/src/gpu/GLBackend.cpp @@ -8,6 +8,7 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include "GPULogging.h" #include "GLBackendShared.h" GLBackend::CommandCall GLBackend::_commandCalls[Batch::NUM_COMMANDS] = @@ -102,25 +103,25 @@ void GLBackend::checkGLError() { else { switch (error) { case GL_INVALID_ENUM: - qDebug() << "An unacceptable value is specified for an enumerated argument.The offending command is ignored and has no other side effect than to set the error flag."; + qCDebug(gpulogging) << "An unacceptable value is specified for an enumerated argument.The offending command is ignored and has no other side effect than to set the error flag."; break; case GL_INVALID_VALUE: - qDebug() << "A numeric argument is out of range.The offending command is ignored and has no other side effect than to set the error flag"; + qCDebug(gpulogging) << "A numeric argument is out of range.The offending command is ignored and has no other side effect than to set the error flag"; break; case GL_INVALID_OPERATION: - qDebug() << "The specified operation is not allowed in the current state.The offending command is ignored and has no other side effect than to set the error flag.."; + qCDebug(gpulogging) << "The specified operation is not allowed in the current state.The offending command is ignored and has no other side effect than to set the error flag.."; break; case GL_INVALID_FRAMEBUFFER_OPERATION: - qDebug() << "The framebuffer object is not complete.The offending command is ignored and has no other side effect than to set the error flag."; + qCDebug(gpulogging) << "The framebuffer object is not complete.The offending command is ignored and has no other side effect than to set the error flag."; break; case GL_OUT_OF_MEMORY: - qDebug() << "There is not enough memory left to execute the command.The state of the GL is undefined, except for the state of the error flags, after this error is recorded."; + qCDebug(gpulogging) << "There is not enough memory left to execute the command.The state of the GL is undefined, except for the state of the error flags, after this error is recorded."; break; case GL_STACK_UNDERFLOW: - qDebug() << "An attempt has been made to perform an operation that would cause an internal stack to underflow."; + qCDebug(gpulogging) << "An attempt has been made to perform an operation that would cause an internal stack to underflow."; break; case GL_STACK_OVERFLOW: - qDebug() << "An attempt has been made to perform an operation that would cause an internal stack to overflow."; + qCDebug(gpulogging) << "An attempt has been made to perform an operation that would cause an internal stack to overflow."; break; } } diff --git a/libraries/gpu/src/gpu/GLBackendShader.cpp b/libraries/gpu/src/gpu/GLBackendShader.cpp index 3f794575fe..75b3df3e33 100755 --- a/libraries/gpu/src/gpu/GLBackendShader.cpp +++ b/libraries/gpu/src/gpu/GLBackendShader.cpp @@ -8,8 +8,8 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include "GPULogging.h" #include "GLBackendShared.h" - #include "Format.h" using namespace gpu; @@ -88,7 +88,7 @@ void makeBindings(GLBackend::GLShader* shader) { GLint linked = 0; glGetProgramiv(glprogram, GL_LINK_STATUS, &linked); if (!linked) { - qDebug() << "GLShader::makeBindings - failed to link after assigning slotBindings?"; + qCDebug(gpulogging) << "GLShader::makeBindings - failed to link after assigning slotBindings?"; } // now assign the ubo binding, then DON't relink! @@ -113,7 +113,7 @@ GLBackend::GLShader* compileShader(const Shader& shader) { // Any GLSLprogram ? normally yes... const std::string& shaderSource = shader.getSource().getCode(); if (shaderSource.empty()) { - qDebug() << "GLShader::compileShader - no GLSL shader source code ? so failed to create"; + qCDebug(gpulogging) << "GLShader::compileShader - no GLSL shader source code ? so failed to create"; return nullptr; } @@ -124,7 +124,7 @@ GLBackend::GLShader* compileShader(const Shader& shader) { // Create the shader object GLuint glshader = glCreateShader(shaderDomain); if (!glshader) { - qDebug() << "GLShader::compileShader - failed to create the gl shader object"; + qCDebug(gpulogging) << "GLShader::compileShader - failed to create the gl shader object"; return nullptr; } @@ -156,8 +156,8 @@ GLBackend::GLShader* compileShader(const Shader& shader) { char* temp = new char[infoLength] ; glGetShaderInfoLog(glshader, infoLength, NULL, temp); - qDebug() << "GLShader::compileShader - failed to compile the gl shader object:"; - qDebug() << temp; + qCDebug(gpulogging) << "GLShader::compileShader - failed to compile the gl shader object:"; + qCDebug(gpulogging) << temp; /* filestream.open("debugshader.glsl.info.txt"); @@ -177,7 +177,7 @@ GLBackend::GLShader* compileShader(const Shader& shader) { // so far so good, program is almost done, need to link: GLuint glprogram = glCreateProgram(); if (!glprogram) { - qDebug() << "GLShader::compileShader - failed to create the gl shader & gl program object"; + qCDebug(gpulogging) << "GLShader::compileShader - failed to create the gl shader & gl program object"; return nullptr; } @@ -205,8 +205,8 @@ GLBackend::GLShader* compileShader(const Shader& shader) { char* temp = new char[infoLength] ; glGetProgramInfoLog(glprogram, infoLength, NULL, temp); - qDebug() << "GLShader::compileShader - failed to LINK the gl program object :"; - qDebug() << temp; + qCDebug(gpulogging) << "GLShader::compileShader - failed to LINK the gl program object :"; + qCDebug(gpulogging) << temp; /* filestream.open("debugshader.glsl.info.txt"); @@ -243,7 +243,7 @@ GLBackend::GLShader* compileProgram(const Shader& program) { for (auto subShader : program.getShaders()) { GLuint so = GLBackend::getShaderID(subShader); if (!so) { - qDebug() << "GLShader::compileProgram - One of the shaders of the program is not compiled?"; + qCDebug(gpulogging) << "GLShader::compileProgram - One of the shaders of the program is not compiled?"; return nullptr; } shaderObjects.push_back(so); @@ -252,7 +252,7 @@ GLBackend::GLShader* compileProgram(const Shader& program) { // so far so good, program is almost done, need to link: GLuint glprogram = glCreateProgram(); if (!glprogram) { - qDebug() << "GLShader::compileProgram - failed to create the gl program object"; + qCDebug(gpulogging) << "GLShader::compileProgram - failed to create the gl program object"; return nullptr; } @@ -285,8 +285,8 @@ GLBackend::GLShader* compileProgram(const Shader& program) { char* temp = new char[infoLength] ; glGetProgramInfoLog(glprogram, infoLength, NULL, temp); - qDebug() << "GLShader::compileProgram - failed to LINK the gl program object :"; - qDebug() << temp; + qCDebug(gpulogging) << "GLShader::compileProgram - failed to LINK the gl program object :"; + qCDebug(gpulogging) << temp; /* filestream.open("debugshader.glsl.info.txt"); diff --git a/libraries/gpu/src/gpu/GLBackendTexture.cpp b/libraries/gpu/src/gpu/GLBackendTexture.cpp index 6875abbc33..2bbb3d633f 100755 --- a/libraries/gpu/src/gpu/GLBackendTexture.cpp +++ b/libraries/gpu/src/gpu/GLBackendTexture.cpp @@ -8,6 +8,7 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include "GPULogging.h" #include "GLBackendShared.h" @@ -48,7 +49,7 @@ public: texel.internalFormat = GL_DEPTH_COMPONENT; break; default: - qDebug() << "Unknown combination of texel format"; + qCDebug(gpulogging) << "Unknown combination of texel format"; } break; } @@ -66,7 +67,7 @@ public: texel.internalFormat = GL_DEPTH_STENCIL; break; default: - qDebug() << "Unknown combination of texel format"; + qCDebug(gpulogging) << "Unknown combination of texel format"; } break; @@ -83,7 +84,7 @@ public: texel.internalFormat = GL_RGB; break; default: - qDebug() << "Unknown combination of texel format"; + qCDebug(gpulogging) << "Unknown combination of texel format"; } break; @@ -120,13 +121,13 @@ public: texel.internalFormat = GL_SRGB_ALPHA; break; default: - qDebug() << "Unknown combination of texel format"; + qCDebug(gpulogging) << "Unknown combination of texel format"; } break; } default: - qDebug() << "Unknown combination of texel format"; + qCDebug(gpulogging) << "Unknown combination of texel format"; } return texel; } else { @@ -146,7 +147,7 @@ public: texel.internalFormat = GL_DEPTH_COMPONENT; break; default: - qDebug() << "Unknown combination of texel format"; + qCDebug(gpulogging) << "Unknown combination of texel format"; } break; @@ -165,7 +166,7 @@ public: texel.internalFormat = GL_DEPTH_STENCIL; break; default: - qDebug() << "Unknown combination of texel format"; + qCDebug(gpulogging) << "Unknown combination of texel format"; } break; @@ -186,7 +187,7 @@ public: texel.internalFormat = GL_SRGB; // standard 2.2 gamma correction color break; default: - qDebug() << "Unknown combination of texel format"; + qCDebug(gpulogging) << "Unknown combination of texel format"; } break; } @@ -209,13 +210,13 @@ public: texel.internalFormat = GL_SRGB_ALPHA; // standard 2.2 gamma correction color break; default: - qDebug() << "Unknown combination of texel format"; + qCDebug(gpulogging) << "Unknown combination of texel format"; } break; } default: - qDebug() << "Unknown combination of texel format"; + qCDebug(gpulogging) << "Unknown combination of texel format"; } return texel; } @@ -317,7 +318,7 @@ GLBackend::GLTexture* GLBackend::syncGPUObject(const Texture& texture) { break; } default: - qDebug() << "GLBackend::syncGPUObject(const Texture&) case for Texture Type " << texture.getType() << " not supported"; + qCDebug(gpulogging) << "GLBackend::syncGPUObject(const Texture&) case for Texture Type " << texture.getType() << " not supported"; } CHECK_GL_ERROR(); diff --git a/libraries/gpu/src/gpu/GPULogging.cpp b/libraries/gpu/src/gpu/GPULogging.cpp new file mode 100644 index 0000000000..972834a729 --- /dev/null +++ b/libraries/gpu/src/gpu/GPULogging.cpp @@ -0,0 +1,14 @@ +// +// GPULogging.cpp +// libraries/GPU/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "GPULogging.h" + +Q_LOGGING_CATEGORY(gpulogging, "hifi.gpu") diff --git a/libraries/gpu/src/gpu/GPULogging.h b/libraries/gpu/src/gpu/GPULogging.h new file mode 100644 index 0000000000..15acc15922 --- /dev/null +++ b/libraries/gpu/src/gpu/GPULogging.h @@ -0,0 +1,20 @@ +// +// GPULogging.h +// libraries/gpu/src/gpu/ +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_GPULogging_h +#define hifi_GPULogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(gpulogging) + +#endif // hifi_GPULogging_h + diff --git a/libraries/networking/src/AccountManager.cpp b/libraries/networking/src/AccountManager.cpp index 46c6418c63..1f1ada5592 100644 --- a/libraries/networking/src/AccountManager.cpp +++ b/libraries/networking/src/AccountManager.cpp @@ -29,6 +29,7 @@ #include "SharedUtil.h" #include "AccountManager.h" +#include "NetworkLogging.h" const bool VERBOSE_HTTP_REQUEST_DEBUGGING = false; @@ -98,9 +99,9 @@ void AccountManager::logout() { QStringList path = QStringList() << ACCOUNTS_GROUP << keyURLString; Setting::Handle(path).remove(); - qDebug() << "Removed account info for" << _authURL << "from in-memory accounts and .ini file"; + qCDebug(networking) << "Removed account info for" << _authURL << "from in-memory accounts and .ini file"; } else { - qDebug() << "Cleared data server account info in account manager."; + qCDebug(networking) << "Cleared data server account info in account manager."; } emit logoutComplete(); @@ -127,7 +128,7 @@ void AccountManager::setAuthURL(const QUrl& authURL) { if (_authURL != authURL) { _authURL = authURL; - qDebug() << "AccountManager URL for authenticated requests has been changed to" << qPrintable(_authURL.toString()); + qCDebug(networking) << "AccountManager URL for authenticated requests has been changed to" << qPrintable(_authURL.toString()); if (_shouldPersistToSettingsFile) { // check if there are existing access tokens to load from settings @@ -142,7 +143,7 @@ void AccountManager::setAuthURL(const QUrl& authURL) { if (keyURL == _authURL) { // pull out the stored access token and store it in memory _accountInfo = settings.value(key).value(); - qDebug() << "Found a data-server access token for" << qPrintable(keyURL.toString()); + qCDebug(networking) << "Found a data-server access token for" << qPrintable(keyURL.toString()); // profile info isn't guaranteed to be saved too if (_accountInfo.hasProfile()) { @@ -197,7 +198,7 @@ void AccountManager::sendRequest(const QString& path, _accountInfo.getAccessToken().authorizationHeaderValue()); } else { if (authType == AccountManagerAuth::Required) { - qDebug() << "No valid access token present. Bailing on invoked request to" + qCDebug(networking) << "No valid access token present. Bailing on invoked request to" << path << "that requires authentication"; return; } @@ -208,10 +209,10 @@ void AccountManager::sendRequest(const QString& path, networkRequest.setUrl(requestURL); if (VERBOSE_HTTP_REQUEST_DEBUGGING) { - qDebug() << "Making a request to" << qPrintable(requestURL.toString()); + qCDebug(networking) << "Making a request to" << qPrintable(requestURL.toString()); if (!dataByteArray.isEmpty()) { - qDebug() << "The POST/PUT body -" << QString(dataByteArray); + qCDebug(networking) << "The POST/PUT body -" << QString(dataByteArray); } } @@ -298,8 +299,8 @@ void AccountManager::passSuccessToCallback(QNetworkReply* requestReply) { } else { if (VERBOSE_HTTP_REQUEST_DEBUGGING) { - qDebug() << "Received JSON response from data-server that has no matching callback."; - qDebug() << QJsonDocument::fromJson(requestReply->readAll()); + qCDebug(networking) << "Received JSON response from data-server that has no matching callback."; + qCDebug(networking) << QJsonDocument::fromJson(requestReply->readAll()); } } } @@ -316,9 +317,9 @@ void AccountManager::passErrorToCallback(QNetworkReply* requestReply) { _pendingCallbackMap.remove(requestReply); } else { if (VERBOSE_HTTP_REQUEST_DEBUGGING) { - qDebug() << "Received error response from data-server that has no matching callback."; - qDebug() << "Error" << requestReply->error() << "-" << requestReply->errorString(); - qDebug() << requestReply->readAll(); + qCDebug(networking) << "Received error response from data-server that has no matching callback."; + qCDebug(networking) << "Error" << requestReply->error() << "-" << requestReply->errorString(); + qCDebug(networking) << requestReply->readAll(); } } } @@ -337,7 +338,7 @@ bool AccountManager::hasValidAccessToken() { if (_accountInfo.getAccessToken().token.isEmpty() || _accountInfo.getAccessToken().isExpired()) { if (VERBOSE_HTTP_REQUEST_DEBUGGING) { - qDebug() << "An access token is required for requests to" << qPrintable(_authURL.toString()); + qCDebug(networking) << "An access token is required for requests to" << qPrintable(_authURL.toString()); } return false; @@ -365,7 +366,7 @@ void AccountManager::setAccessTokenForCurrentAuthURL(const QString& accessToken) OAuthAccessToken newOAuthToken; newOAuthToken.token = accessToken; - qDebug() << "Setting new account manager access token to" << accessToken; + qCDebug(networking) << "Setting new account manager access token to" << accessToken; _accountInfo.setAccessToken(newOAuthToken); } @@ -409,13 +410,13 @@ void AccountManager::requestAccessTokenFinished() { if (!rootObject.contains("access_token") || !rootObject.contains("expires_in") || !rootObject.contains("token_type")) { // TODO: error handling - malformed token response - qDebug() << "Received a response for password grant that is missing one or more expected values."; + qCDebug(networking) << "Received a response for password grant that is missing one or more expected values."; } else { // clear the path from the response URL so we have the right root URL for this access token QUrl rootURL = requestReply->url(); rootURL.setPath(""); - qDebug() << "Storing an account with access-token for" << qPrintable(rootURL.toString()); + qCDebug(networking) << "Storing an account with access-token for" << qPrintable(rootURL.toString()); _accountInfo = DataServerAccountInfo(); _accountInfo.setAccessTokenFromJSON(rootObject); @@ -428,14 +429,14 @@ void AccountManager::requestAccessTokenFinished() { } } else { // TODO: error handling - qDebug() << "Error in response for password grant -" << rootObject["error_description"].toString(); + qCDebug(networking) << "Error in response for password grant -" << rootObject["error_description"].toString(); emit loginFailed(); } } void AccountManager::requestAccessTokenError(QNetworkReply::NetworkError error) { // TODO: error handling - qDebug() << "AccountManager requestError - " << error; + qCDebug(networking) << "AccountManager requestError - " << error; } void AccountManager::requestProfile() { @@ -472,13 +473,13 @@ void AccountManager::requestProfileFinished() { } else { // TODO: error handling - qDebug() << "Error in response for profile"; + qCDebug(networking) << "Error in response for profile"; } } void AccountManager::requestProfileError(QNetworkReply::NetworkError error) { // TODO: error handling - qDebug() << "AccountManager requestProfileError - " << error; + qCDebug(networking) << "AccountManager requestProfileError - " << error; } void AccountManager::generateNewKeypair() { @@ -498,13 +499,13 @@ void AccountManager::generateNewKeypair() { keypairGenerator->moveToThread(generateThread); - qDebug() << "Starting worker thread to generate 2048-bit RSA key-pair."; + qCDebug(networking) << "Starting worker thread to generate 2048-bit RSA key-pair."; generateThread->start(); } void AccountManager::processGeneratedKeypair(const QByteArray& publicKey, const QByteArray& privateKey) { - qDebug() << "Generated 2048-bit RSA key-pair. Storing private key and uploading public key."; + qCDebug(networking) << "Generated 2048-bit RSA key-pair. Storing private key and uploading public key."; // set the private key on our data-server account info _accountInfo.setPrivateKey(privateKey); diff --git a/libraries/networking/src/AddressManager.cpp b/libraries/networking/src/AddressManager.cpp index f8b297c025..73aaa63844 100644 --- a/libraries/networking/src/AddressManager.cpp +++ b/libraries/networking/src/AddressManager.cpp @@ -21,7 +21,7 @@ #include #include "NodeList.h" - +#include "NetworkLogging.h" #include "AddressManager.h" const QString ADDRESS_MANAGER_SETTINGS_GROUP = "AddressManager"; @@ -74,7 +74,7 @@ const QString AddressManager::currentPath(bool withOrientation) const { QString orientationString = createByteArray(_orientationGetter()); pathString += "/" + orientationString; } else { - qDebug() << "Cannot add orientation to path without a getter for position." + qCDebug(networking) << "Cannot add orientation to path without a getter for position." << "Call AddressManager::setOrientationGetter to pass a function that will return a glm::quat"; } @@ -82,7 +82,7 @@ const QString AddressManager::currentPath(bool withOrientation) const { return pathString; } else { - qDebug() << "Cannot create address path without a getter for position." + qCDebug(networking) << "Cannot create address path without a getter for position." << "Call AddressManager::setPositionGetter to pass a function that will return a const glm::vec3&"; return QString(); } @@ -105,7 +105,7 @@ const JSONCallbackParameters& AddressManager::apiCallbackParameters() { bool AddressManager::handleUrl(const QUrl& lookupUrl) { if (lookupUrl.scheme() == HIFI_URL_SCHEME) { - qDebug() << "Trying to go to URL" << lookupUrl.toString(); + qCDebug(networking) << "Trying to go to URL" << lookupUrl.toString(); // there are 4 possible lookup strings @@ -132,7 +132,7 @@ bool AddressManager::handleUrl(const QUrl& lookupUrl) { return true; } else if (lookupUrl.toString().startsWith('/')) { - qDebug() << "Going to relative path" << lookupUrl.path(); + qCDebug(networking) << "Going to relative path" << lookupUrl.path(); // if this is a relative path then handle it as a relative viewpoint handleRelativeViewpoint(lookupUrl.path()); @@ -211,7 +211,7 @@ void AddressManager::goToAddressFromObject(const QVariantMap& dataObject, const ? domainObject[DOMAIN_NETWORK_PORT_KEY].toUInt() : DEFAULT_DOMAIN_SERVER_PORT; - qDebug() << "Possible domain change required to connect to" << domainHostname + qCDebug(networking) << "Possible domain change required to connect to" << domainHostname << "on" << domainPort; emit possibleDomainChangeRequired(domainHostname, domainPort); } else { @@ -221,7 +221,7 @@ void AddressManager::goToAddressFromObject(const QVariantMap& dataObject, const QString domainIDString = domainObject[DOMAIN_ID_KEY].toString(); QUuid domainID(domainIDString); - qDebug() << "Possible domain change required to connect to domain with ID" << domainID + qCDebug(networking) << "Possible domain change required to connect to domain with ID" << domainID << "via ice-server at" << iceServerAddress; emit possibleDomainChangeRequiredViaICEForID(iceServerAddress, domainID); @@ -241,7 +241,7 @@ void AddressManager::goToAddressFromObject(const QVariantMap& dataObject, const if (!overridePath.isEmpty()) { if (!handleRelativeViewpoint(overridePath)){ - qDebug() << "User entered path could not be handled as a viewpoint - " << overridePath; + qCDebug(networking) << "User entered path could not be handled as a viewpoint - " << overridePath; } } else { // take the path that came back @@ -253,28 +253,28 @@ void AddressManager::goToAddressFromObject(const QVariantMap& dataObject, const if (!returnedPath.isEmpty()) { // try to parse this returned path as a viewpoint, that's the only thing it could be for now if (!handleRelativeViewpoint(returnedPath, shouldFaceViewpoint)) { - qDebug() << "Received a location path that was could not be handled as a viewpoint -" << returnedPath; + qCDebug(networking) << "Received a location path that was could not be handled as a viewpoint -" << returnedPath; } } } } else { - qDebug() << "Received an address manager API response with no domain key. Cannot parse."; - qDebug() << locationMap; + qCDebug(networking) << "Received an address manager API response with no domain key. Cannot parse."; + qCDebug(networking) << locationMap; } } else { // we've been told that this result exists but is offline, emit our signal so the application can handle emit lookupResultIsOffline(); } } else { - qDebug() << "Received an address manager API response with no location key or place key. Cannot parse."; - qDebug() << locationMap; + qCDebug(networking) << "Received an address manager API response with no location key or place key. Cannot parse."; + qCDebug(networking) << locationMap; } } void AddressManager::handleAPIError(QNetworkReply& errorReply) { - qDebug() << "AddressManager API error -" << errorReply.error() << "-" << errorReply.errorString(); + qCDebug(networking) << "AddressManager API error -" << errorReply.error() << "-" << errorReply.errorString(); if (errorReply.error() == QNetworkReply::ContentNotFoundError) { emit lookupResultIsNotFound(); @@ -379,14 +379,14 @@ bool AddressManager::handleRelativeViewpoint(const QString& lookupString, bool s emit locationChangeRequired(newPosition, true, newOrientation, shouldFace); return true; } else { - qDebug() << "Orientation parsed from lookup string is invalid. Will not use for location change."; + qCDebug(networking) << "Orientation parsed from lookup string is invalid. Will not use for location change."; } } emit locationChangeRequired(newPosition, false, newOrientation, shouldFace); } else { - qDebug() << "Could not jump to position from lookup string because it has an invalid value."; + qCDebug(networking) << "Could not jump to position from lookup string because it has an invalid value."; } return true; @@ -422,7 +422,7 @@ void AddressManager::setDomainInfo(const QString& hostname, quint16 port) { _rootPlaceName = hostname; _rootPlaceID = QUuid(); - qDebug() << "Possible domain change required to connect to domain at" << hostname << "on" << port; + qCDebug(networking) << "Possible domain change required to connect to domain at" << hostname << "on" << port; emit possibleDomainChangeRequired(hostname, port); } diff --git a/libraries/networking/src/DataServerAccountInfo.cpp b/libraries/networking/src/DataServerAccountInfo.cpp index 00ef0f9e1d..0df4887b74 100644 --- a/libraries/networking/src/DataServerAccountInfo.cpp +++ b/libraries/networking/src/DataServerAccountInfo.cpp @@ -14,7 +14,9 @@ #include #include +#include "NetworkLogging.h" #include "DataServerAccountInfo.h" + #pragma clang diagnostic ignored "-Wdeprecated-declarations" DataServerAccountInfo::DataServerAccountInfo() : @@ -72,7 +74,7 @@ void DataServerAccountInfo::setUsername(const QString& username) { // clear our username signature so it has to be re-created _usernameSignature = QByteArray(); - qDebug() << "Username changed to" << username; + qCDebug(networking) << "Username changed to" << username; } } @@ -140,16 +142,16 @@ const QByteArray& DataServerAccountInfo::getUsernameSignature() { rsaPrivateKey, RSA_PKCS1_PADDING); if (encryptReturn == -1) { - qDebug() << "Error encrypting username signature."; - qDebug() << "Will re-attempt on next domain-server check in."; + qCDebug(networking) << "Error encrypting username signature."; + qCDebug(networking) << "Will re-attempt on next domain-server check in."; _usernameSignature = QByteArray(); } // free the private key RSA struct now that we are done with it RSA_free(rsaPrivateKey); } else { - qDebug() << "Could not create RSA struct from QByteArray private key."; - qDebug() << "Will re-attempt on next domain-server check in."; + qCDebug(networking) << "Could not create RSA struct from QByteArray private key."; + qCDebug(networking) << "Will re-attempt on next domain-server check in."; } } } diff --git a/libraries/networking/src/DomainHandler.cpp b/libraries/networking/src/DomainHandler.cpp index 78ec64832b..4f9585cceb 100644 --- a/libraries/networking/src/DomainHandler.cpp +++ b/libraries/networking/src/DomainHandler.cpp @@ -19,6 +19,7 @@ #include "PacketHeaders.h" #include "SharedUtil.h" #include "UserActivityLogger.h" +#include "NetworkLogging.h" #include "DomainHandler.h" @@ -57,7 +58,7 @@ void DomainHandler::clearSettings() { } void DomainHandler::softReset() { - qDebug() << "Resetting current domain connection information."; + qCDebug(networking) << "Resetting current domain connection information."; clearConnectionInfo(); clearSettings(); } @@ -65,7 +66,7 @@ void DomainHandler::softReset() { void DomainHandler::hardReset() { softReset(); - qDebug() << "Hard reset in NodeList DomainHandler."; + qCDebug(networking) << "Hard reset in NodeList DomainHandler."; _iceDomainID = QUuid(); _iceServerSockAddr = HifiSockAddr(); _hostname = QString(); @@ -87,7 +88,7 @@ void DomainHandler::setSockAddr(const HifiSockAddr& sockAddr, const QString& hos void DomainHandler::setUUID(const QUuid& uuid) { if (uuid != _uuid) { _uuid = uuid; - qDebug() << "Domain ID changed to" << uuidStringWithoutCurlyBraces(_uuid); + qCDebug(networking) << "Domain ID changed to" << uuidStringWithoutCurlyBraces(_uuid); } } @@ -101,10 +102,10 @@ void DomainHandler::setHostnameAndPort(const QString& hostname, quint16 port) { // set the new hostname _hostname = hostname; - qDebug() << "Updated domain hostname to" << _hostname; + qCDebug(networking) << "Updated domain hostname to" << _hostname; // re-set the sock addr to null and fire off a lookup of the IP address for this domain-server's hostname - qDebug("Looking up DS hostname %s.", _hostname.toLocal8Bit().constData()); + qCDebug(networking, "Looking up DS hostname %s.", _hostname.toLocal8Bit().constData()); QHostInfo::lookupHost(_hostname, this, SLOT(completedHostnameLookup(const QHostInfo&))); UserActivityLogger::getInstance().changedDomain(_hostname); @@ -112,7 +113,7 @@ void DomainHandler::setHostnameAndPort(const QString& hostname, quint16 port) { } if (_sockAddr.getPort() != port) { - qDebug() << "Updated domain port to" << port; + qCDebug(networking) << "Updated domain port to" << port; } // grab the port by reading the string after the colon @@ -134,7 +135,7 @@ void DomainHandler::setIceServerHostnameAndID(const QString& iceServerHostname, // refresh our ICE client UUID to something new _iceClientID = QUuid::createUuid(); - qDebug() << "ICE required to connect to domain via ice server at" << iceServerHostname; + qCDebug(networking) << "ICE required to connect to domain via ice server at" << iceServerHostname; } } @@ -152,14 +153,14 @@ void DomainHandler::completedHostnameLookup(const QHostInfo& hostInfo) { for (int i = 0; i < hostInfo.addresses().size(); i++) { if (hostInfo.addresses()[i].protocol() == QAbstractSocket::IPv4Protocol) { _sockAddr.setAddress(hostInfo.addresses()[i]); - qDebug("DS at %s is at %s", _hostname.toLocal8Bit().constData(), + qCDebug(networking, "DS at %s is at %s", _hostname.toLocal8Bit().constData(), _sockAddr.getAddress().toString().toLocal8Bit().constData()); return; } } // if we got here then we failed to lookup the address - qDebug("Failed domain server lookup"); + qCDebug(networking, "Failed domain server lookup"); } void DomainHandler::setIsConnected(bool isConnected) { @@ -195,7 +196,7 @@ void DomainHandler::requestDomainSettings() { Assignment::Type assignmentType = Assignment::typeForNodeType(DependencyManager::get()->getOwnerType()); settingsJSONURL.setQuery(QString("type=%1").arg(assignmentType)); - qDebug() << "Requesting domain-server settings at" << settingsJSONURL.toString(); + qCDebug(networking) << "Requesting domain-server settings at" << settingsJSONURL.toString(); QNetworkRequest settingsRequest(settingsJSONURL); settingsRequest.setHeader(QNetworkRequest::UserAgentHeader, HIGH_FIDELITY_USER_AGENT); @@ -216,7 +217,7 @@ void DomainHandler::settingsRequestFinished() { // parse the JSON to a QJsonObject and save it _settingsObject = QJsonDocument::fromJson(settingsReply->readAll()).object(); - qDebug() << "Received domain settings."; + qCDebug(networking) << "Received domain settings."; emit settingsReceived(_settingsObject); // reset failed settings requests to 0, we got them @@ -224,10 +225,10 @@ void DomainHandler::settingsRequestFinished() { } else { // error grabbing the settings - in some cases this means we are stuck // so we should retry until we get it - qDebug() << "Error getting domain settings -" << settingsReply->errorString() << "- retrying"; + qCDebug(networking) << "Error getting domain settings -" << settingsReply->errorString() << "- retrying"; if (++_failedSettingsRequests >= MAX_SETTINGS_REQUEST_FAILED_ATTEMPTS) { - qDebug() << "Failed to retreive domain-server settings" << MAX_SETTINGS_REQUEST_FAILED_ATTEMPTS + qCDebug(networking) << "Failed to retreive domain-server settings" << MAX_SETTINGS_REQUEST_FAILED_ATTEMPTS << "times. Re-setting connection to domain."; clearSettings(); clearConnectionInfo(); @@ -246,7 +247,7 @@ void DomainHandler::parseDTLSRequirementPacket(const QByteArray& dtlsRequirement unsigned short dtlsPort = 0; memcpy(&dtlsPort, dtlsRequirementPacket.data() + numBytesPacketHeader, sizeof(dtlsPort)); - qDebug() << "domain-server DTLS port changed to" << dtlsPort << "- Enabling DTLS."; + qCDebug(networking) << "domain-server DTLS port changed to" << dtlsPort << "- Enabling DTLS."; _sockAddr.setPort(dtlsPort); @@ -261,9 +262,9 @@ void DomainHandler::processICEResponsePacket(const QByteArray& icePacket) { iceResponseStream >> packetPeer; if (packetPeer.getUUID() != _iceDomainID) { - qDebug() << "Received a network peer with ID that does not match current domain. Will not attempt connection."; + qCDebug(networking) << "Received a network peer with ID that does not match current domain. Will not attempt connection."; } else { - qDebug() << "Received network peer object for domain -" << packetPeer; + qCDebug(networking) << "Received network peer object for domain -" << packetPeer; _icePeer = packetPeer; emit requestICEConnectionAttempt(); diff --git a/libraries/networking/src/HifiSockAddr.cpp b/libraries/networking/src/HifiSockAddr.cpp index 425dffefe9..c0fb0ecb69 100644 --- a/libraries/networking/src/HifiSockAddr.cpp +++ b/libraries/networking/src/HifiSockAddr.cpp @@ -14,6 +14,7 @@ #include #include "HifiSockAddr.h" +#include "NetworkLogging.h" static int hifiSockAddrMetaTypeId = qMetaTypeId(); @@ -52,12 +53,12 @@ HifiSockAddr::HifiSockAddr(const QString& hostname, quint16 hostOrderPort, bool if (_address.protocol() != QAbstractSocket::IPv4Protocol) { // lookup the IP by the hostname if (shouldBlockForLookup) { - qDebug() << "Synchronously looking up IP address for hostname" << hostname; + qCDebug(networking) << "Synchronously looking up IP address for hostname" << hostname; QHostInfo result = QHostInfo::fromName(hostname); handleLookupResult(result); } else { int lookupID = QHostInfo::lookupHost(hostname, this, SLOT(handleLookupResult(QHostInfo))); - qDebug() << "Asynchronously looking up IP address for hostname" << hostname << "- lookup ID is" << lookupID; + qCDebug(networking) << "Asynchronously looking up IP address for hostname" << hostname << "- lookup ID is" << lookupID; } } } @@ -85,7 +86,7 @@ bool HifiSockAddr::operator==(const HifiSockAddr& rhsSockAddr) const { void HifiSockAddr::handleLookupResult(const QHostInfo& hostInfo) { if (hostInfo.error() != QHostInfo::NoError) { - qDebug() << "Lookup failed for" << hostInfo.lookupId() << ":" << hostInfo.errorString(); + qCDebug(networking) << "Lookup failed for" << hostInfo.lookupId() << ":" << hostInfo.errorString(); emit lookupFailed(); } @@ -93,7 +94,7 @@ void HifiSockAddr::handleLookupResult(const QHostInfo& hostInfo) { // just take the first IPv4 address if (address.protocol() == QAbstractSocket::IPv4Protocol) { _address = address; - qDebug() << "QHostInfo lookup result for" + qCDebug(networking) << "QHostInfo lookup result for" << hostInfo.hostName() << "with lookup ID" << hostInfo.lookupId() << "is" << address.toString(); emit lookupCompleted(); break; diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index 42a20aac03..f476b36514 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -30,6 +30,7 @@ #include "PacketHeaders.h" #include "SharedUtil.h" #include "UUID.h" +#include "NetworkLogging.h" const char SOLO_NODE_TYPES[2] = { NodeType::AvatarMixer, @@ -60,14 +61,14 @@ LimitedNodeList::LimitedNodeList(unsigned short socketListenPort, unsigned short } _nodeSocket.bind(QHostAddress::AnyIPv4, socketListenPort); - qDebug() << "NodeList socket is listening on" << _nodeSocket.localPort(); + qCDebug(networking) << "NodeList socket is listening on" << _nodeSocket.localPort(); if (dtlsListenPort > 0) { // only create the DTLS socket during constructor if a custom port is passed _dtlsSocket = new QUdpSocket(this); _dtlsSocket->bind(QHostAddress::AnyIPv4, dtlsListenPort); - qDebug() << "NodeList DTLS socket is listening on" << _dtlsSocket->localPort(); + qCDebug(networking) << "NodeList DTLS socket is listening on" << _dtlsSocket->localPort(); } const int LARGER_BUFFER_SIZE = 1048576; @@ -94,7 +95,7 @@ void LimitedNodeList::setSessionUUID(const QUuid& sessionUUID) { _sessionUUID = sessionUUID; if (sessionUUID != oldUUID) { - qDebug() << "NodeList UUID changed from" << uuidStringWithoutCurlyBraces(oldUUID) + qCDebug(networking) << "NodeList UUID changed from" << uuidStringWithoutCurlyBraces(oldUUID) << "to" << uuidStringWithoutCurlyBraces(_sessionUUID); emit uuidChanged(sessionUUID, oldUUID); } @@ -125,7 +126,7 @@ QUdpSocket& LimitedNodeList::getDTLSSocket() { // DTLS requires that IP_DONTFRAG be set // This is not accessible on some platforms (OS X) so we need to make sure DTLS still works without it - qDebug() << "LimitedNodeList DTLS socket is listening on" << _dtlsSocket->localPort(); + qCDebug(networking) << "LimitedNodeList DTLS socket is listening on" << _dtlsSocket->localPort(); } return *_dtlsSocket; @@ -147,11 +148,11 @@ void LimitedNodeList::changeSocketBufferSizes(int numBytes) { if (oldBufferSize < numBytes) { int newBufferSize = _nodeSocket.socketOption(bufferOpt).toInt(); - qDebug() << "Changed socket" << bufferTypeString << "buffer size from" << oldBufferSize << "to" + qCDebug(networking) << "Changed socket" << bufferTypeString << "buffer size from" << oldBufferSize << "to" << newBufferSize << "bytes"; } else { // don't make the buffer smaller - qDebug() << "Did not change socket" << bufferTypeString << "buffer size from" << oldBufferSize + qCDebug(networking) << "Did not change socket" << bufferTypeString << "buffer size from" << oldBufferSize << "since it is larger than desired size of" << numBytes; } } @@ -169,7 +170,7 @@ bool LimitedNodeList::packetVersionAndHashMatch(const QByteArray& packet) { QUuid senderUUID = uuidFromPacketHeader(packet); if (!versionDebugSuppressMap.contains(senderUUID, checkType)) { - qDebug() << "Packet version mismatch on" << packetTypeForPacket(packet) << "- Sender" + qCDebug(networking) << "Packet version mismatch on" << packetTypeForPacket(packet) << "- Sender" << uuidFromPacketHeader(packet) << "sent" << qPrintable(QString::number(packet[numPacketTypeBytes])) << "but" << qPrintable(QString::number(versionForPacketType(mismatchType))) << "expected."; @@ -193,7 +194,7 @@ bool LimitedNodeList::packetVersionAndHashMatch(const QByteArray& packet) { QUuid senderUUID = uuidFromPacketHeader(packet); if (!hashDebugSuppressMap.contains(senderUUID, checkType)) { - qDebug() << "Packet hash mismatch on" << checkType << "- Sender" + qCDebug(networking) << "Packet hash mismatch on" << checkType << "- Sender" << uuidFromPacketHeader(packet); hashDebugSuppressMap.insert(senderUUID, checkType); @@ -203,7 +204,7 @@ bool LimitedNodeList::packetVersionAndHashMatch(const QByteArray& packet) { static QString repeatedMessage = LogHandler::getInstance().addRepeatedMessageRegex("Packet of type \\d+ received from unknown node with UUID"); - qDebug() << "Packet of type" << checkType << "received from unknown node with UUID" + qCDebug(networking) << "Packet of type" << checkType << "received from unknown node with UUID" << qPrintable(uuidStringWithoutCurlyBraces(uuidFromPacketHeader(packet))); } } else { @@ -246,7 +247,7 @@ qint64 LimitedNodeList::writeDatagram(const QByteArray& datagram, const HifiSock destinationSockAddr.getAddress(), destinationSockAddr.getPort()); if (bytesWritten < 0) { - qDebug() << "ERROR in writeDatagram:" << _nodeSocket.error() << "-" << _nodeSocket.errorString(); + qCDebug(networking) << "ERROR in writeDatagram:" << _nodeSocket.error() << "-" << _nodeSocket.errorString(); } return bytesWritten; @@ -368,7 +369,7 @@ SharedNodePointer LimitedNodeList::sendingNodeForPacket(const QByteArray& packet } void LimitedNodeList::eraseAllNodes() { - qDebug() << "Clearing the NodeList. Deleting all nodes in list."; + qCDebug(networking) << "Clearing the NodeList. Deleting all nodes in list."; QSet killedNodes; eachNode([&killedNodes](const SharedNodePointer& node){ @@ -417,7 +418,7 @@ void LimitedNodeList::processKillNode(const QByteArray& dataByteArray) { } void LimitedNodeList::handleNodeKill(const SharedNodePointer& node) { - qDebug() << "Killed" << *node; + qCDebug(networking) << "Killed" << *node; emit nodeKilled(node); } @@ -442,7 +443,7 @@ SharedNodePointer LimitedNodeList::addOrUpdateNode(const QUuid& uuid, NodeType_t _nodeHash.insert(UUIDNodePair(newNode->getUUID(), newNodePointer)); - qDebug() << "Added" << *newNode; + qCDebug(networking) << "Added" << *newNode; emit nodeAdded(newNodePointer); @@ -629,7 +630,7 @@ bool LimitedNodeList::processSTUNResponse(const QByteArray& packet) { if (newPublicAddress != _publicSockAddr.getAddress() || newPublicPort != _publicSockAddr.getPort()) { _publicSockAddr = HifiSockAddr(newPublicAddress, newPublicPort); - qDebug("New public socket received from STUN server is %s:%hu", + qCDebug(networking, "New public socket received from STUN server is %s:%hu", _publicSockAddr.getAddress().toString().toLocal8Bit().constData(), _publicSockAddr.getPort()); @@ -660,9 +661,9 @@ void LimitedNodeList::updateLocalSockAddr() { if (newSockAddr != _localSockAddr) { if (_localSockAddr.isNull()) { - qDebug() << "Local socket is" << newSockAddr; + qCDebug(networking) << "Local socket is" << newSockAddr; } else { - qDebug() << "Local socket has changed from" << _localSockAddr << "to" << newSockAddr; + qCDebug(networking) << "Local socket has changed from" << _localSockAddr << "to" << newSockAddr; } _localSockAddr = newSockAddr; @@ -686,7 +687,7 @@ void LimitedNodeList::sendHeartbeatToIceServer(const HifiSockAddr& iceServerSock if (!connectionRequestID.isNull()) { iceDataStream << connectionRequestID; - qDebug() << "Sending packet to ICE server to request connection info for peer with ID" + qCDebug(networking) << "Sending packet to ICE server to request connection info for peer with ID" << uuidStringWithoutCurlyBraces(connectionRequestID); } @@ -703,7 +704,7 @@ void LimitedNodeList::putLocalPortIntoSharedMemory(const QString key, QObject* p memcpy(sharedPortMem->data(), &localPort, sizeof(localPort)); sharedPortMem->unlock(); - qDebug() << "Wrote local listening port" << localPort << "to shared memory at key" << key; + qCDebug(networking) << "Wrote local listening port" << localPort << "to shared memory at key" << key; } else { qWarning() << "Failed to create and attach to shared memory to share local port with assignment-client children."; } diff --git a/libraries/networking/src/NetworkLogging.cpp b/libraries/networking/src/NetworkLogging.cpp new file mode 100644 index 0000000000..45ff716a97 --- /dev/null +++ b/libraries/networking/src/NetworkLogging.cpp @@ -0,0 +1,14 @@ +// +// NetworkLogging.cpp +// libraries/networking/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "NetworkLogging.h" + +Q_LOGGING_CATEGORY(networking, "hifi.networking") diff --git a/libraries/networking/src/NetworkLogging.h b/libraries/networking/src/NetworkLogging.h new file mode 100644 index 0000000000..47a6a34264 --- /dev/null +++ b/libraries/networking/src/NetworkLogging.h @@ -0,0 +1,19 @@ +// +// NetworkLogging.h +// libraries/networking/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_NetworkLogging_h +#define hifi_NetworkLogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(networking) + +#endif // hifi_NetworkLogging_h diff --git a/libraries/networking/src/NetworkPacket.cpp b/libraries/networking/src/NetworkPacket.cpp index a8110847e1..69bd0962bf 100644 --- a/libraries/networking/src/NetworkPacket.cpp +++ b/libraries/networking/src/NetworkPacket.cpp @@ -14,6 +14,7 @@ #include #include "SharedUtil.h" +#include "NetworkLogging.h" #include "NetworkPacket.h" @@ -22,7 +23,7 @@ void NetworkPacket::copyContents(const SharedNodePointer& node, const QByteArray _node = node; _byteArray = packet; } else { - qDebug(">>> NetworkPacket::copyContents() unexpected length = %d", packet.size()); + qCDebug(networking, ">>> NetworkPacket::copyContents() unexpected length = %d", packet.size()); } } diff --git a/libraries/networking/src/Node.cpp b/libraries/networking/src/Node.cpp index defcd0035b..4abae367d7 100644 --- a/libraries/networking/src/Node.cpp +++ b/libraries/networking/src/Node.cpp @@ -16,6 +16,7 @@ #include "Node.h" #include "SharedUtil.h" +#include "NetworkLogging.h" #include #include @@ -76,7 +77,7 @@ void Node::setPublicSocket(const HifiSockAddr& publicSocket) { } if (!_publicSocket.isNull()) { - qDebug() << "Public socket change for node" << *this; + qCDebug(networking) << "Public socket change for node" << *this; } _publicSocket = publicSocket; @@ -91,7 +92,7 @@ void Node::setLocalSocket(const HifiSockAddr& localSocket) { } if (!_localSocket.isNull()) { - qDebug() << "Local socket change for node" << *this; + qCDebug(networking) << "Local socket change for node" << *this; } _localSocket = localSocket; @@ -106,7 +107,7 @@ void Node::setSymmetricSocket(const HifiSockAddr& symmetricSocket) { } if (!_symmetricSocket.isNull()) { - qDebug() << "Symmetric socket change for node" << *this; + qCDebug(networking) << "Symmetric socket change for node" << *this; } _symmetricSocket = symmetricSocket; @@ -114,17 +115,17 @@ void Node::setSymmetricSocket(const HifiSockAddr& symmetricSocket) { } void Node::activateLocalSocket() { - qDebug() << "Activating local socket for network peer with ID" << uuidStringWithoutCurlyBraces(_uuid); + qCDebug(networking) << "Activating local socket for network peer with ID" << uuidStringWithoutCurlyBraces(_uuid); _activeSocket = &_localSocket; } void Node::activatePublicSocket() { - qDebug() << "Activating public socket for network peer with ID" << uuidStringWithoutCurlyBraces(_uuid); + qCDebug(networking) << "Activating public socket for network peer with ID" << uuidStringWithoutCurlyBraces(_uuid); _activeSocket = &_publicSocket; } void Node::activateSymmetricSocket() { - qDebug() << "Activating symmetric socket for network peer with ID" << uuidStringWithoutCurlyBraces(_uuid); + qCDebug(networking) << "Activating symmetric socket for network peer with ID" << uuidStringWithoutCurlyBraces(_uuid); _activeSocket = &_symmetricSocket; } diff --git a/libraries/networking/src/NodeList.cpp b/libraries/networking/src/NodeList.cpp index 307ba93c88..76f66420bf 100644 --- a/libraries/networking/src/NodeList.cpp +++ b/libraries/networking/src/NodeList.cpp @@ -25,6 +25,7 @@ #include "PacketHeaders.h" #include "SharedUtil.h" #include "UUID.h" +#include "NetworkLogging.h" NodeList::NodeList(char newOwnerType, unsigned short socketListenPort, unsigned short dtlsListenPort) : LimitedNodeList(socketListenPort, dtlsListenPort), @@ -99,7 +100,7 @@ void NodeList::timePingReply(const QByteArray& packet, const SharedNodePointer& const bool wantDebug = false; if (wantDebug) { - qDebug() << "PING_REPLY from node " << *sendingNode << "\n" << + qCDebug(networking) << "PING_REPLY from node " << *sendingNode << "\n" << " now: " << now << "\n" << " ourTime: " << ourOriginalTime << "\n" << " pingTime: " << pingTime << "\n" << @@ -167,17 +168,17 @@ void NodeList::processNodeData(const HifiSockAddr& senderSockAddr, const QByteAr break; } case PacketTypeUnverifiedPingReply: { - qDebug() << "Received reply from domain-server on" << senderSockAddr; + qCDebug(networking) << "Received reply from domain-server on" << senderSockAddr; // for now we're unsafely assuming this came back from the domain if (senderSockAddr == _domainHandler.getICEPeer().getLocalSocket()) { - qDebug() << "Connecting to domain using local socket"; + qCDebug(networking) << "Connecting to domain using local socket"; _domainHandler.activateICELocalSocket(); } else if (senderSockAddr == _domainHandler.getICEPeer().getPublicSocket()) { - qDebug() << "Conecting to domain using public socket"; + qCDebug(networking) << "Conecting to domain using public socket"; _domainHandler.activateICEPublicSocket(); } else { - qDebug() << "Reply does not match either local or public socket for domain. Will not connect."; + qCDebug(networking) << "Reply does not match either local or public socket for domain. Will not connect."; } } case PacketTypeStunResponse: { @@ -225,7 +226,7 @@ const unsigned int NUM_STUN_REQUESTS_BEFORE_FALLBACK = 5; void NodeList::sendSTUNRequest() { if (!_hasCompletedInitialSTUNFailure) { - qDebug() << "Sending intial stun request to" << STUN_SERVER_HOSTNAME; + qCDebug(networking) << "Sending intial stun request to" << STUN_SERVER_HOSTNAME; } LimitedNodeList::sendSTUNRequest(); @@ -236,7 +237,7 @@ void NodeList::sendSTUNRequest() { if (!_hasCompletedInitialSTUNFailure) { // if we're here this was the last failed STUN request // use our DS as our stun server - qDebug("Failed to lookup public address via STUN server at %s:%hu. Using DS for STUN.", + qCDebug(networking, "Failed to lookup public address via STUN server at %s:%hu. Using DS for STUN.", STUN_SERVER_HOSTNAME, STUN_SERVER_PORT); _hasCompletedInitialSTUNFailure = true; @@ -276,7 +277,7 @@ void NodeList::sendDomainServerCheckIn() { ? PacketTypeDomainConnectRequest : PacketTypeDomainListRequest; if (!_domainHandler.isConnected()) { - qDebug() << "Sending connect request to domain-server at" << _domainHandler.getHostname(); + qCDebug(networking) << "Sending connect request to domain-server at" << _domainHandler.getHostname(); // is this our localhost domain-server? // if so we need to make sure we have an up-to-date local port in case it restarted @@ -290,7 +291,7 @@ void NodeList::sendDomainServerCheckIn() { getLocalServerPortFromSharedMemory(DOMAIN_SERVER_LOCAL_PORT_SMEM_KEY, localDSPortSharedMem, domainPort); - qDebug() << "Local domain-server port read from shared memory (or default) is" << domainPort; + qCDebug(networking) << "Local domain-server port read from shared memory (or default) is" << domainPort; _domainHandler.setPort(domainPort); } @@ -327,7 +328,7 @@ void NodeList::sendDomainServerCheckIn() { const QByteArray& usernameSignature = AccountManager::getInstance().getAccountInfo().getUsernameSignature(); if (!usernameSignature.isEmpty()) { - qDebug() << "Including username signature in domain connect request."; + qCDebug(networking) << "Including username signature in domain connect request."; packetStream << usernameSignature; } } @@ -365,7 +366,7 @@ void NodeList::handleICEConnectionToDomainServer() { _domainHandler.getICEClientID(), _domainHandler.getICEDomainID()); } else { - qDebug() << "Sending ping packets to establish connectivity with domain-server with ID" + qCDebug(networking) << "Sending ping packets to establish connectivity with domain-server with ID" << uuidStringWithoutCurlyBraces(_domainHandler.getICEDomainID()); // send the ping packet to the local and public sockets for this node diff --git a/libraries/networking/src/RSAKeypairGenerator.cpp b/libraries/networking/src/RSAKeypairGenerator.cpp index bfe16cc9b8..f142ce1831 100644 --- a/libraries/networking/src/RSAKeypairGenerator.cpp +++ b/libraries/networking/src/RSAKeypairGenerator.cpp @@ -15,6 +15,8 @@ #include +#include "NetworkLogging.h" + #include "RSAKeypairGenerator.h" #pragma clang diagnostic ignored "-Wdeprecated-declarations" @@ -38,7 +40,7 @@ void RSAKeypairGenerator::generateKeypair() { const int RSA_KEY_BITS = 2048; if (!RSA_generate_key_ex(keyPair, RSA_KEY_BITS, exponent, NULL)) { - qDebug() << "Error generating 2048-bit RSA Keypair -" << ERR_get_error(); + qCDebug(networking) << "Error generating 2048-bit RSA Keypair -" << ERR_get_error(); emit errorGeneratingKeypair(); @@ -58,7 +60,7 @@ void RSAKeypairGenerator::generateKeypair() { int privateKeyLength = i2d_RSAPrivateKey(keyPair, &privateKeyDER); if (publicKeyLength <= 0 || privateKeyLength <= 0) { - qDebug() << "Error getting DER public or private key from RSA struct -" << ERR_get_error(); + qCDebug(networking) << "Error getting DER public or private key from RSA struct -" << ERR_get_error(); emit errorGeneratingKeypair(); @@ -89,4 +91,4 @@ void RSAKeypairGenerator::generateKeypair() { OPENSSL_free(privateKeyDER); emit generatedKeypair(publicKeyArray, privateKeyArray); -} \ No newline at end of file +} diff --git a/libraries/networking/src/ResourceCache.cpp b/libraries/networking/src/ResourceCache.cpp index 9cf0d53244..54afa98505 100644 --- a/libraries/networking/src/ResourceCache.cpp +++ b/libraries/networking/src/ResourceCache.cpp @@ -21,6 +21,8 @@ #include #include "NetworkAccessManager.h" +#include "NetworkLogging.h" + #include "ResourceCache.h" #define clamp(x, min, max) (((x) < (min)) ? (min) :\ @@ -50,7 +52,7 @@ void ResourceCache::refresh(const QUrl& url) { } void ResourceCache::getResourceAsynchronously(const QUrl& url) { - qDebug() << "ResourceCache::getResourceAsynchronously" << url.toString(); + qCDebug(networking) << "ResourceCache::getResourceAsynchronously" << url.toString(); _resourcesToBeGottenLock.lockForWrite(); _resourcesToBeGotten.enqueue(QUrl(url)); _resourcesToBeGottenLock.unlock(); @@ -354,10 +356,10 @@ void Resource::maybeRefresh() { } } else if (!variant.isValid() || !variant.canConvert() || !variant.value().isValid() || variant.value().isNull()) { - qDebug() << "Cannot determine when" << _url.fileName() << "was modified last, cached version might be outdated"; + qCDebug(networking) << "Cannot determine when" << _url.fileName() << "was modified last, cached version might be outdated"; return; } - qDebug() << "Loaded" << _url.fileName() << "from the disk cache but the network version is newer, refreshing."; + qCDebug(networking) << "Loaded" << _url.fileName() << "from the disk cache but the network version is newer, refreshing."; refresh(); } } @@ -441,7 +443,7 @@ void Resource::handleReplyError(QNetworkReply::NetworkError error, QDebug debug) } void Resource::handleReplyFinished() { - qDebug() << "Got finished without download progress/error?" << _url; + qCDebug(networking) << "Got finished without download progress/error?" << _url; handleDownloadProgress(0, 0); } diff --git a/libraries/networking/src/SentPacketHistory.cpp b/libraries/networking/src/SentPacketHistory.cpp index 3cdb0af8c0..39f8a9c26e 100644 --- a/libraries/networking/src/SentPacketHistory.cpp +++ b/libraries/networking/src/SentPacketHistory.cpp @@ -9,9 +9,13 @@ // #include +#include "NetworkLogging.h" #include "SentPacketHistory.h" #include + + + SentPacketHistory::SentPacketHistory(int size) : _sentPackets(size), _newestSequenceNumber(std::numeric_limits::max()) @@ -24,7 +28,7 @@ void SentPacketHistory::packetSent(uint16_t sequenceNumber, const QByteArray& pa // the code calling this function uint16_t expectedSequenceNumber = _newestSequenceNumber + (uint16_t)1; if (sequenceNumber != expectedSequenceNumber) { - qDebug() << "Unexpected sequence number passed to SentPacketHistory::packetSent()!" + qCDebug(networking) << "Unexpected sequence number passed to SentPacketHistory::packetSent()!" << "Expected:" << expectedSequenceNumber << "Actual:" << sequenceNumber; } _newestSequenceNumber = sequenceNumber; diff --git a/libraries/networking/src/SequenceNumberStats.cpp b/libraries/networking/src/SequenceNumberStats.cpp index 58c684e16b..8dd0b78d89 100644 --- a/libraries/networking/src/SequenceNumberStats.cpp +++ b/libraries/networking/src/SequenceNumberStats.cpp @@ -10,6 +10,7 @@ // #include "SequenceNumberStats.h" +#include "NetworkLogging.h" #include @@ -42,8 +43,8 @@ SequenceNumberStats::ArrivalInfo SequenceNumberStats::sequenceNumberReceived(qui // if the sender node has changed, reset all stats if (senderUUID != _lastSenderUUID) { if (_stats._received > 0) { - qDebug() << "sequence number stats was reset due to new sender node"; - qDebug() << "previous:" << _lastSenderUUID << "current:" << senderUUID; + qCDebug(networking) << "sequence number stats was reset due to new sender node"; + qCDebug(networking) << "previous:" << _lastSenderUUID << "current:" << senderUUID; reset(); } _lastSenderUUID = senderUUID; @@ -61,7 +62,7 @@ SequenceNumberStats::ArrivalInfo SequenceNumberStats::sequenceNumberReceived(qui } else { // out of order if (wantExtraDebugging) { - qDebug() << "out of order... got:" << incoming << "expected:" << expected; + qCDebug(networking) << "out of order... got:" << incoming << "expected:" << expected; } int incomingInt = (int)incoming; @@ -80,7 +81,7 @@ SequenceNumberStats::ArrivalInfo SequenceNumberStats::sequenceNumberReceived(qui } else if (absGap > MAX_REASONABLE_SEQUENCE_GAP) { arrivalInfo._status = Unreasonable; - qDebug() << "unreasonable sequence number:" << incoming << "previous:" << _lastReceivedSequence; + qCDebug(networking) << "unreasonable sequence number:" << incoming << "previous:" << _lastReceivedSequence; _stats._unreasonable++; @@ -98,8 +99,8 @@ SequenceNumberStats::ArrivalInfo SequenceNumberStats::sequenceNumberReceived(qui arrivalInfo._status = Early; if (wantExtraDebugging) { - qDebug() << "this packet is earlier than expected..."; - qDebug() << ">>>>>>>> missing gap=" << (incomingInt - expectedInt); + qCDebug(networking) << "this packet is earlier than expected..."; + qCDebug(networking) << ">>>>>>>> missing gap=" << (incomingInt - expectedInt); } int skipped = incomingInt - expectedInt; _stats._early++; @@ -119,7 +120,7 @@ SequenceNumberStats::ArrivalInfo SequenceNumberStats::sequenceNumberReceived(qui } } else { // late if (wantExtraDebugging) { - qDebug() << "this packet is later than expected..."; + qCDebug(networking) << "this packet is later than expected..."; } _stats._late++; @@ -131,7 +132,7 @@ SequenceNumberStats::ArrivalInfo SequenceNumberStats::sequenceNumberReceived(qui arrivalInfo._status = Recovered; if (wantExtraDebugging) { - qDebug() << "found it in _missingSet"; + qCDebug(networking) << "found it in _missingSet"; } _stats._lost--; _stats._recovered++; @@ -142,7 +143,7 @@ SequenceNumberStats::ArrivalInfo SequenceNumberStats::sequenceNumberReceived(qui arrivalInfo._status = Unreasonable; - qDebug() << "unreasonable sequence number:" << incoming << "(possible duplicate)"; + qCDebug(networking) << "unreasonable sequence number:" << incoming << "(possible duplicate)"; _stats._unreasonable++; @@ -185,7 +186,7 @@ void SequenceNumberStats::receivedUnreasonable(quint16 incoming) { _statsHistory.clear(); _consecutiveUnreasonableOnTime = 0; - qDebug() << "re-synced with sequence number sender"; + qCDebug(networking) << "re-synced with sequence number sender"; } } else { _consecutiveUnreasonableOnTime = 0; @@ -194,7 +195,7 @@ void SequenceNumberStats::receivedUnreasonable(quint16 incoming) { void SequenceNumberStats::pruneMissingSet(const bool wantExtraDebugging) { if (wantExtraDebugging) { - qDebug() << "pruning _missingSet! size:" << _missingSet.size(); + qCDebug(networking) << "pruning _missingSet! size:" << _missingSet.size(); } // some older sequence numbers may be from before a rollover point; this must be handled. @@ -207,14 +208,14 @@ void SequenceNumberStats::pruneMissingSet(const bool wantExtraDebugging) { while (i != _missingSet.end()) { quint16 missing = *i; if (wantExtraDebugging) { - qDebug() << "checking item:" << missing << "is it in need of pruning?"; - qDebug() << "old age cutoff:" << nonRolloverCutoff; + qCDebug(networking) << "checking item:" << missing << "is it in need of pruning?"; + qCDebug(networking) << "old age cutoff:" << nonRolloverCutoff; } if (missing > _lastReceivedSequence || missing < nonRolloverCutoff) { i = _missingSet.erase(i); if (wantExtraDebugging) { - qDebug() << "pruning really old missing sequence:" << missing; + qCDebug(networking) << "pruning really old missing sequence:" << missing; } } else { i++; @@ -226,14 +227,14 @@ void SequenceNumberStats::pruneMissingSet(const bool wantExtraDebugging) { while (i != _missingSet.end()) { quint16 missing = *i; if (wantExtraDebugging) { - qDebug() << "checking item:" << missing << "is it in need of pruning?"; - qDebug() << "old age cutoff:" << rolloverCutoff; + qCDebug(networking) << "checking item:" << missing << "is it in need of pruning?"; + qCDebug(networking) << "old age cutoff:" << rolloverCutoff; } if (missing > _lastReceivedSequence && missing < rolloverCutoff) { i = _missingSet.erase(i); if (wantExtraDebugging) { - qDebug() << "pruning really old missing sequence:" << missing; + qCDebug(networking) << "pruning really old missing sequence:" << missing; } } else { i++; diff --git a/libraries/networking/src/UserActivityLogger.cpp b/libraries/networking/src/UserActivityLogger.cpp index 89c0bd34bd..f2019ba9a9 100644 --- a/libraries/networking/src/UserActivityLogger.cpp +++ b/libraries/networking/src/UserActivityLogger.cpp @@ -14,6 +14,8 @@ #include #include +#include "NetworkLogging.h" + #include "UserActivityLogger.h" static const QString USER_ACTIVITY_URL = "/api/v1/user_activities"; @@ -52,7 +54,7 @@ void UserActivityLogger::logAction(QString action, QJsonObject details, JSONCall detailsPart.setBody(QJsonDocument(details).toJson(QJsonDocument::Compact)); multipart->append(detailsPart); } - qDebug() << "Logging activity" << action; + qCDebug(networking) << "Logging activity" << action; // if no callbacks specified, call our owns if (params.isEmpty()) { @@ -69,11 +71,11 @@ void UserActivityLogger::logAction(QString action, QJsonObject details, JSONCall } void UserActivityLogger::requestFinished(QNetworkReply& requestReply) { - // qDebug() << object; + // qCDebug(networking) << object; } void UserActivityLogger::requestError(QNetworkReply& errorReply) { - qDebug() << errorReply.error() << "-" << errorReply.errorString(); + qCDebug(networking) << errorReply.error() << "-" << errorReply.errorString(); } void UserActivityLogger::launch(QString applicationVersion) { diff --git a/libraries/octree/src/CoverageMap.cpp b/libraries/octree/src/CoverageMap.cpp index 320e7f60ef..cd013a0827 100644 --- a/libraries/octree/src/CoverageMap.cpp +++ b/libraries/octree/src/CoverageMap.cpp @@ -15,6 +15,7 @@ #include +#include "OctreeLogging.h" #include "CoverageMap.h" int CoverageMap::_mapCount = 0; @@ -73,19 +74,19 @@ CoverageMap::~CoverageMap() { }; void CoverageMap::printStats() { - qDebug("CoverageMap::printStats()..."); - qDebug("MINIMUM_POLYGON_AREA_TO_STORE=%f",MINIMUM_POLYGON_AREA_TO_STORE); - qDebug("_mapCount=%d",_mapCount); - qDebug("_checkMapRootCalls=%d",_checkMapRootCalls); - qDebug("_notAllInView=%d",_notAllInView); - qDebug("_maxPolygonsUsed=%d",CoverageRegion::_maxPolygonsUsed); - qDebug("_totalPolygons=%d",CoverageRegion::_totalPolygons); - qDebug("_occlusionTests=%d",CoverageRegion::_occlusionTests); - qDebug("_regionSkips=%d",CoverageRegion::_regionSkips); - qDebug("_tooSmallSkips=%d",CoverageRegion::_tooSmallSkips); - qDebug("_regionFullSkips=%d",CoverageRegion::_regionFullSkips); - qDebug("_outOfOrderPolygon=%d",CoverageRegion::_outOfOrderPolygon); - qDebug("_clippedPolygons=%d",CoverageRegion::_clippedPolygons); + qCDebug(octree, "CoverageMap::printStats()..."); + qCDebug(octree, "MINIMUM_POLYGON_AREA_TO_STORE=%f",MINIMUM_POLYGON_AREA_TO_STORE); + qCDebug(octree, "_mapCount=%d",_mapCount); + qCDebug(octree, "_checkMapRootCalls=%d",_checkMapRootCalls); + qCDebug(octree, "_notAllInView=%d",_notAllInView); + qCDebug(octree, "_maxPolygonsUsed=%d",CoverageRegion::_maxPolygonsUsed); + qCDebug(octree, "_totalPolygons=%d",CoverageRegion::_totalPolygons); + qCDebug(octree, "_occlusionTests=%d",CoverageRegion::_occlusionTests); + qCDebug(octree, "_regionSkips=%d",CoverageRegion::_regionSkips); + qCDebug(octree, "_tooSmallSkips=%d",CoverageRegion::_tooSmallSkips); + qCDebug(octree, "_regionFullSkips=%d",CoverageRegion::_regionFullSkips); + qCDebug(octree, "_outOfOrderPolygon=%d",CoverageRegion::_outOfOrderPolygon); + qCDebug(octree, "_clippedPolygons=%d",CoverageRegion::_clippedPolygons); } void CoverageMap::erase() { @@ -104,7 +105,7 @@ void CoverageMap::erase() { } if (_isRoot && wantDebugging) { - qDebug("CoverageMap last to be deleted..."); + qCDebug(octree, "CoverageMap last to be deleted..."); printStats(); CoverageRegion::_maxPolygonsUsed = 0; @@ -235,9 +236,9 @@ CoverageMapStorageResult CoverageMap::checkMap(OctreeProjectedPolygon* polygon, /* if (result == STORED) - qDebug("CoverageMap2::checkMap()... STORED\n"); + qCDebug(octree, "CoverageMap2::checkMap()... STORED\n"); else - qDebug("CoverageMap2::checkMap()... OCCLUDED\n"); + qCDebug(octree, "CoverageMap2::checkMap()... OCCLUDED\n"); */ return result; @@ -260,16 +261,16 @@ CoverageMapStorageResult CoverageMap::checkMap(OctreeProjectedPolygon* polygon, /* switch (result) { case STORED: - qDebug("checkMap() = STORED\n"); + qCDebug(octree, "checkMap() = STORED\n"); break; case NOT_STORED: - qDebug("checkMap() = NOT_STORED\n"); + qCDebug(octree, "checkMap() = NOT_STORED\n"); break; case OCCLUDED: - qDebug("checkMap() = OCCLUDED\n"); + qCDebug(octree, "checkMap() = OCCLUDED\n"); break; default: - qDebug("checkMap() = ????? \n"); + qCDebug(octree, "checkMap() = ????? \n"); break; } */ @@ -327,11 +328,11 @@ void CoverageRegion::erase() { /** if (_polygonCount) { - qDebug("CoverageRegion::erase()...\n"); - qDebug("_polygonCount=%d\n",_polygonCount); + qCDebug(octree, "CoverageRegion::erase()...\n"); + qCDebug(octree, "_polygonCount=%d\n",_polygonCount); _myBoundingBox.printDebugDetails(getRegionName()); //for (int i = 0; i < _polygonCount; i++) { - // qDebug("_polygons[%d]=",i); + // qCDebug(octree, "_polygons[%d]=",i); // _polygons[i]->getBoundingBox().printDebugDetails(); //} } @@ -538,4 +539,4 @@ CoverageMapStorageResult CoverageRegion::checkRegion(OctreeProjectedPolygon* pol } } return result; -} \ No newline at end of file +} diff --git a/libraries/octree/src/CoverageMapV2.cpp b/libraries/octree/src/CoverageMapV2.cpp index a29231fe26..61c1242951 100644 --- a/libraries/octree/src/CoverageMapV2.cpp +++ b/libraries/octree/src/CoverageMapV2.cpp @@ -16,6 +16,7 @@ #include +#include "OctreeLogging.h" #include "CoverageMapV2.h" int CoverageMapV2::_mapCount = 0; @@ -80,11 +81,11 @@ void CoverageMapV2::erase() { } if (_isRoot && wantDebugging) { - qDebug("CoverageMapV2 last to be deleted..."); - qDebug("MINIMUM_POLYGON_AREA_TO_STORE=%f",MINIMUM_POLYGON_AREA_TO_STORE); - qDebug("_mapCount=%d",_mapCount); - qDebug("_checkMapRootCalls=%d",_checkMapRootCalls); - qDebug("_notAllInView=%d",_notAllInView); + qCDebug(octree, "CoverageMapV2 last to be deleted..."); + qCDebug(octree, "MINIMUM_POLYGON_AREA_TO_STORE=%f",MINIMUM_POLYGON_AREA_TO_STORE); + qCDebug(octree, "_mapCount=%d",_mapCount); + qCDebug(octree, "_checkMapRootCalls=%d",_checkMapRootCalls); + qCDebug(octree, "_notAllInView=%d",_notAllInView); _mapCount = 0; _checkMapRootCalls = 0; _notAllInView = 0; @@ -247,4 +248,4 @@ void CoverageMapV2::recurseMap(const OctreeProjectedPolygon* polygon, bool store } // normal exit case... return... -} \ No newline at end of file +} diff --git a/libraries/octree/src/JurisdictionMap.cpp b/libraries/octree/src/JurisdictionMap.cpp index ba4a0a1c8f..79c1a96ccc 100644 --- a/libraries/octree/src/JurisdictionMap.cpp +++ b/libraries/octree/src/JurisdictionMap.cpp @@ -17,6 +17,7 @@ #include #include +#include "OctreeLogging.h" #include "JurisdictionMap.h" @@ -148,12 +149,12 @@ void myDebugPrintOctalCode(const unsigned char* octalCode, bool withNewLine) { JurisdictionMap::JurisdictionMap(const char* rootHexCode, const char* endNodesHexCodes) { - qDebug("JurisdictionMap::JurisdictionMap(const char* rootHexCode=[%p] %s, const char* endNodesHexCodes=[%p] %s)", + qCDebug(octree, "JurisdictionMap::JurisdictionMap(const char* rootHexCode=[%p] %s, const char* endNodesHexCodes=[%p] %s)", rootHexCode, rootHexCode, endNodesHexCodes, endNodesHexCodes); _rootOctalCode = hexStringToOctalCode(QString(rootHexCode)); - qDebug("JurisdictionMap::JurisdictionMap() _rootOctalCode=%p octalCode=", _rootOctalCode); + qCDebug(octree, "JurisdictionMap::JurisdictionMap() _rootOctalCode=%p octalCode=", _rootOctalCode); myDebugPrintOctalCode(_rootOctalCode, true); QString endNodesHexStrings(endNodesHexCodes); @@ -165,13 +166,13 @@ JurisdictionMap::JurisdictionMap(const char* rootHexCode, const char* endNodesHe unsigned char* endNodeOctcode = hexStringToOctalCode(endNodeHexString); - qDebug("JurisdictionMap::JurisdictionMap() endNodeList(%d)=%s", + qCDebug(octree, "JurisdictionMap::JurisdictionMap() endNodeList(%d)=%s", i, endNodeHexString.toLocal8Bit().constData()); //printOctalCode(endNodeOctcode); _endNodes.push_back(endNodeOctcode); - qDebug("JurisdictionMap::JurisdictionMap() endNodeOctcode=%p octalCode=", endNodeOctcode); + qCDebug(octree, "JurisdictionMap::JurisdictionMap() endNodeOctcode=%p octalCode=", endNodeOctcode); myDebugPrintOctalCode(endNodeOctcode, true); } @@ -212,7 +213,7 @@ bool JurisdictionMap::readFromFile(const char* filename) { QString settingsFile(filename); QSettings settings(settingsFile, QSettings::IniFormat); QString rootCode = settings.value("root","00").toString(); - qDebug() << "rootCode=" << rootCode; + qCDebug(octree) << "rootCode=" << rootCode; _rootOctalCode = hexStringToOctalCode(rootCode); printOctalCode(_rootOctalCode); @@ -223,7 +224,7 @@ bool JurisdictionMap::readFromFile(const char* filename) { foreach (const QString &childKey, childKeys) { QString childValue = settings.value(childKey).toString(); values.insert(childKey, childValue); - qDebug() << childKey << "=" << childValue; + qCDebug(octree) << childKey << "=" << childValue; unsigned char* octcode = hexStringToOctalCode(childValue); printOctalCode(octcode); @@ -237,11 +238,11 @@ bool JurisdictionMap::readFromFile(const char* filename) { void JurisdictionMap::displayDebugDetails() const { QString rootNodeValue = octalCodeToHexString(_rootOctalCode); - qDebug() << "root:" << rootNodeValue; + qCDebug(octree) << "root:" << rootNodeValue; for (size_t i = 0; i < _endNodes.size(); i++) { QString value = octalCodeToHexString(_endNodes[i]); - qDebug() << "End node[" << i << "]: " << rootNodeValue; + qCDebug(octree) << "End node[" << i << "]: " << rootNodeValue; } } diff --git a/libraries/octree/src/Octree.cpp b/libraries/octree/src/Octree.cpp index e07d62fe83..f4121d051f 100644 --- a/libraries/octree/src/Octree.cpp +++ b/libraries/octree/src/Octree.cpp @@ -46,6 +46,7 @@ #include "OctreeElementBag.h" #include "Octree.h" #include "ViewFrustum.h" +#include "OctreeLogging.h" QVector PERSIST_EXTENSIONS = {"svo", "json"}; @@ -89,7 +90,7 @@ void Octree::recurseElementWithOperation(OctreeElement* element, RecurseOctreeOp = LogHandler::getInstance().addRepeatedMessageRegex( "Octree::recurseElementWithOperation\\(\\) reached DANGEROUSLY_DEEP_RECURSION, bailing!"); - qDebug() << "Octree::recurseElementWithOperation() reached DANGEROUSLY_DEEP_RECURSION, bailing!"; + qCDebug(octree) << "Octree::recurseElementWithOperation() reached DANGEROUSLY_DEEP_RECURSION, bailing!"; return; } @@ -111,7 +112,7 @@ void Octree::recurseElementWithPostOperation(OctreeElement* element, RecurseOctr = LogHandler::getInstance().addRepeatedMessageRegex( "Octree::recurseElementWithPostOperation\\(\\) reached DANGEROUSLY_DEEP_RECURSION, bailing!"); - qDebug() << "Octree::recurseElementWithPostOperation() reached DANGEROUSLY_DEEP_RECURSION, bailing!"; + qCDebug(octree) << "Octree::recurseElementWithPostOperation() reached DANGEROUSLY_DEEP_RECURSION, bailing!"; return; } @@ -141,7 +142,7 @@ void Octree::recurseElementWithOperationDistanceSorted(OctreeElement* element, R = LogHandler::getInstance().addRepeatedMessageRegex( "Octree::recurseElementWithOperationDistanceSorted\\(\\) reached DANGEROUSLY_DEEP_RECURSION, bailing!"); - qDebug() << "Octree::recurseElementWithOperationDistanceSorted() reached DANGEROUSLY_DEEP_RECURSION, bailing!"; + qCDebug(octree) << "Octree::recurseElementWithOperationDistanceSorted() reached DANGEROUSLY_DEEP_RECURSION, bailing!"; return; } @@ -182,7 +183,7 @@ bool Octree::recurseElementWithOperator(OctreeElement* element, RecurseOctreeOpe = LogHandler::getInstance().addRepeatedMessageRegex( "Octree::recurseElementWithOperator\\(\\) reached DANGEROUSLY_DEEP_RECURSION, bailing!"); - qDebug() << "Octree::recurseElementWithOperator() reached DANGEROUSLY_DEEP_RECURSION, bailing!"; + qCDebug(octree) << "Octree::recurseElementWithOperator() reached DANGEROUSLY_DEEP_RECURSION, bailing!"; return false; } @@ -251,7 +252,7 @@ OctreeElement* Octree::createMissingElement(OctreeElement* lastParentElement, co = LogHandler::getInstance().addRepeatedMessageRegex( "Octree::createMissingElement\\(\\) reached DANGEROUSLY_DEEP_RECURSION, bailing!"); - qDebug() << "Octree::createMissingElement() reached DANGEROUSLY_DEEP_RECURSION, bailing!"; + qCDebug(octree) << "Octree::createMissingElement() reached DANGEROUSLY_DEEP_RECURSION, bailing!"; return lastParentElement; } int indexOfNewChild = branchIndexWithDescendant(lastParentElement->getOctalCode(), codeToReach); @@ -283,13 +284,13 @@ int Octree::readElementData(OctreeElement* destinationElement, const unsigned ch const unsigned char ALL_CHILDREN_ASSUMED_TO_EXIST = 0xFF; if ((size_t)bytesLeftToRead < sizeof(unsigned char)) { - qDebug() << "UNEXPECTED: readElementData() only had " << bytesLeftToRead << " bytes. " + qCDebug(octree) << "UNEXPECTED: readElementData() only had " << bytesLeftToRead << " bytes. " "Not enough for meaningful data."; return bytesAvailable; // assume we read the entire buffer... } if (destinationElement->getScale() < SCALE_AT_DANGEROUSLY_DEEP_RECURSION) { - qDebug() << "UNEXPECTED: readElementData() destination element is unreasonably small [" + qCDebug(octree) << "UNEXPECTED: readElementData() destination element is unreasonably small [" << destinationElement->getScale() << " meters] " << " Discarding " << bytesAvailable << " remaining bytes."; return bytesAvailable; // assume we read the entire buffer... @@ -331,7 +332,7 @@ int Octree::readElementData(OctreeElement* destinationElement, const unsigned ch if (bytesLeftToRead < bytesForMasks) { if (bytesLeftToRead > 0) { - qDebug() << "UNEXPECTED: readElementDataFromBuffer() only had " << bytesLeftToRead << " bytes before masks. " + qCDebug(octree) << "UNEXPECTED: readElementDataFromBuffer() only had " << bytesLeftToRead << " bytes before masks. " "Not enough for meaningful data."; } return bytesAvailable; // assume we read the entire buffer... @@ -414,14 +415,14 @@ void Octree::readBitstreamToTree(const unsigned char * bitstream, unsigned long ); - qDebug() << "UNEXPECTED: parsing of the octal code would make UNREASONABLY_DEEP_RECURSION... " + qCDebug(octree) << "UNEXPECTED: parsing of the octal code would make UNREASONABLY_DEEP_RECURSION... " "numberOfThreeBitSectionsInStream:" << numberOfThreeBitSectionsInStream << "This buffer is corrupt. Returning."; return; } if (numberOfThreeBitSectionsInStream == OVERFLOWED_OCTCODE_BUFFER) { - qDebug() << "UNEXPECTED: parsing of the octal code would overflow the buffer. " + qCDebug(octree) << "UNEXPECTED: parsing of the octal code would overflow the buffer. " "This buffer is corrupt. Returning."; return; } @@ -605,7 +606,7 @@ void Octree::processRemoveOctreeElementsBitstream(const unsigned char* bitstream int codeLength = numberOfThreeBitSectionsInCode(voxelCode, maxSize); if (codeLength == OVERFLOWED_OCTCODE_BUFFER) { - qDebug("WARNING! Got remove voxel bitstream that would overflow buffer in numberOfThreeBitSectionsInCode()," + qCDebug(octree, "WARNING! Got remove voxel bitstream that would overflow buffer in numberOfThreeBitSectionsInCode()," " bailing processing of packet!"); break; } @@ -616,7 +617,7 @@ void Octree::processRemoveOctreeElementsBitstream(const unsigned char* bitstream voxelCode += voxelDataSize; atByte += voxelDataSize; } else { - qDebug("WARNING! Got remove voxel bitstream that would overflow buffer, bailing processing!"); + qCDebug(octree, "WARNING! Got remove voxel bitstream that would overflow buffer, bailing processing!"); break; } } @@ -636,7 +637,7 @@ void Octree::reaverageOctreeElements(OctreeElement* startElement) { recursionCount++; } if (recursionCount > UNREASONABLY_DEEP_RECURSION) { - qDebug("Octree::reaverageOctreeElements()... bailing out of UNREASONABLY_DEEP_RECURSION"); + qCDebug(octree, "Octree::reaverageOctreeElements()... bailing out of UNREASONABLY_DEEP_RECURSION"); recursionCount--; return; } @@ -1004,7 +1005,7 @@ int Octree::encodeTreeBitstream(OctreeElement* element, // you can't call this without a valid element if (!element) { - qDebug("WARNING! encodeTreeBitstream() called with element=NULL"); + qCDebug(octree, "WARNING! encodeTreeBitstream() called with element=NULL"); params.stopReason = EncodeBitstreamParams::NULL_NODE; return bytesWritten; } @@ -1100,7 +1101,7 @@ int Octree::encodeTreeBitstreamRecursion(OctreeElement* element, // you can't call this without a valid element if (!element) { - qDebug("WARNING! encodeTreeBitstreamRecursion() called with element=NULL"); + qCDebug(octree, "WARNING! encodeTreeBitstreamRecursion() called with element=NULL"); params.stopReason = EncodeBitstreamParams::NULL_NODE; return bytesAtThisLevel; } @@ -1541,16 +1542,16 @@ int Octree::encodeTreeBitstreamRecursion(OctreeElement* element, } if (!mustIncludeAllChildData() && !continueThisLevel) { - qDebug() << "WARNING UNEXPECTED CASE: reached end of child element data loop with continueThisLevel=FALSE"; - qDebug() << "This is not expected!!!! -- continueThisLevel=FALSE...."; + qCDebug(octree) << "WARNING UNEXPECTED CASE: reached end of child element data loop with continueThisLevel=FALSE"; + qCDebug(octree) << "This is not expected!!!! -- continueThisLevel=FALSE...."; } if (continueThisLevel && actualChildrenDataBits != childrenDataBits) { // repair the child data mask continueThisLevel = packetData->updatePriorBitMask(childDataBitsPlaceHolder, actualChildrenDataBits); if (!continueThisLevel) { - qDebug() << "WARNING UNEXPECTED CASE: Failed to update childDataBitsPlaceHolder"; - qDebug() << "This is not expected!!!! -- continueThisLevel=FALSE...."; + qCDebug(octree) << "WARNING UNEXPECTED CASE: Failed to update childDataBitsPlaceHolder"; + qCDebug(octree) << "This is not expected!!!! -- continueThisLevel=FALSE...."; } } @@ -1565,8 +1566,8 @@ int Octree::encodeTreeBitstreamRecursion(OctreeElement* element, params.stats->existsBitsWritten(); } } else { - qDebug() << "WARNING UNEXPECTED CASE: Failed to append childrenExistInTreeBits"; - qDebug() << "This is not expected!!!! -- continueThisLevel=FALSE...."; + qCDebug(octree) << "WARNING UNEXPECTED CASE: Failed to append childrenExistInTreeBits"; + qCDebug(octree) << "This is not expected!!!! -- continueThisLevel=FALSE...."; } } @@ -1580,8 +1581,8 @@ int Octree::encodeTreeBitstreamRecursion(OctreeElement* element, params.stats->existsInPacketBitsWritten(); } } else { - qDebug() << "WARNING UNEXPECTED CASE: Failed to append childrenExistInPacketBits"; - qDebug() << "This is not expected!!!! -- continueThisLevel=FALSE...."; + qCDebug(octree) << "WARNING UNEXPECTED CASE: Failed to append childrenExistInPacketBits"; + qCDebug(octree) << "This is not expected!!!! -- continueThisLevel=FALSE...."; } } @@ -1697,8 +1698,8 @@ int Octree::encodeTreeBitstreamRecursion(OctreeElement* element, // repair the child exists mask continueThisLevel = packetData->updatePriorBitMask(childExistsPlaceHolder, childrenExistInPacketBits); if (!continueThisLevel) { - qDebug() << "WARNING UNEXPECTED CASE: Failed to update childExistsPlaceHolder"; - qDebug() << "This is not expected!!!! -- continueThisLevel=FALSE...."; + qCDebug(octree) << "WARNING UNEXPECTED CASE: Failed to update childExistsPlaceHolder"; + qCDebug(octree) << "This is not expected!!!! -- continueThisLevel=FALSE...."; } // If this is the last of the child exists bits, then we're actually be rolling out the entire tree @@ -1708,10 +1709,10 @@ int Octree::encodeTreeBitstreamRecursion(OctreeElement* element, if (!continueThisLevel) { if (wantDebug) { - qDebug() << " WARNING line:" << __LINE__; - qDebug() << " breaking the child recursion loop with continueThisLevel=false!!!"; - qDebug() << " AFTER attempting to updatePriorBitMask() for empty sub tree...."; - qDebug() << " IS THIS ACCEPTABLE!!!!"; + qCDebug(octree) << " WARNING line:" << __LINE__; + qCDebug(octree) << " breaking the child recursion loop with continueThisLevel=false!!!"; + qCDebug(octree) << " AFTER attempting to updatePriorBitMask() for empty sub tree...."; + qCDebug(octree) << " IS THIS ACCEPTABLE!!!!"; } break; // can't continue... } @@ -1743,8 +1744,8 @@ int Octree::encodeTreeBitstreamRecursion(OctreeElement* element, // now that all slices are back in the correct order, copy them to the correct output buffer continueThisLevel = packetData->updatePriorBytes(firstRecursiveSliceOffset, &tempReshuffleBuffer[0], allSlicesSize); if (!continueThisLevel) { - qDebug() << "WARNING UNEXPECTED CASE: Failed to update recursive slice!!!"; - qDebug() << "This is not expected!!!! -- continueThisLevel=FALSE...."; + qCDebug(octree) << "WARNING UNEXPECTED CASE: Failed to update recursive slice!!!"; + qCDebug(octree) << "This is not expected!!!! -- continueThisLevel=FALSE...."; } } } // end keepDiggingDeeper @@ -1766,7 +1767,7 @@ int Octree::encodeTreeBitstreamRecursion(OctreeElement* element, if (partOfRootFit) { continueThisLevel = packetData->endLevel(rootDataLevelKey); if (!continueThisLevel) { - qDebug() << " UNEXPECTED ROOT ELEMENT -- could not packetData->endLevel(rootDataLevelKey) -- line:" << __LINE__; + qCDebug(octree) << " UNEXPECTED ROOT ELEMENT -- could not packetData->endLevel(rootDataLevelKey) -- line:" << __LINE__; } } else { packetData->discardLevel(rootDataLevelKey); @@ -1791,8 +1792,8 @@ int Octree::encodeTreeBitstreamRecursion(OctreeElement* element, } if (!continueThisLevel) { - qDebug() << "WARNING UNEXPECTED CASE: Something failed in packing ROOT data"; - qDebug() << "This is not expected!!!! -- continueThisLevel=FALSE...."; + qCDebug(octree) << "WARNING UNEXPECTED CASE: Something failed in packing ROOT data"; + qCDebug(octree) << "This is not expected!!!! -- continueThisLevel=FALSE...."; } } @@ -1805,8 +1806,8 @@ int Octree::encodeTreeBitstreamRecursion(OctreeElement* element, packetData->discardLevel(thisLevelKey); if (!mustIncludeAllChildData()) { - qDebug() << "WARNING UNEXPECTED CASE: Something failed in attempting to pack this element"; - qDebug() << "This is not expected!!!! -- continueThisLevel=FALSE...."; + qCDebug(octree) << "WARNING UNEXPECTED CASE: Something failed in attempting to pack this element"; + qCDebug(octree) << "This is not expected!!!! -- continueThisLevel=FALSE...."; } } @@ -1815,9 +1816,9 @@ int Octree::encodeTreeBitstreamRecursion(OctreeElement* element, // added back to the element bag. if (!continueThisLevel) { if (!mustIncludeAllChildData()) { - qDebug() << "WARNING UNEXPECTED CASE - Something failed in attempting to pack this element."; - qDebug() << " If the datatype requires all child data, then this might happen. Otherwise" ; - qDebug() << " this is an unexpected case and we should research a potential logic error." ; + qCDebug(octree) << "WARNING UNEXPECTED CASE - Something failed in attempting to pack this element."; + qCDebug(octree) << " If the datatype requires all child data, then this might happen. Otherwise" ; + qCDebug(octree) << " this is an unexpected case and we should research a potential logic error." ; } bag.insert(element); @@ -1864,7 +1865,7 @@ bool Octree::readFromFile(const char* fileName) { emit importSize(1.0f, 1.0f, 1.0f); emit importProgress(0); - qDebug() << "Loading file" << qFileName << "..."; + qCDebug(octree) << "Loading file" << qFileName << "..."; fileOk = readFromStream(fileLength, fileInputStream); @@ -1891,7 +1892,7 @@ bool Octree::readFromURL(const QString& urlString) { QNetworkAccessManager& networkAccessManager = NetworkAccessManager::getInstance(); QNetworkReply* reply = networkAccessManager.get(request); - qDebug() << "Downloading svo at" << qPrintable(urlString); + qCDebug(octree) << "Downloading svo at" << qPrintable(urlString); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); @@ -1916,10 +1917,10 @@ bool Octree::readFromStream(unsigned long streamLength, QDataStream& inputStream device->ungetChar(firstChar); if (firstChar == (char) PacketTypeEntityData) { - qDebug() << "Reading from SVO Stream length:" << streamLength; + qCDebug(octree) << "Reading from SVO Stream length:" << streamLength; return readSVOFromStream(streamLength, inputStream); } else { - qDebug() << "Reading from JSON Stream length:" << streamLength; + qCDebug(octree) << "Reading from JSON Stream length:" << streamLength; return readJSONFromStream(streamLength, inputStream); } } @@ -1965,28 +1966,28 @@ bool Octree::readSVOFromStream(unsigned long streamLength, QDataStream& inputStr dataAt += sizeof(gotVersion); dataLength -= sizeof(gotVersion); fileOk = true; - qDebug("SVO file version match. Expected: %d Got: %d", + qCDebug(octree, "SVO file version match. Expected: %d Got: %d", versionForPacketType(expectedDataPacketType()), gotVersion); hasBufferBreaks = versionHasSVOfileBreaks(gotVersion); } else { - qDebug("SVO file version mismatch. Expected: %d Got: %d", + qCDebug(octree, "SVO file version mismatch. Expected: %d Got: %d", versionForPacketType(expectedDataPacketType()), gotVersion); } } else { - qDebug() << "SVO file type mismatch. Expected: " << nameForPacketType(expectedType) + qCDebug(octree) << "SVO file type mismatch. Expected: " << nameForPacketType(expectedType) << " Got: " << nameForPacketType(gotType); } } else { - qDebug() << " NOTE: this file type does not include type and version information."; + qCDebug(octree) << " NOTE: this file type does not include type and version information."; fileOk = true; // assume the file is ok } if (hasBufferBreaks) { - qDebug() << " this version includes buffer breaks"; + qCDebug(octree) << " this version includes buffer breaks"; } else { - qDebug() << " this version does not include buffer breaks"; + qCDebug(octree) << " this version does not include buffer breaks"; } if (fileOk) { @@ -2022,13 +2023,13 @@ bool Octree::readSVOFromStream(unsigned long streamLength, QDataStream& inputStr remainingLength -= sizeof(chunkLength); if (chunkLength > remainingLength) { - qDebug() << "UNEXPECTED chunk size of:" << chunkLength + qCDebug(octree) << "UNEXPECTED chunk size of:" << chunkLength << "greater than remaining length:" << remainingLength; break; } if (chunkLength > MAX_CHUNK_LENGTH) { - qDebug() << "UNEXPECTED chunk size of:" << chunkLength + qCDebug(octree) << "UNEXPECTED chunk size of:" << chunkLength << "greater than MAX_CHUNK_LENGTH:" << MAX_CHUNK_LENGTH; break; } @@ -2078,7 +2079,7 @@ void Octree::writeToFile(const char* fileName, OctreeElement* element, QString p } else if (persistAsFileType == "json") { writeToJSONFile(cFileName, element); } else { - qDebug() << "unable to write octree to file of type" << persistAsFileType; + qCDebug(octree) << "unable to write octree to file of type" << persistAsFileType; } } @@ -2086,7 +2087,7 @@ void Octree::writeToJSONFile(const char* fileName, OctreeElement* element) { QFile persistFile(fileName); QVariantMap entityDescription; - qDebug("Saving to file %s...", fileName); + qCDebug(octree, "Saving to file %s...", fileName); OctreeElement* top; if (element) { @@ -2107,7 +2108,7 @@ void Octree::writeToSVOFile(const char* fileName, OctreeElement* element) { std::ofstream file(fileName, std::ios::out|std::ios::binary); if(file.is_open()) { - qDebug("Saving to file %s...", fileName); + qCDebug(octree, "Saving to file %s...", fileName); PacketType expectedType = expectedDataPacketType(); PacketVersion expectedVersion = versionForPacketType(expectedType); @@ -2118,14 +2119,14 @@ void Octree::writeToSVOFile(const char* fileName, OctreeElement* element) { // if so, read the first byte of the file and see if it matches the expected version code file.write(reinterpret_cast(&expectedType), sizeof(expectedType)); file.write(&expectedVersion, sizeof(expectedVersion)); - qDebug() << "SVO file type: " << nameForPacketType(expectedType) << " version: " << (int)expectedVersion; + qCDebug(octree) << "SVO file type: " << nameForPacketType(expectedType) << " version: " << (int)expectedVersion; hasBufferBreaks = versionHasSVOfileBreaks(expectedVersion); } if (hasBufferBreaks) { - qDebug() << " this version includes buffer breaks"; + qCDebug(octree) << " this version includes buffer breaks"; } else { - qDebug() << " this version does not include buffer breaks"; + qCDebug(octree) << " this version does not include buffer breaks"; } diff --git a/libraries/octree/src/OctreeEditPacketSender.cpp b/libraries/octree/src/OctreeEditPacketSender.cpp index cc47190228..65fbb0f983 100644 --- a/libraries/octree/src/OctreeEditPacketSender.cpp +++ b/libraries/octree/src/OctreeEditPacketSender.cpp @@ -15,6 +15,7 @@ #include #include +#include "OctreeLogging.h" #include "OctreeEditPacketSender.h" const int OctreeEditPacketSender::DEFAULT_MAX_PENDING_MESSAGES = PacketSender::DEFAULT_PACKETS_PER_SECOND; @@ -119,7 +120,7 @@ void OctreeEditPacketSender::queuePacketToNode(const QUuid& nodeUUID, unsigned c quint64 queuedAt = usecTimestampNow(); quint64 transitTime = queuedAt - createdAt; - qDebug() << "OctreeEditPacketSender::queuePacketToNode() queued " << buffer[0] << + qCDebug(octree) << "OctreeEditPacketSender::queuePacketToNode() queued " << buffer[0] << " - command to node bytes=" << length << " satoshiCost=" << satoshiCost << " sequence=" << sequence << diff --git a/libraries/octree/src/OctreeElement.cpp b/libraries/octree/src/OctreeElement.cpp index c8564ee5cb..af66af69e3 100644 --- a/libraries/octree/src/OctreeElement.cpp +++ b/libraries/octree/src/OctreeElement.cpp @@ -26,6 +26,7 @@ #include "OctreeConstants.h" #include "OctreeElement.h" #include "Octree.h" +#include "OctreeLogging.h" #include "SharedUtil.h" quint64 OctreeElement::_octreeMemoryUsage = 0; @@ -282,7 +283,7 @@ void OctreeElement::auditChildren(const char* label) const { OctreeElement* testChildNew = getChildAtIndex(childIndex); OctreeElement* testChildOld = _childrenArray[childIndex]; - qDebug("child at index %d... testChildOld=%p testChildNew=%p %s", + qCebug("child at index %d... testChildOld=%p testChildNew=%p %s", childIndex, testChildOld, testChildNew , ((testChildNew != testChildOld) ? " DOES NOT MATCH <<<< BAD <<<<" : " - OK ") ); @@ -435,7 +436,7 @@ OctreeElement* OctreeElement::getChildAtIndex(int childIndex) const { if (externalIndex < childCount && externalIndex >= 0) { result = _children.external[externalIndex]; } else { - qDebug("getChildAtIndex() attempt to access external client out of " + qCDebug(octree, "getChildAtIndex() attempt to access external client out of " "bounds externalIndex=%d <<<<<<<<<< WARNING!!!", externalIndex); } break; @@ -446,7 +447,7 @@ OctreeElement* OctreeElement::getChildAtIndex(int childIndex) const { } #ifdef HAS_AUDIT_CHILDREN if (result != _childrenArray[childIndex]) { - qDebug("getChildAtIndex() case:%s result<%p> != _childrenArray[childIndex]<%p> <<<<<<<<<< WARNING!!!", + qCDebug(octree, "getChildAtIndex() case:%s result<%p> != _childrenArray[childIndex]<%p> <<<<<<<<<< WARNING!!!", caseStr, result,_childrenArray[childIndex]); } #endif // def HAS_AUDIT_CHILDREN @@ -1119,7 +1120,7 @@ void OctreeElement::setChildAtIndex(int childIndex, OctreeElement* child) { _externalChildrenMemoryUsage += newChildCount * sizeof(OctreeElement*); } else { //assert(false); - qDebug("THIS SHOULD NOT HAPPEN previousChildCount == %d && newChildCount == %d",previousChildCount, newChildCount); + qCDebug(octree, "THIS SHOULD NOT HAPPEN previousChildCount == %d && newChildCount == %d",previousChildCount, newChildCount); } // check to see if we could store these 4 children locally @@ -1163,7 +1164,7 @@ bool OctreeElement::safeDeepDeleteChildAtIndex(int childIndex, int recursionCoun = LogHandler::getInstance().addRepeatedMessageRegex( "OctreeElement::safeDeepDeleteChildAtIndex\\(\\) reached DANGEROUSLY_DEEP_RECURSION, bailing!"); - qDebug() << "OctreeElement::safeDeepDeleteChildAtIndex() reached DANGEROUSLY_DEEP_RECURSION, bailing!"; + qCDebug(octree) << "OctreeElement::safeDeepDeleteChildAtIndex() reached DANGEROUSLY_DEEP_RECURSION, bailing!"; return deleteApproved; } OctreeElement* childToDelete = getChildAtIndex(childIndex); @@ -1398,7 +1399,7 @@ OctreeElement* OctreeElement::getOrCreateChildElementAt(float x, float y, float float halfOurScale = ourScale / 2.0f; if(s > ourScale) { - qDebug("UNEXPECTED -- OctreeElement::getOrCreateChildElementAt() s=[%f] > ourScale=[%f] ", s, ourScale); + qCDebug(octree, "UNEXPECTED -- OctreeElement::getOrCreateChildElementAt() s=[%f] > ourScale=[%f] ", s, ourScale); } if (s > halfOurScale) { @@ -1521,11 +1522,11 @@ int OctreeElement::getMyChildContaining(const AACube& cube) const { // TODO: consider changing this to assert() if (cubeScale > ourScale) { - qDebug() << "UNEXPECTED -- OctreeElement::getMyChildContaining() -- (cubeScale > ourScale)"; - qDebug() << " cube=" << cube; - qDebug() << " elements AACube=" << _cube; - qDebug() << " cubeScale=" << cubeScale; - qDebug() << " ourScale=" << ourScale; + qCDebug(octree) << "UNEXPECTED -- OctreeElement::getMyChildContaining() -- (cubeScale > ourScale)"; + qCDebug(octree) << " cube=" << cube; + qCDebug(octree) << " elements AACube=" << _cube; + qCDebug(octree) << " cubeScale=" << cubeScale; + qCDebug(octree) << " ourScale=" << ourScale; assert(false); } @@ -1553,7 +1554,7 @@ int OctreeElement::getMyChildContaining(const AABox& box) const { // TODO: consider changing this to assert() if(boxLargestScale > ourScale) { - qDebug("UNEXPECTED -- OctreeElement::getMyChildContaining() " + qCDebug(octree, "UNEXPECTED -- OctreeElement::getMyChildContaining() " "boxLargestScale=[%f] > ourScale=[%f] ", boxLargestScale, ourScale); } diff --git a/libraries/octree/src/OctreeHeadlessViewer.cpp b/libraries/octree/src/OctreeHeadlessViewer.cpp index d47a324e07..ea5c811ce1 100644 --- a/libraries/octree/src/OctreeHeadlessViewer.cpp +++ b/libraries/octree/src/OctreeHeadlessViewer.cpp @@ -11,6 +11,7 @@ #include +#include "OctreeLogging.h" #include "OctreeHeadlessViewer.h" OctreeHeadlessViewer::OctreeHeadlessViewer() : @@ -41,16 +42,16 @@ void OctreeHeadlessViewer::queryOctree() { bool wantExtraDebugging = false; if (wantExtraDebugging) { - qDebug() << "OctreeHeadlessViewer::queryOctree() _jurisdictionListener=" << _jurisdictionListener; - qDebug() << "---------------"; - qDebug() << "_jurisdictionListener=" << _jurisdictionListener; - qDebug() << "Jurisdictions..."; + qCDebug(octree) << "OctreeHeadlessViewer::queryOctree() _jurisdictionListener=" << _jurisdictionListener; + qCDebug(octree) << "---------------"; + qCDebug(octree) << "_jurisdictionListener=" << _jurisdictionListener; + qCDebug(octree) << "Jurisdictions..."; jurisdictions.lockForRead(); for (NodeToJurisdictionMapIterator i = jurisdictions.begin(); i != jurisdictions.end(); ++i) { - qDebug() << i.key() << ": " << &i.value(); + qCDebug(octree) << i.key() << ": " << &i.value(); } jurisdictions.unlock(); - qDebug() << "---------------"; + qCDebug(octree) << "---------------"; } // These will be the same for all servers, so we can set them up once and then reuse for each server we send to. @@ -115,7 +116,7 @@ void OctreeHeadlessViewer::queryOctree() { }); if (wantExtraDebugging) { - qDebug("Servers: total %d, in view %d, unknown jurisdiction %d", + qCDebug(octree, "Servers: total %d, in view %d, unknown jurisdiction %d", totalServers, inViewServers, unknownJurisdictionServers); } @@ -136,7 +137,7 @@ void OctreeHeadlessViewer::queryOctree() { } if (wantExtraDebugging) { - qDebug("perServerPPS: %d perUnknownServer: %d", perServerPPS, perUnknownServer); + qCDebug(octree, "perServerPPS: %d perUnknownServer: %d", perServerPPS, perUnknownServer); } auto nodeList = DependencyManager::get(); @@ -157,7 +158,7 @@ void OctreeHeadlessViewer::queryOctree() { jurisdictions.unlock(); unknownView = true; // assume it's in view if (wantExtraDebugging) { - qDebug() << "no known jurisdiction for node " << *node << ", assume it's visible."; + qCDebug(octree) << "no known jurisdiction for node " << *node << ", assume it's visible."; } } else { const JurisdictionMap& map = (jurisdictions)[nodeUUID]; @@ -179,7 +180,7 @@ void OctreeHeadlessViewer::queryOctree() { } else { jurisdictions.unlock(); if (wantExtraDebugging) { - qDebug() << "Jurisdiction without RootCode for node " << *node << ". That's unusual!"; + qCDebug(octree) << "Jurisdiction without RootCode for node " << *node << ". That's unusual!"; } } } @@ -187,11 +188,11 @@ void OctreeHeadlessViewer::queryOctree() { if (inView) { _octreeQuery.setMaxOctreePacketsPerSecond(perServerPPS); if (wantExtraDebugging) { - qDebug() << "inView for node " << *node << ", give it budget of " << perServerPPS; + qCDebug(octree) << "inView for node " << *node << ", give it budget of " << perServerPPS; } } else if (unknownView) { if (wantExtraDebugging) { - qDebug() << "no known jurisdiction for node " << *node << ", give it budget of " + qCDebug(octree) << "no known jurisdiction for node " << *node << ", give it budget of " << perUnknownServer << " to send us jurisdiction."; } @@ -205,11 +206,11 @@ void OctreeHeadlessViewer::queryOctree() { _octreeQuery.setCameraNearClip(0.1f); _octreeQuery.setCameraFarClip(0.1f); if (wantExtraDebugging) { - qDebug() << "Using 'minimal' camera position for node" << *node; + qCDebug(octree) << "Using 'minimal' camera position for node" << *node; } } else { if (wantExtraDebugging) { - qDebug() << "Using regular camera position for node" << *node; + qCDebug(octree) << "Using regular camera position for node" << *node; } } _octreeQuery.setMaxOctreePacketsPerSecond(perUnknownServer); diff --git a/libraries/octree/src/OctreeLogging.cpp b/libraries/octree/src/OctreeLogging.cpp new file mode 100644 index 0000000000..beef83c31d --- /dev/null +++ b/libraries/octree/src/OctreeLogging.cpp @@ -0,0 +1,14 @@ +// +// OctreeLogging.cpp +// libraries/octree/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "OctreeLogging.h" + +Q_LOGGING_CATEGORY(octree, "hifi.octree") diff --git a/libraries/octree/src/OctreeLogging.h b/libraries/octree/src/OctreeLogging.h new file mode 100644 index 0000000000..dd43d4dbab --- /dev/null +++ b/libraries/octree/src/OctreeLogging.h @@ -0,0 +1,19 @@ +// +// OctreeLogging.h +// libraries/octree/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_OctreeLogging_h +#define hifi_OctreeLogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(octree) + +#endif // hifi_OctreeLogging_h diff --git a/libraries/octree/src/OctreePacketData.cpp b/libraries/octree/src/OctreePacketData.cpp index 6206198962..674faa11c3 100644 --- a/libraries/octree/src/OctreePacketData.cpp +++ b/libraries/octree/src/OctreePacketData.cpp @@ -12,6 +12,7 @@ #include #include +#include "OctreeLogging.h" #include "OctreePacketData.h" bool OctreePacketData::_debug = false; @@ -65,12 +66,12 @@ bool OctreePacketData::append(const unsigned char* data, int length) { const bool wantDebug = false; if (wantDebug && !success) { - qDebug() << "OctreePacketData::append(const unsigned char* data, int length) FAILING...."; - qDebug() << " length=" << length; - qDebug() << " _bytesAvailable=" << _bytesAvailable; - qDebug() << " _bytesInUse=" << _bytesInUse; - qDebug() << " _targetSize=" << _targetSize; - qDebug() << " _bytesReserved=" << _bytesReserved; + qCDebug(octree) << "OctreePacketData::append(const unsigned char* data, int length) FAILING...."; + qCDebug(octree) << " length=" << length; + qCDebug(octree) << " _bytesAvailable=" << _bytesAvailable; + qCDebug(octree) << " _bytesInUse=" << _bytesInUse; + qCDebug(octree) << " _targetSize=" << _targetSize; + qCDebug(octree) << " _bytesReserved=" << _bytesReserved; } return success; } @@ -176,7 +177,7 @@ const unsigned char* OctreePacketData::getFinalizedData() { if (_dirty) { if (_debug) { - qDebug("getFinalizedData() _compressedBytes=%d _bytesInUse=%d",_compressedBytes, _bytesInUse); + qCDebug(octree, "getFinalizedData() _compressedBytes=%d _bytesInUse=%d",_compressedBytes, _bytesInUse); } compressContent(); } @@ -190,7 +191,7 @@ int OctreePacketData::getFinalizedSize() { if (_dirty) { if (_debug) { - qDebug("getFinalizedSize() _compressedBytes=%d _bytesInUse=%d",_compressedBytes, _bytesInUse); + qCDebug(octree, "getFinalizedSize() _compressedBytes=%d _bytesInUse=%d",_compressedBytes, _bytesInUse); } compressContent(); } @@ -241,7 +242,7 @@ void OctreePacketData::discardLevel(LevelDetails key) { _totalBytesOfColor -= reduceBytesOfColor; if (_debug) { - qDebug("discardLevel() BEFORE _dirty=%s bytesInLevel=%d _compressedBytes=%d _bytesInUse=%d", + qCDebug(octree, "discardLevel() BEFORE _dirty=%s bytesInLevel=%d _compressedBytes=%d _bytesInUse=%d", debug::valueOf(_dirty), bytesInLevel, _compressedBytes, _bytesInUse); } @@ -253,7 +254,7 @@ void OctreePacketData::discardLevel(LevelDetails key) { _bytesReserved = key._bytesReservedAtStart; if (_debug) { - qDebug("discardLevel() AFTER _dirty=%s bytesInLevel=%d _compressedBytes=%d _bytesInUse=%d", + qCDebug(octree, "discardLevel() AFTER _dirty=%s bytesInLevel=%d _compressedBytes=%d _bytesInUse=%d", debug::valueOf(_dirty), bytesInLevel, _compressedBytes, _bytesInUse); } } @@ -263,9 +264,9 @@ bool OctreePacketData::endLevel(LevelDetails key) { // reserved bytes should be the same value as when the level started if (_bytesReserved != key._bytesReservedAtStart) { - qDebug() << "WARNING: endLevel() called but some reserved bytes not used."; - qDebug() << " current bytesReserved:" << _bytesReserved; - qDebug() << " start level bytesReserved:" << key._bytesReservedAtStart; + qCDebug(octree) << "WARNING: endLevel() called but some reserved bytes not used."; + qCDebug(octree) << " current bytesReserved:" << _bytesReserved; + qCDebug(octree) << " start level bytesReserved:" << key._bytesReservedAtStart; } return success; @@ -499,13 +500,13 @@ void OctreePacketData::loadFinalizedContent(const unsigned char* data, int lengt } } else { if (_debug) { - qDebug("OctreePacketData::loadCompressedContent()... length = 0, nothing to do..."); + qCDebug(octree, "OctreePacketData::loadCompressedContent()... length = 0, nothing to do..."); } } } void OctreePacketData::debugContent() { - qDebug("OctreePacketData::debugContent()... COMPRESSED DATA.... size=%d",_compressedBytes); + qCDebug(octree, "OctreePacketData::debugContent()... COMPRESSED DATA.... size=%d",_compressedBytes); int perline=0; for (int i = 0; i < _compressedBytes; i++) { printf("%.2x ",_compressed[i]); @@ -517,7 +518,7 @@ void OctreePacketData::debugContent() { } printf("\n"); - qDebug("OctreePacketData::debugContent()... UNCOMPRESSED DATA.... size=%d",_bytesInUse); + qCDebug(octree, "OctreePacketData::debugContent()... UNCOMPRESSED DATA.... size=%d",_bytesInUse); perline=0; for (int i = 0; i < _bytesInUse; i++) { printf("%.2x ",_uncompressed[i]); diff --git a/libraries/octree/src/OctreePersistThread.cpp b/libraries/octree/src/OctreePersistThread.cpp index 02f46ee64b..9c7a43b12d 100644 --- a/libraries/octree/src/OctreePersistThread.cpp +++ b/libraries/octree/src/OctreePersistThread.cpp @@ -26,6 +26,7 @@ #include #include +#include "OctreeLogging.h" #include "OctreePersistThread.h" const int OctreePersistThread::DEFAULT_PERSIST_INTERVAL = 1000 * 30; // every 30 seconds @@ -54,7 +55,7 @@ OctreePersistThread::OctreePersistThread(Octree* tree, const QString& filename, void OctreePersistThread::parseSettings(const QJsonObject& settings) { if (settings["backups"].isArray()) { const QJsonArray& backupRules = settings["backups"].toArray(); - qDebug() << "BACKUP RULES:"; + qCDebug(octree) << "BACKUP RULES:"; foreach (const QJsonValue& value, backupRules) { @@ -77,10 +78,10 @@ void OctreePersistThread::parseSettings(const QJsonObject& settings) { count = countVal.toInt(); } - qDebug() << " Name:" << obj["Name"].toString(); - qDebug() << " format:" << obj["format"].toString(); - qDebug() << " interval:" << interval; - qDebug() << " count:" << count; + qCDebug(octree) << " Name:" << obj["Name"].toString(); + qCDebug(octree) << " format:" << obj["format"].toString(); + qCDebug(octree) << " interval:" << interval; + qCDebug(octree) << " count:" << count; BackupRule newRule = { obj["Name"].toString(), interval, obj["format"].toString(), count, 0}; @@ -89,15 +90,15 @@ void OctreePersistThread::parseSettings(const QJsonObject& settings) { if (newRule.lastBackup > 0) { quint64 now = usecTimestampNow(); quint64 sinceLastBackup = now - newRule.lastBackup; - qDebug() << " lastBackup:" << qPrintable(formatUsecTime(sinceLastBackup)) << "ago"; + qCDebug(octree) << " lastBackup:" << qPrintable(formatUsecTime(sinceLastBackup)) << "ago"; } else { - qDebug() << " lastBackup: NEVER"; + qCDebug(octree) << " lastBackup: NEVER"; } _backupRules << newRule; } } else { - qDebug() << "BACKUP RULES: NONE"; + qCDebug(octree) << "BACKUP RULES: NONE"; } } @@ -122,7 +123,7 @@ bool OctreePersistThread::process() { if (!_initialLoadComplete) { quint64 loadStarted = usecTimestampNow(); - qDebug() << "loading Octrees from file: " << _filename << "..."; + qCDebug(octree) << "loading Octrees from file: " << _filename << "..."; bool persistantFileRead; @@ -135,7 +136,7 @@ bool OctreePersistThread::process() { QString lockFileName = _filename + ".lock"; std::ifstream lockFile(qPrintable(lockFileName), std::ios::in|std::ios::binary|std::ios::ate); if(lockFile.is_open()) { - qDebug() << "WARNING: Octree lock file detected at startup:" << lockFileName + qCDebug(octree) << "WARNING: Octree lock file detected at startup:" << lockFileName << "-- Attempting to restore from previous backup file."; // This is where we should attempt to find the most recent backup and restore from @@ -143,9 +144,9 @@ bool OctreePersistThread::process() { restoreFromMostRecentBackup(); lockFile.close(); - qDebug() << "Loading Octree... lock file closed:" << lockFileName; + qCDebug(octree) << "Loading Octree... lock file closed:" << lockFileName; remove(qPrintable(lockFileName)); - qDebug() << "Loading Octree... lock file removed:" << lockFileName; + qCDebug(octree) << "Loading Octree... lock file removed:" << lockFileName; } persistantFileRead = _tree->readFromFile(qPrintable(_filename.toLocal8Bit())); @@ -157,23 +158,23 @@ bool OctreePersistThread::process() { _loadTimeUSecs = loadDone - loadStarted; _tree->clearDirtyBit(); // the tree is clean since we just loaded it - qDebug("DONE loading Octrees from file... fileRead=%s", debug::valueOf(persistantFileRead)); + qCDebug(octree, "DONE loading Octrees from file... fileRead=%s", debug::valueOf(persistantFileRead)); unsigned long nodeCount = OctreeElement::getNodeCount(); unsigned long internalNodeCount = OctreeElement::getInternalNodeCount(); unsigned long leafNodeCount = OctreeElement::getLeafNodeCount(); - qDebug("Nodes after loading scene %lu nodes %lu internal %lu leaves", nodeCount, internalNodeCount, leafNodeCount); + qCDebug(octree, "Nodes after loading scene %lu nodes %lu internal %lu leaves", nodeCount, internalNodeCount, leafNodeCount); bool wantDebug = false; if (wantDebug) { double usecPerGet = (double)OctreeElement::getGetChildAtIndexTime() / (double)OctreeElement::getGetChildAtIndexCalls(); - qDebug() << "getChildAtIndexCalls=" << OctreeElement::getGetChildAtIndexCalls() + qCDebug(octree) << "getChildAtIndexCalls=" << OctreeElement::getGetChildAtIndexCalls() << " getChildAtIndexTime=" << OctreeElement::getGetChildAtIndexTime() << " perGet=" << usecPerGet; double usecPerSet = (double)OctreeElement::getSetChildAtIndexTime() / (double)OctreeElement::getSetChildAtIndexCalls(); - qDebug() << "setChildAtIndexCalls=" << OctreeElement::getSetChildAtIndexCalls() + qCDebug(octree) << "setChildAtIndexCalls=" << OctreeElement::getSetChildAtIndexCalls() << " setChildAtIndexTime=" << OctreeElement::getSetChildAtIndexTime() << " perSet=" << usecPerSet; } @@ -224,47 +225,47 @@ bool OctreePersistThread::process() { void OctreePersistThread::aboutToFinish() { - qDebug() << "Persist thread about to finish..."; + qCDebug(octree) << "Persist thread about to finish..."; persist(); - qDebug() << "Persist thread done with about to finish..."; + qCDebug(octree) << "Persist thread done with about to finish..."; } void OctreePersistThread::persist() { if (_tree->isDirty()) { _tree->lockForWrite(); { - qDebug() << "pruning Octree before saving..."; + qCDebug(octree) << "pruning Octree before saving..."; _tree->pruneTree(); - qDebug() << "DONE pruning Octree before saving..."; + qCDebug(octree) << "DONE pruning Octree before saving..."; } _tree->unlock(); - qDebug() << "persist operation calling backup..."; + qCDebug(octree) << "persist operation calling backup..."; backup(); // handle backup if requested - qDebug() << "persist operation DONE with backup..."; + qCDebug(octree) << "persist operation DONE with backup..."; // create our "lock" file to indicate we're saving. QString lockFileName = _filename + ".lock"; std::ofstream lockFile(qPrintable(lockFileName), std::ios::out|std::ios::binary); if(lockFile.is_open()) { - qDebug() << "saving Octree lock file created at:" << lockFileName; + qCDebug(octree) << "saving Octree lock file created at:" << lockFileName; _tree->writeToFile(qPrintable(_filename), NULL, _persistAsFileType); time(&_lastPersistTime); _tree->clearDirtyBit(); // tree is clean after saving - qDebug() << "DONE saving Octree to file..."; + qCDebug(octree) << "DONE saving Octree to file..."; lockFile.close(); - qDebug() << "saving Octree lock file closed:" << lockFileName; + qCDebug(octree) << "saving Octree lock file closed:" << lockFileName; remove(qPrintable(lockFileName)); - qDebug() << "saving Octree lock file removed:" << lockFileName; + qCDebug(octree) << "saving Octree lock file removed:" << lockFileName; } } } void OctreePersistThread::restoreFromMostRecentBackup() { - qDebug() << "Restoring from most recent backup..."; + qCDebug(octree) << "Restoring from most recent backup..."; QString mostRecentBackupFileName; QDateTime mostRecentBackupTime; @@ -273,20 +274,20 @@ void OctreePersistThread::restoreFromMostRecentBackup() { // If we found a backup file, restore from that file. if (recentBackup) { - qDebug() << "BEST backup file:" << mostRecentBackupFileName << " last modified:" << mostRecentBackupTime.toString(); + qCDebug(octree) << "BEST backup file:" << mostRecentBackupFileName << " last modified:" << mostRecentBackupTime.toString(); - qDebug() << "Removing old file:" << _filename; + qCDebug(octree) << "Removing old file:" << _filename; remove(qPrintable(_filename)); - qDebug() << "Restoring backup file " << mostRecentBackupFileName << "..."; + qCDebug(octree) << "Restoring backup file " << mostRecentBackupFileName << "..."; bool result = QFile::copy(mostRecentBackupFileName, _filename); if (result) { - qDebug() << "DONE restoring backup file " << mostRecentBackupFileName << "to" << _filename << "..."; + qCDebug(octree) << "DONE restoring backup file " << mostRecentBackupFileName << "to" << _filename << "..."; } else { - qDebug() << "ERROR while restoring backup file " << mostRecentBackupFileName << "to" << _filename << "..."; + qCDebug(octree) << "ERROR while restoring backup file " << mostRecentBackupFileName << "to" << _filename << "..."; } } else { - qDebug() << "NO BEST backup file found."; + qCDebug(octree) << "NO BEST backup file found."; } } @@ -346,7 +347,7 @@ void OctreePersistThread::rollOldBackupVersions(const BackupRule& rule) { if (rule.extensionFormat.contains("%N")) { if (rule.maxBackupVersions > 0) { - qDebug() << "Rolling old backup versions for rule" << rule.name << "..."; + qCDebug(octree) << "Rolling old backup versions for rule" << rule.name << "..."; for(int n = rule.maxBackupVersions - 1; n > 0; n--) { QString backupExtensionN = rule.extensionFormat; QString backupExtensionNplusOne = rule.extensionFormat; @@ -359,18 +360,18 @@ void OctreePersistThread::rollOldBackupVersions(const BackupRule& rule) { QFile backupFileN(backupFilenameN); if (backupFileN.exists()) { - qDebug() << "rolling backup file " << backupFilenameN << "to" << backupFilenameNplusOne << "..."; + qCDebug(octree) << "rolling backup file " << backupFilenameN << "to" << backupFilenameNplusOne << "..."; int result = rename(qPrintable(backupFilenameN), qPrintable(backupFilenameNplusOne)); if (result == 0) { - qDebug() << "DONE rolling backup file " << backupFilenameN << "to" << backupFilenameNplusOne << "..."; + qCDebug(octree) << "DONE rolling backup file " << backupFilenameN << "to" << backupFilenameNplusOne << "..."; } else { - qDebug() << "ERROR in rolling backup file " << backupFilenameN << "to" << backupFilenameNplusOne << "..."; + qCDebug(octree) << "ERROR in rolling backup file " << backupFilenameN << "to" << backupFilenameNplusOne << "..."; } } } - qDebug() << "Done rolling old backup versions..."; + qCDebug(octree) << "Done rolling old backup versions..."; } else { - qDebug() << "Rolling backups for rule" << rule.name << "." + qCDebug(octree) << "Rolling backups for rule" << rule.name << "." << " Max Rolled Backup Versions less than 1 [" << rule.maxBackupVersions << "]." << " No need to roll backups..."; } @@ -379,7 +380,7 @@ void OctreePersistThread::rollOldBackupVersions(const BackupRule& rule) { void OctreePersistThread::backup() { - qDebug() << "backup operation wantBackup:" << _wantBackup; + qCDebug(octree) << "backup operation wantBackup:" << _wantBackup; if (_wantBackup) { quint64 now = usecTimestampNow(); @@ -390,11 +391,11 @@ void OctreePersistThread::backup() { quint64 SECS_TO_USECS = 1000 * 1000; quint64 intervalToBackup = rule.interval * SECS_TO_USECS; - qDebug() << "Checking [" << rule.name << "] - Time since last backup [" << sinceLastBackup << "] " << + qCDebug(octree) << "Checking [" << rule.name << "] - Time since last backup [" << sinceLastBackup << "] " << "compared to backup interval [" << intervalToBackup << "]..."; if (sinceLastBackup > intervalToBackup) { - qDebug() << "Time since last backup [" << sinceLastBackup << "] for rule [" << rule.name + qCDebug(octree) << "Time since last backup [" << sinceLastBackup << "] for rule [" << rule.name << "] exceeds backup interval [" << intervalToBackup << "] doing backup now..."; struct tm* localTime = localtime(&_lastPersistTime); @@ -417,25 +418,25 @@ void OctreePersistThread::backup() { if (rule.maxBackupVersions > 0) { QFile persistFile(_filename); if (persistFile.exists()) { - qDebug() << "backing up persist file " << _filename << "to" << backupFileName << "..."; + qCDebug(octree) << "backing up persist file " << _filename << "to" << backupFileName << "..."; bool result = QFile::copy(_filename, backupFileName); if (result) { - qDebug() << "DONE backing up persist file..."; + qCDebug(octree) << "DONE backing up persist file..."; rule.lastBackup = now; // only record successful backup in this case. } else { - qDebug() << "ERROR in backing up persist file..."; + qCDebug(octree) << "ERROR in backing up persist file..."; } } else { - qDebug() << "persist file " << _filename << " does not exist. " << + qCDebug(octree) << "persist file " << _filename << " does not exist. " << "nothing to backup for this rule ["<< rule.name << "]..."; } } else { - qDebug() << "This backup rule" << rule.name + qCDebug(octree) << "This backup rule" << rule.name << " has Max Rolled Backup Versions less than 1 [" << rule.maxBackupVersions << "]." << " There are no backups to be done..."; } } else { - qDebug() << "Backup not needed for this rule ["<< rule.name << "]..."; + qCDebug(octree) << "Backup not needed for this rule ["<< rule.name << "]..."; } } } diff --git a/libraries/octree/src/OctreeProjectedPolygon.cpp b/libraries/octree/src/OctreeProjectedPolygon.cpp index a7edabb03c..15543378f8 100644 --- a/libraries/octree/src/OctreeProjectedPolygon.cpp +++ b/libraries/octree/src/OctreeProjectedPolygon.cpp @@ -15,6 +15,7 @@ #include "GeometryUtil.h" #include "SharedUtil.h" +#include "OctreeLogging.h" #include "OctreeProjectedPolygon.h" @@ -94,7 +95,7 @@ void BoundingBox::explandToInclude(const BoundingBox& box) { void BoundingBox::printDebugDetails(const char* label) const { - qDebug("%s _set=%s\n corner=%f,%f size=%f,%f\n bounds=[(%f,%f) to (%f,%f)]", + qCDebug(octree, "%s _set=%s\n corner=%f,%f size=%f,%f\n bounds=[(%f,%f) to (%f,%f)]", (label ? label : "BoundingBox"), debug::valueOf(_set), corner.x, corner.y, size.x, size.y, corner.x, corner.y, corner.x+size.x, corner.y+size.y); } @@ -263,12 +264,12 @@ bool OctreeProjectedPolygon::pointInside(const glm::vec2& point, bool* matchesVe } void OctreeProjectedPolygon::printDebugDetails() const { - qDebug("OctreeProjectedPolygon..." + qCDebug(octree, "OctreeProjectedPolygon..." " minX=%f maxX=%f minY=%f maxY=%f", getMinX(), getMaxX(), getMinY(), getMaxY()); - qDebug(" vertex count=%d distance=%f", getVertexCount(), getDistance()); + qCDebug(octree, " vertex count=%d distance=%f", getVertexCount(), getDistance()); for (int i = 0; i < getVertexCount(); i++) { glm::vec2 point = getVertex(i); - qDebug(" vertex[%d] = %f, %f ", i, point.x, point.y); + qCDebug(octree, " vertex[%d] = %f, %f ", i, point.x, point.y); } } diff --git a/libraries/octree/src/OctreeRenderer.cpp b/libraries/octree/src/OctreeRenderer.cpp index 187f916d35..ae40cbfa15 100644 --- a/libraries/octree/src/OctreeRenderer.cpp +++ b/libraries/octree/src/OctreeRenderer.cpp @@ -15,6 +15,7 @@ #include #include #include +#include "OctreeLogging.h" #include "OctreeRenderer.h" OctreeRenderer::OctreeRenderer() : @@ -49,11 +50,11 @@ void OctreeRenderer::processDatagram(const QByteArray& dataByteArray, const Shar bool extraDebugging = false; if (extraDebugging) { - qDebug() << "OctreeRenderer::processDatagram()"; + qCDebug(octree) << "OctreeRenderer::processDatagram()"; } if (!_tree) { - qDebug() << "OctreeRenderer::processDatagram() called before init, calling init()..."; + qCDebug(octree) << "OctreeRenderer::processDatagram() called before init, calling init()..."; this->init(); } @@ -94,7 +95,7 @@ void OctreeRenderer::processDatagram(const QByteArray& dataByteArray, const Shar unsigned int dataBytes = packetLength - (numBytesPacketHeader + OCTREE_PACKET_EXTRA_HEADERS_SIZE); if (extraDebugging) { - qDebug("OctreeRenderer::processDatagram() ... Got Packet Section" + qCDebug(octree, "OctreeRenderer::processDatagram() ... Got Packet Section" " color:%s compressed:%s sequence: %u flight:%d usec size:%u data:%u", debug::valueOf(packetIsColored), debug::valueOf(packetIsCompressed), sequence, flightTime, packetLength, dataBytes); @@ -123,7 +124,7 @@ void OctreeRenderer::processDatagram(const QByteArray& dataByteArray, const Shar OctreePacketData packetData(packetIsCompressed); packetData.loadFinalizedContent(dataAt, sectionLength); if (extraDebugging) { - qDebug("OctreeRenderer::processDatagram() ... Got Packet Section" + qCDebug(octree, "OctreeRenderer::processDatagram() ... Got Packet Section" " color:%s compressed:%s sequence: %u flight:%d usec size:%u data:%u" " subsection:%d sectionLength:%d uncompressed:%d", debug::valueOf(packetIsColored), debug::valueOf(packetIsCompressed), @@ -131,11 +132,11 @@ void OctreeRenderer::processDatagram(const QByteArray& dataByteArray, const Shar packetData.getUncompressedSize()); } if (extraDebugging) { - qDebug() << "OctreeRenderer::processDatagram() ******* START _tree->readBitstreamToTree()..."; + qCDebug(octree) << "OctreeRenderer::processDatagram() ******* START _tree->readBitstreamToTree()..."; } _tree->readBitstreamToTree(packetData.getUncompressedData(), packetData.getUncompressedSize(), args); if (extraDebugging) { - qDebug() << "OctreeRenderer::processDatagram() ******* END _tree->readBitstreamToTree()..."; + qCDebug(octree) << "OctreeRenderer::processDatagram() ******* END _tree->readBitstreamToTree()..."; } _tree->unlock(); diff --git a/libraries/octree/src/OctreeSceneStats.cpp b/libraries/octree/src/OctreeSceneStats.cpp index 4b21890a22..d2b1ed91d1 100644 --- a/libraries/octree/src/OctreeSceneStats.cpp +++ b/libraries/octree/src/OctreeSceneStats.cpp @@ -19,6 +19,7 @@ #include "OctreePacketData.h" #include "OctreeElement.h" +#include "OctreeLogging.h" #include "OctreeSceneStats.h" @@ -630,51 +631,51 @@ int OctreeSceneStats::unpackFromMessage(const unsigned char* sourceBuffer, int a void OctreeSceneStats::printDebugDetails() { - qDebug() << "\n------------------------------"; - qDebug() << "OctreeSceneStats:"; - qDebug() << "start: " << _start; - qDebug() << "end: " << _end; - qDebug() << "elapsed: " << _elapsed; - qDebug() << "encoding: " << _totalEncodeTime; - qDebug(); - qDebug() << "full scene: " << debug::valueOf(_isFullScene); - qDebug() << "moving: " << debug::valueOf(_isMoving); - qDebug(); - qDebug() << "packets: " << _packets; - qDebug() << "bytes: " << _bytes; - qDebug(); - qDebug() << "total elements: " << _totalElements; - qDebug() << "internal: " << _totalInternal; - qDebug() << "leaves: " << _totalLeaves; - qDebug() << "traversed: " << _traversed; - qDebug() << "internal: " << _internal; - qDebug() << "leaves: " << _leaves; - qDebug() << "skipped distance: " << _skippedDistance; - qDebug() << "internal: " << _internalSkippedDistance; - qDebug() << "leaves: " << _leavesSkippedDistance; - qDebug() << "skipped out of view: " << _skippedOutOfView; - qDebug() << "internal: " << _internalSkippedOutOfView; - qDebug() << "leaves: " << _leavesSkippedOutOfView; - qDebug() << "skipped was in view: " << _skippedWasInView; - qDebug() << "internal: " << _internalSkippedWasInView; - qDebug() << "leaves: " << _leavesSkippedWasInView; - qDebug() << "skipped no change: " << _skippedNoChange; - qDebug() << "internal: " << _internalSkippedNoChange; - qDebug() << "leaves: " << _leavesSkippedNoChange; - qDebug() << "skipped occluded: " << _skippedOccluded; - qDebug() << "internal: " << _internalSkippedOccluded; - qDebug() << "leaves: " << _leavesSkippedOccluded; - qDebug(); - qDebug() << "color sent: " << _colorSent; - qDebug() << "internal: " << _internalColorSent; - qDebug() << "leaves: " << _leavesColorSent; - qDebug() << "Didn't Fit: " << _didntFit; - qDebug() << "internal: " << _internalDidntFit; - qDebug() << "leaves: " << _leavesDidntFit; - qDebug() << "color bits: " << _colorBitsWritten; - qDebug() << "exists bits: " << _existsBitsWritten; - qDebug() << "in packet bit: " << _existsInPacketBitsWritten; - qDebug() << "trees removed: " << _treesRemoved; + qCDebug(octree) << "\n------------------------------"; + qCDebug(octree) << "OctreeSceneStats:"; + qCDebug(octree) << "start: " << _start; + qCDebug(octree) << "end: " << _end; + qCDebug(octree) << "elapsed: " << _elapsed; + qCDebug(octree) << "encoding: " << _totalEncodeTime; + qCDebug(octree); + qCDebug(octree) << "full scene: " << debug::valueOf(_isFullScene); + qCDebug(octree) << "moving: " << debug::valueOf(_isMoving); + qCDebug(octree); + qCDebug(octree) << "packets: " << _packets; + qCDebug(octree) << "bytes: " << _bytes; + qCDebug(octree); + qCDebug(octree) << "total elements: " << _totalElements; + qCDebug(octree) << "internal: " << _totalInternal; + qCDebug(octree) << "leaves: " << _totalLeaves; + qCDebug(octree) << "traversed: " << _traversed; + qCDebug(octree) << "internal: " << _internal; + qCDebug(octree) << "leaves: " << _leaves; + qCDebug(octree) << "skipped distance: " << _skippedDistance; + qCDebug(octree) << "internal: " << _internalSkippedDistance; + qCDebug(octree) << "leaves: " << _leavesSkippedDistance; + qCDebug(octree) << "skipped out of view: " << _skippedOutOfView; + qCDebug(octree) << "internal: " << _internalSkippedOutOfView; + qCDebug(octree) << "leaves: " << _leavesSkippedOutOfView; + qCDebug(octree) << "skipped was in view: " << _skippedWasInView; + qCDebug(octree) << "internal: " << _internalSkippedWasInView; + qCDebug(octree) << "leaves: " << _leavesSkippedWasInView; + qCDebug(octree) << "skipped no change: " << _skippedNoChange; + qCDebug(octree) << "internal: " << _internalSkippedNoChange; + qCDebug(octree) << "leaves: " << _leavesSkippedNoChange; + qCDebug(octree) << "skipped occluded: " << _skippedOccluded; + qCDebug(octree) << "internal: " << _internalSkippedOccluded; + qCDebug(octree) << "leaves: " << _leavesSkippedOccluded; + qCDebug(octree); + qCDebug(octree) << "color sent: " << _colorSent; + qCDebug(octree) << "internal: " << _internalColorSent; + qCDebug(octree) << "leaves: " << _leavesColorSent; + qCDebug(octree) << "Didn't Fit: " << _didntFit; + qCDebug(octree) << "internal: " << _internalDidntFit; + qCDebug(octree) << "leaves: " << _leavesDidntFit; + qCDebug(octree) << "color bits: " << _colorBitsWritten; + qCDebug(octree) << "exists bits: " << _existsBitsWritten; + qCDebug(octree) << "in packet bit: " << _existsInPacketBitsWritten; + qCDebug(octree) << "trees removed: " << _treesRemoved; } OctreeSceneStats::ItemInfo OctreeSceneStats::_ITEMS[] = { @@ -845,10 +846,10 @@ void OctreeSceneStats::trackIncomingOctreePacket(const QByteArray& packet, qint64 flightTime = arrivedAt - sentAt + nodeClockSkewUsec; if (wantExtraDebugging) { - qDebug() << "sentAt:" << sentAt << " usecs"; - qDebug() << "arrivedAt:" << arrivedAt << " usecs"; - qDebug() << "nodeClockSkewUsec:" << nodeClockSkewUsec << " usecs"; - qDebug() << "flightTime:" << flightTime << " usecs"; + qCDebug(octree) << "sentAt:" << sentAt << " usecs"; + qCDebug(octree) << "arrivedAt:" << arrivedAt << " usecs"; + qCDebug(octree) << "nodeClockSkewUsec:" << nodeClockSkewUsec << " usecs"; + qCDebug(octree) << "flightTime:" << flightTime << " usecs"; } // Guard against possible corrupted packets... with bad timestamps @@ -859,7 +860,7 @@ void OctreeSceneStats::trackIncomingOctreePacket(const QByteArray& packet, = LogHandler::getInstance().addRepeatedMessageRegex( "ignoring unreasonable packet... flightTime: -?\\d+ nodeClockSkewUsec: -?\\d+ usecs"); - qDebug() << "ignoring unreasonable packet... flightTime:" << flightTime + qCDebug(octree) << "ignoring unreasonable packet... flightTime:" << flightTime << "nodeClockSkewUsec:" << nodeClockSkewUsec << "usecs";; return; // ignore any packets that are unreasonable } diff --git a/libraries/octree/src/Plane.cpp b/libraries/octree/src/Plane.cpp index d9e5633233..a6e3a8f30d 100644 --- a/libraries/octree/src/Plane.cpp +++ b/libraries/octree/src/Plane.cpp @@ -13,6 +13,8 @@ // #include "Plane.h" +#include "OctreeLogging.h" + #include @@ -63,6 +65,6 @@ float Plane::distance(const glm::vec3 &point) const { } void Plane::print() const { - qDebug("Plane - point (x=%f y=%f z=%f) normal (x=%f y=%f z=%f) d=%f", + qCDebug(octree, "Plane - point (x=%f y=%f z=%f) normal (x=%f y=%f z=%f) d=%f", _point.x, _point.y, _point.z, _normal.x, _normal.y, _normal.z, _dCoefficient); } diff --git a/libraries/octree/src/ViewFrustum.cpp b/libraries/octree/src/ViewFrustum.cpp index 594dd8325e..9570bcdd03 100644 --- a/libraries/octree/src/ViewFrustum.cpp +++ b/libraries/octree/src/ViewFrustum.cpp @@ -21,6 +21,7 @@ #include "GLMHelpers.h" #include "SharedUtil.h" #include "ViewFrustum.h" +#include "OctreeLogging.h" #include "OctreeConstants.h" using namespace std; @@ -432,43 +433,43 @@ bool ViewFrustum::matches(const ViewFrustum& compareTo, bool debug) const { testMatches(compareTo._eyeOffsetOrientation, _eyeOffsetOrientation); if (!result && debug) { - qDebug("ViewFrustum::matches()... result=%s", debug::valueOf(result)); - qDebug("%s -- compareTo._position=%f,%f,%f _position=%f,%f,%f", + qCDebug(octree, "ViewFrustum::matches()... result=%s", debug::valueOf(result)); + qCDebug(octree, "%s -- compareTo._position=%f,%f,%f _position=%f,%f,%f", (testMatches(compareTo._position,_position) ? "MATCHES " : "NO MATCH"), compareTo._position.x, compareTo._position.y, compareTo._position.z, _position.x, _position.y, _position.z ); - qDebug("%s -- compareTo._direction=%f,%f,%f _direction=%f,%f,%f", + qCDebug(octree, "%s -- compareTo._direction=%f,%f,%f _direction=%f,%f,%f", (testMatches(compareTo._direction, _direction) ? "MATCHES " : "NO MATCH"), compareTo._direction.x, compareTo._direction.y, compareTo._direction.z, _direction.x, _direction.y, _direction.z ); - qDebug("%s -- compareTo._up=%f,%f,%f _up=%f,%f,%f", + qCDebug(octree, "%s -- compareTo._up=%f,%f,%f _up=%f,%f,%f", (testMatches(compareTo._up, _up) ? "MATCHES " : "NO MATCH"), compareTo._up.x, compareTo._up.y, compareTo._up.z, _up.x, _up.y, _up.z ); - qDebug("%s -- compareTo._right=%f,%f,%f _right=%f,%f,%f", + qCDebug(octree, "%s -- compareTo._right=%f,%f,%f _right=%f,%f,%f", (testMatches(compareTo._right, _right) ? "MATCHES " : "NO MATCH"), compareTo._right.x, compareTo._right.y, compareTo._right.z, _right.x, _right.y, _right.z ); - qDebug("%s -- compareTo._fieldOfView=%f _fieldOfView=%f", + qCDebug(octree, "%s -- compareTo._fieldOfView=%f _fieldOfView=%f", (testMatches(compareTo._fieldOfView, _fieldOfView) ? "MATCHES " : "NO MATCH"), compareTo._fieldOfView, _fieldOfView); - qDebug("%s -- compareTo._aspectRatio=%f _aspectRatio=%f", + qCDebug(octree, "%s -- compareTo._aspectRatio=%f _aspectRatio=%f", (testMatches(compareTo._aspectRatio, _aspectRatio) ? "MATCHES " : "NO MATCH"), compareTo._aspectRatio, _aspectRatio); - qDebug("%s -- compareTo._nearClip=%f _nearClip=%f", + qCDebug(octree, "%s -- compareTo._nearClip=%f _nearClip=%f", (testMatches(compareTo._nearClip, _nearClip) ? "MATCHES " : "NO MATCH"), compareTo._nearClip, _nearClip); - qDebug("%s -- compareTo._farClip=%f _farClip=%f", + qCDebug(octree, "%s -- compareTo._farClip=%f _farClip=%f", (testMatches(compareTo._farClip, _farClip) ? "MATCHES " : "NO MATCH"), compareTo._farClip, _farClip); - qDebug("%s -- compareTo._focalLength=%f _focalLength=%f", + qCDebug(octree, "%s -- compareTo._focalLength=%f _focalLength=%f", (testMatches(compareTo._focalLength, _focalLength) ? "MATCHES " : "NO MATCH"), compareTo._focalLength, _focalLength); - qDebug("%s -- compareTo._eyeOffsetPosition=%f,%f,%f _eyeOffsetPosition=%f,%f,%f", + qCDebug(octree, "%s -- compareTo._eyeOffsetPosition=%f,%f,%f _eyeOffsetPosition=%f,%f,%f", (testMatches(compareTo._eyeOffsetPosition, _eyeOffsetPosition) ? "MATCHES " : "NO MATCH"), compareTo._eyeOffsetPosition.x, compareTo._eyeOffsetPosition.y, compareTo._eyeOffsetPosition.z, _eyeOffsetPosition.x, _eyeOffsetPosition.y, _eyeOffsetPosition.z); - qDebug("%s -- compareTo._eyeOffsetOrientation=%f,%f,%f,%f _eyeOffsetOrientation=%f,%f,%f,%f", + qCDebug(octree, "%s -- compareTo._eyeOffsetOrientation=%f,%f,%f,%f _eyeOffsetOrientation=%f,%f,%f,%f", (testMatches(compareTo._eyeOffsetOrientation, _eyeOffsetOrientation) ? "MATCHES " : "NO MATCH"), compareTo._eyeOffsetOrientation.x, compareTo._eyeOffsetOrientation.y, compareTo._eyeOffsetOrientation.z, compareTo._eyeOffsetOrientation.w, @@ -514,46 +515,46 @@ bool ViewFrustum::isVerySimilar(const ViewFrustum& compareTo, bool debug) const if (!result && debug) { - qDebug("ViewFrustum::isVerySimilar()... result=%s\n", debug::valueOf(result)); - qDebug("%s -- compareTo._position=%f,%f,%f _position=%f,%f,%f", + qCDebug(octree, "ViewFrustum::isVerySimilar()... result=%s\n", debug::valueOf(result)); + qCDebug(octree, "%s -- compareTo._position=%f,%f,%f _position=%f,%f,%f", (testMatches(compareTo._position,_position, POSITION_SIMILAR_ENOUGH) ? "IS SIMILAR ENOUGH " : "IS NOT SIMILAR ENOUGH"), compareTo._position.x, compareTo._position.y, compareTo._position.z, _position.x, _position.y, _position.z ); - qDebug("%s -- positionDistance=%f", + qCDebug(octree, "%s -- positionDistance=%f", (testMatches(0,positionDistance, POSITION_SIMILAR_ENOUGH) ? "IS SIMILAR ENOUGH " : "IS NOT SIMILAR ENOUGH"), positionDistance); - qDebug("%s -- angleOrientation=%f", + qCDebug(octree, "%s -- angleOrientation=%f", (testMatches(0, angleOrientation, ORIENTATION_SIMILAR_ENOUGH) ? "IS SIMILAR ENOUGH " : "IS NOT SIMILAR ENOUGH"), angleOrientation); - qDebug("%s -- compareTo._fieldOfView=%f _fieldOfView=%f", + qCDebug(octree, "%s -- compareTo._fieldOfView=%f _fieldOfView=%f", (testMatches(compareTo._fieldOfView, _fieldOfView) ? "MATCHES " : "NO MATCH"), compareTo._fieldOfView, _fieldOfView); - qDebug("%s -- compareTo._aspectRatio=%f _aspectRatio=%f", + qCDebug(octree, "%s -- compareTo._aspectRatio=%f _aspectRatio=%f", (testMatches(compareTo._aspectRatio, _aspectRatio) ? "MATCHES " : "NO MATCH"), compareTo._aspectRatio, _aspectRatio); - qDebug("%s -- compareTo._nearClip=%f _nearClip=%f", + qCDebug(octree, "%s -- compareTo._nearClip=%f _nearClip=%f", (testMatches(compareTo._nearClip, _nearClip) ? "MATCHES " : "NO MATCH"), compareTo._nearClip, _nearClip); - qDebug("%s -- compareTo._farClip=%f _farClip=%f", + qCDebug(octree, "%s -- compareTo._farClip=%f _farClip=%f", (testMatches(compareTo._farClip, _farClip) ? "MATCHES " : "NO MATCH"), compareTo._farClip, _farClip); - qDebug("%s -- compareTo._focalLength=%f _focalLength=%f", + qCDebug(octree, "%s -- compareTo._focalLength=%f _focalLength=%f", (testMatches(compareTo._focalLength, _focalLength) ? "MATCHES " : "NO MATCH"), compareTo._focalLength, _focalLength); - qDebug("%s -- compareTo._eyeOffsetPosition=%f,%f,%f _eyeOffsetPosition=%f,%f,%f", + qCDebug(octree, "%s -- compareTo._eyeOffsetPosition=%f,%f,%f _eyeOffsetPosition=%f,%f,%f", (testMatches(compareTo._eyeOffsetPosition, _eyeOffsetPosition, POSITION_SIMILAR_ENOUGH) ? "IS SIMILAR ENOUGH " : "IS NOT SIMILAR ENOUGH"), compareTo._eyeOffsetPosition.x, compareTo._eyeOffsetPosition.y, compareTo._eyeOffsetPosition.z, _eyeOffsetPosition.x, _eyeOffsetPosition.y, _eyeOffsetPosition.z); - qDebug("%s -- eyeOffsetpositionDistance=%f", + qCDebug(octree, "%s -- eyeOffsetpositionDistance=%f", (testMatches(0,eyeOffsetpositionDistance, EYEOFFSET_POSITION_SIMILAR_ENOUGH) ? "IS SIMILAR ENOUGH " : "IS NOT SIMILAR ENOUGH"), eyeOffsetpositionDistance); - qDebug("%s -- angleEyeOffsetOrientation=%f", + qCDebug(octree, "%s -- angleEyeOffsetOrientation=%f", (testMatches(0, angleEyeOffsetOrientation, ORIENTATION_SIMILAR_ENOUGH) ? "IS SIMILAR ENOUGH " : "IS NOT SIMILAR ENOUGH"), angleEyeOffsetOrientation); } @@ -631,19 +632,19 @@ void ViewFrustum::computeOffAxisFrustum(float& left, float& right, float& bottom } void ViewFrustum::printDebugDetails() const { - qDebug("ViewFrustum::printDebugDetails()..."); - qDebug("_position=%f,%f,%f", _position.x, _position.y, _position.z ); - qDebug("_direction=%f,%f,%f", _direction.x, _direction.y, _direction.z ); - qDebug("_up=%f,%f,%f", _up.x, _up.y, _up.z ); - qDebug("_right=%f,%f,%f", _right.x, _right.y, _right.z ); - qDebug("_fieldOfView=%f", _fieldOfView); - qDebug("_aspectRatio=%f", _aspectRatio); - qDebug("_keyHoleRadius=%f", _keyholeRadius); - qDebug("_nearClip=%f", _nearClip); - qDebug("_farClip=%f", _farClip); - qDebug("_focalLength=%f", _focalLength); - qDebug("_eyeOffsetPosition=%f,%f,%f", _eyeOffsetPosition.x, _eyeOffsetPosition.y, _eyeOffsetPosition.z ); - qDebug("_eyeOffsetOrientation=%f,%f,%f,%f", _eyeOffsetOrientation.x, _eyeOffsetOrientation.y, _eyeOffsetOrientation.z, + qCDebug(octree, "ViewFrustum::printDebugDetails()..."); + qCDebug(octree, "_position=%f,%f,%f", _position.x, _position.y, _position.z ); + qCDebug(octree, "_direction=%f,%f,%f", _direction.x, _direction.y, _direction.z ); + qCDebug(octree, "_up=%f,%f,%f", _up.x, _up.y, _up.z ); + qCDebug(octree, "_right=%f,%f,%f", _right.x, _right.y, _right.z ); + qCDebug(octree, "_fieldOfView=%f", _fieldOfView); + qCDebug(octree, "_aspectRatio=%f", _aspectRatio); + qCDebug(octree, "_keyHoleRadius=%f", _keyholeRadius); + qCDebug(octree, "_nearClip=%f", _nearClip); + qCDebug(octree, "_farClip=%f", _farClip); + qCDebug(octree, "_focalLength=%f", _focalLength); + qCDebug(octree, "_eyeOffsetPosition=%f,%f,%f", _eyeOffsetPosition.x, _eyeOffsetPosition.y, _eyeOffsetPosition.z ); + qCDebug(octree, "_eyeOffsetOrientation=%f,%f,%f,%f", _eyeOffsetOrientation.x, _eyeOffsetOrientation.y, _eyeOffsetOrientation.z, _eyeOffsetOrientation.w ); } diff --git a/libraries/physics/src/EntityMotionState.cpp b/libraries/physics/src/EntityMotionState.cpp index 35eb006655..d84daa6b42 100644 --- a/libraries/physics/src/EntityMotionState.cpp +++ b/libraries/physics/src/EntityMotionState.cpp @@ -16,6 +16,7 @@ #include "EntityMotionState.h" #include "PhysicsEngine.h" #include "PhysicsHelpers.h" +#include "PhysicsLogging.h" QSet* _outgoingEntityList; @@ -108,10 +109,10 @@ void EntityMotionState::setWorldTransform(const btTransform& worldTrans) { #ifdef WANT_DEBUG quint64 now = usecTimestampNow(); - qDebug() << "EntityMotionState::setWorldTransform()... changed entity:" << _entity->getEntityItemID(); - qDebug() << " last edited:" << _entity->getLastEdited() << formatUsecTime(now - _entity->getLastEdited()) << "ago"; - qDebug() << " last simulated:" << _entity->getLastSimulated() << formatUsecTime(now - _entity->getLastSimulated()) << "ago"; - qDebug() << " last updated:" << _entity->getLastUpdated() << formatUsecTime(now - _entity->getLastUpdated()) << "ago"; + qCDebug(physics) << "EntityMotionState::setWorldTransform()... changed entity:" << _entity->getEntityItemID(); + qCDebug(physics) << " last edited:" << _entity->getLastEdited() << formatUsecTime(now - _entity->getLastEdited()) << "ago"; + qCDebug(physics) << " last simulated:" << _entity->getLastSimulated() << formatUsecTime(now - _entity->getLastSimulated()) << "ago"; + qCDebug(physics) << " last updated:" << _entity->getLastUpdated() << formatUsecTime(now - _entity->getLastUpdated()) << "ago"; #endif } @@ -238,9 +239,9 @@ void EntityMotionState::sendUpdate(OctreeEditPacketSender* packetSender, uint32_ #ifdef WANT_DEBUG quint64 now = usecTimestampNow(); - qDebug() << "EntityMotionState::sendUpdate()"; - qDebug() << " EntityItemId:" << _entity->getEntityItemID() << "---------------------------------------------"; - qDebug() << " lastSimulated:" << debugTime(lastSimulated, now); + qCDebug(physics) << "EntityMotionState::sendUpdate()"; + qCDebug(physics) << " EntityItemId:" << _entity->getEntityItemID() << "---------------------------------------------"; + qCDebug(physics) << " lastSimulated:" << debugTime(lastSimulated, now); #endif //def WANT_DEBUG } else { @@ -251,12 +252,12 @@ void EntityMotionState::sendUpdate(OctreeEditPacketSender* packetSender, uint32_ EntityItemID id(_entity->getID()); EntityEditPacketSender* entityPacketSender = static_cast(packetSender); #ifdef WANT_DEBUG - qDebug() << "EntityMotionState::sendUpdate()... calling queueEditEntityMessage()..."; + qCDebug(physics) << "EntityMotionState::sendUpdate()... calling queueEditEntityMessage()..."; #endif entityPacketSender->queueEditEntityMessage(PacketTypeEntityAddOrEdit, id, properties); } else { #ifdef WANT_DEBUG - qDebug() << "EntityMotionState::sendUpdate()... NOT sending update as requested."; + qCDebug(physics) << "EntityMotionState::sendUpdate()... NOT sending update as requested."; #endif } diff --git a/libraries/physics/src/ObjectMotionState.cpp b/libraries/physics/src/ObjectMotionState.cpp index 21dead5b0b..c9f416cc37 100644 --- a/libraries/physics/src/ObjectMotionState.cpp +++ b/libraries/physics/src/ObjectMotionState.cpp @@ -15,6 +15,7 @@ #include "ObjectMotionState.h" #include "PhysicsEngine.h" #include "PhysicsHelpers.h" +#include "PhysicsLogging.h" const float DEFAULT_FRICTION = 0.5f; const float MAX_FRICTION = 10.0f; @@ -161,11 +162,11 @@ bool ObjectMotionState::shouldSendUpdate(uint32_t simulationFrame) { if (dx2 > MAX_POSITION_ERROR_SQUARED) { #ifdef WANT_DEBUG - qDebug() << ".... (dx2 > MAX_POSITION_ERROR_SQUARED) ...."; - qDebug() << "wasPosition:" << wasPosition; - qDebug() << "bullet position:" << position; - qDebug() << "_sentPosition:" << _sentPosition; - qDebug() << "dx2:" << dx2; + qCDebug(physics) << ".... (dx2 > MAX_POSITION_ERROR_SQUARED) ...."; + qCDebug(physics) << "wasPosition:" << wasPosition; + qCDebug(physics) << "bullet position:" << position; + qCDebug(physics) << "_sentPosition:" << _sentPosition; + qCDebug(physics) << "dx2:" << dx2; #endif return true; @@ -187,17 +188,17 @@ bool ObjectMotionState::shouldSendUpdate(uint32_t simulationFrame) { #ifdef WANT_DEBUG if ((fabsf(glm::dot(actualRotation, _sentRotation)) < MIN_ROTATION_DOT)) { - qDebug() << ".... ((fabsf(glm::dot(actualRotation, _sentRotation)) < MIN_ROTATION_DOT)) ...."; + qCDebug(physics) << ".... ((fabsf(glm::dot(actualRotation, _sentRotation)) < MIN_ROTATION_DOT)) ...."; - qDebug() << "wasAngularVelocity:" << wasAngularVelocity; - qDebug() << "_sentAngularVelocity:" << _sentAngularVelocity; + qCDebug(physics) << "wasAngularVelocity:" << wasAngularVelocity; + qCDebug(physics) << "_sentAngularVelocity:" << _sentAngularVelocity; - qDebug() << "length wasAngularVelocity:" << glm::length(wasAngularVelocity); - qDebug() << "length _sentAngularVelocity:" << glm::length(_sentAngularVelocity); + qCDebug(physics) << "length wasAngularVelocity:" << glm::length(wasAngularVelocity); + qCDebug(physics) << "length _sentAngularVelocity:" << glm::length(_sentAngularVelocity); - qDebug() << "wasRotation:" << wasRotation; - qDebug() << "bullet actualRotation:" << actualRotation; - qDebug() << "_sentRotation:" << _sentRotation; + qCDebug(physics) << "wasRotation:" << wasRotation; + qCDebug(physics) << "bullet actualRotation:" << actualRotation; + qCDebug(physics) << "_sentRotation:" << _sentRotation; } #endif diff --git a/libraries/physics/src/PhysicsEngine.cpp b/libraries/physics/src/PhysicsEngine.cpp index 67e4e0616f..97f1a0ddef 100644 --- a/libraries/physics/src/PhysicsEngine.cpp +++ b/libraries/physics/src/PhysicsEngine.cpp @@ -88,7 +88,7 @@ void PhysicsEngine::addEntityInternal(EntityItem* entity) { motionState->setKinematic(true, _numSubsteps); _nonPhysicalKinematicObjects.insert(motionState); // We failed to add the entity to the simulation. Probably because we couldn't create a shape for it. - //qDebug() << "failed to add entity " << entity->getEntityItemID() << " to physics engine"; + //qCDebug(physics) << "failed to add entity " << entity->getEntityItemID() << " to physics engine"; } } } diff --git a/libraries/physics/src/PhysicsLogging.cpp b/libraries/physics/src/PhysicsLogging.cpp new file mode 100644 index 0000000000..ddef4557fe --- /dev/null +++ b/libraries/physics/src/PhysicsLogging.cpp @@ -0,0 +1,14 @@ +// +// PhysicsLogging.cpp +// libraries/physics/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "PhysicsLogging.h" + +Q_LOGGING_CATEGORY(physics, "hifi.physics") diff --git a/libraries/physics/src/PhysicsLogging.h b/libraries/physics/src/PhysicsLogging.h new file mode 100644 index 0000000000..2a3969ecc0 --- /dev/null +++ b/libraries/physics/src/PhysicsLogging.h @@ -0,0 +1,19 @@ +// +// PhysicsLogging.h +// libraries/physics/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_PhysicsLogging_h +#define hifi_PhysicsLogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(physics) + +#endif // hifi_PhysicsLogging_h diff --git a/libraries/physics/src/ShapeManager.cpp b/libraries/physics/src/ShapeManager.cpp index 2c30887e3e..bed7b473da 100644 --- a/libraries/physics/src/ShapeManager.cpp +++ b/libraries/physics/src/ShapeManager.cpp @@ -37,7 +37,7 @@ btCollisionShape* ShapeManager::getShape(const ShapeInfo& info) { const float MIN_SHAPE_DIAGONAL_SQUARED = 3.0e-4f; // 1 cm cube const float MAX_SHAPE_DIAGONAL_SQUARED = 3.0e6f; // 1000 m cube if (diagonal < MIN_SHAPE_DIAGONAL_SQUARED || diagonal > MAX_SHAPE_DIAGONAL_SQUARED) { - // qDebug() << "ShapeManager::getShape -- not making shape due to size" << diagonal; + // qCDebug(physics) << "ShapeManager::getShape -- not making shape due to size" << diagonal; return NULL; } DoubleHashKey key = info.getHash(); diff --git a/libraries/render-utils/src/GeometryCache.cpp b/libraries/render-utils/src/GeometryCache.cpp index 98843cc87f..051cbb0e17 100644 --- a/libraries/render-utils/src/GeometryCache.cpp +++ b/libraries/render-utils/src/GeometryCache.cpp @@ -25,6 +25,7 @@ #include #include "TextureCache.h" +#include "RenderUtilsLogging.h" #include "GeometryCache.h" //#define WANT_DEBUG @@ -40,10 +41,10 @@ GeometryCache::GeometryCache() : GeometryCache::~GeometryCache() { #ifdef WANT_DEBUG - qDebug() << "GeometryCache::~GeometryCache()... "; - qDebug() << " _registeredLine3DVBOs.size():" << _registeredLine3DVBOs.size(); - qDebug() << " _line3DVBOs.size():" << _line3DVBOs.size(); - qDebug() << " BatchItemDetails... population:" << GeometryCache::BatchItemDetails::population; + qCDebug(renderutils) << "GeometryCache::~GeometryCache()... "; + qCDebug(renderutils) << " _registeredLine3DVBOs.size():" << _registeredLine3DVBOs.size(); + qCDebug(renderutils) << " _line3DVBOs.size():" << _line3DVBOs.size(); + qCDebug(renderutils) << " BatchItemDetails... population:" << GeometryCache::BatchItemDetails::population; #endif //def WANT_DEBUG } @@ -70,7 +71,7 @@ void GeometryCache::renderSphere(float radius, int slices, int stacks, const glm if (registered && _registeredSphereVertices.contains(id)) { _registeredSphereVertices[id].clear(); #ifdef WANT_DEBUG - qDebug() << "renderSphere()... RELEASING REGISTERED VERTICES BUFFER"; + qCDebug(renderutils) << "renderSphere()... RELEASING REGISTERED VERTICES BUFFER"; #endif } @@ -114,17 +115,17 @@ void GeometryCache::renderSphere(float radius, int slices, int stacks, const glm delete[] vertexData; #ifdef WANT_DEBUG - qDebug() << "GeometryCache::renderSphere()... --- CREATING VERTICES BUFFER"; - qDebug() << " radius:" << radius; - qDebug() << " slices:" << slices; - qDebug() << " stacks:" << stacks; + qCDebug(renderutils) << "GeometryCache::renderSphere()... --- CREATING VERTICES BUFFER"; + qCDebug(renderutils) << " radius:" << radius; + qCDebug(renderutils) << " slices:" << slices; + qCDebug(renderutils) << " stacks:" << stacks; - qDebug() << " _sphereVertices.size():" << _sphereVertices.size(); + qCDebug(renderutils) << " _sphereVertices.size():" << _sphereVertices.size(); #endif } #ifdef WANT_DEBUG else if (registered) { - qDebug() << "renderSphere()... REUSING PREVIOUSLY REGISTERED VERTICES BUFFER"; + qCDebug(renderutils) << "renderSphere()... REUSING PREVIOUSLY REGISTERED VERTICES BUFFER"; } #endif @@ -134,7 +135,7 @@ void GeometryCache::renderSphere(float radius, int slices, int stacks, const glm if (registered && _registeredSphereIndices.contains(id)) { _registeredSphereIndices[id].clear(); #ifdef WANT_DEBUG - qDebug() << "renderSphere()... RELEASING REGISTERED INDICES BUFFER"; + qCDebug(renderutils) << "renderSphere()... RELEASING REGISTERED INDICES BUFFER"; #endif } @@ -199,18 +200,18 @@ void GeometryCache::renderSphere(float radius, int slices, int stacks, const glm delete[] indexData; #ifdef WANT_DEBUG - qDebug() << "GeometryCache::renderSphere()... --- CREATING INDICES BUFFER"; - qDebug() << " radius:" << radius; - qDebug() << " slices:" << slices; - qDebug() << " stacks:" << stacks; - qDebug() << "indexCount:" << indexCount; - qDebug() << " indices:" << indices; - qDebug() << " _sphereIndices.size():" << _sphereIndices.size(); + qCDebug(renderutils) << "GeometryCache::renderSphere()... --- CREATING INDICES BUFFER"; + qCDebug(renderutils) << " radius:" << radius; + qCDebug(renderutils) << " slices:" << slices; + qCDebug(renderutils) << " stacks:" << stacks; + qCDebug(renderutils) << "indexCount:" << indexCount; + qCDebug(renderutils) << " indices:" << indices; + qCDebug(renderutils) << " _sphereIndices.size():" << _sphereIndices.size(); #endif } #ifdef WANT_DEBUG else if (registered) { - qDebug() << "renderSphere()... REUSING PREVIOUSLY REGISTERED INDICES BUFFER"; + qCDebug(renderutils) << "renderSphere()... REUSING PREVIOUSLY REGISTERED INDICES BUFFER"; } #endif @@ -220,7 +221,7 @@ void GeometryCache::renderSphere(float radius, int slices, int stacks, const glm if (registered && _registeredSphereColors.contains(id)) { _registeredSphereColors[id].clear(); #ifdef WANT_DEBUG - qDebug() << "renderSphere()... RELEASING REGISTERED COLORS BUFFER"; + qCDebug(renderutils) << "renderSphere()... RELEASING REGISTERED COLORS BUFFER"; #endif } @@ -248,17 +249,17 @@ void GeometryCache::renderSphere(float radius, int slices, int stacks, const glm delete[] colorData; #ifdef WANT_DEBUG - qDebug() << "GeometryCache::renderSphere()... --- CREATING COLORS BUFFER"; - qDebug() << " vertices:" << vertices; - qDebug() << " color:" << color; - qDebug() << " slices:" << slices; - qDebug() << " stacks:" << stacks; - qDebug() << " _sphereColors.size():" << _sphereColors.size(); + qCDebug(renderutils) << "GeometryCache::renderSphere()... --- CREATING COLORS BUFFER"; + qCDebug(renderutils) << " vertices:" << vertices; + qCDebug(renderutils) << " color:" << color; + qCDebug(renderutils) << " slices:" << slices; + qCDebug(renderutils) << " stacks:" << stacks; + qCDebug(renderutils) << " _sphereColors.size():" << _sphereColors.size(); #endif } #ifdef WANT_DEBUG else if (registered) { - qDebug() << "renderSphere()... REUSING PREVIOUSLY REGISTERED COLORS BUFFER"; + qCDebug(renderutils) << "renderSphere()... REUSING PREVIOUSLY REGISTERED COLORS BUFFER"; } #endif @@ -489,7 +490,7 @@ void GeometryCache::renderGrid(int xDivisions, int yDivisions, const glm::vec4& // TODO: why do we seem to create extra BatchItemDetails when we resize the window?? what's that?? void GeometryCache::renderGrid(int x, int y, int width, int height, int rows, int cols, const glm::vec4& color, int id) { #ifdef WANT_DEBUG - qDebug() << "GeometryCache::renderGrid(x["<& points, con if (details.isCreated) { details.clear(); #ifdef WANT_DEBUG - qDebug() << "updateVertices()... RELEASING REGISTERED"; + qCDebug(renderutils) << "updateVertices()... RELEASING REGISTERED"; #endif // def WANT_DEBUG } @@ -653,7 +654,7 @@ void GeometryCache::updateVertices(int id, const QVector& points, con delete[] colorData; #ifdef WANT_DEBUG - qDebug() << "new registered linestrip buffer made -- _registeredVertices.size():" << _registeredVertices.size(); + qCDebug(renderutils) << "new registered linestrip buffer made -- _registeredVertices.size():" << _registeredVertices.size(); #endif } @@ -663,7 +664,7 @@ void GeometryCache::updateVertices(int id, const QVector& points, con if (details.isCreated) { details.clear(); #ifdef WANT_DEBUG - qDebug() << "updateVertices()... RELEASING REGISTERED"; + qCDebug(renderutils) << "updateVertices()... RELEASING REGISTERED"; #endif // def WANT_DEBUG } @@ -716,7 +717,7 @@ void GeometryCache::updateVertices(int id, const QVector& points, con delete[] colorData; #ifdef WANT_DEBUG - qDebug() << "new registered linestrip buffer made -- _registeredVertices.size():" << _registeredVertices.size(); + qCDebug(renderutils) << "new registered linestrip buffer made -- _registeredVertices.size():" << _registeredVertices.size(); #endif } @@ -960,12 +961,12 @@ void GeometryCache::renderBevelCornersRect(int x, int y, int width, int height, details.clear(); _lastRegisteredBevelRects[id] = key; #ifdef WANT_DEBUG - qDebug() << "renderBevelCornersRect()... RELEASING REGISTERED"; + qCDebug(renderutils) << "renderBevelCornersRect()... RELEASING REGISTERED"; #endif // def WANT_DEBUG } #ifdef WANT_DEBUG else { - qDebug() << "renderBevelCornersRect()... REUSING PREVIOUSLY REGISTERED"; + qCDebug(renderutils) << "renderBevelCornersRect()... REUSING PREVIOUSLY REGISTERED"; } #endif // def WANT_DEBUG } @@ -1068,12 +1069,12 @@ void GeometryCache::renderQuad(const glm::vec2& minCorner, const glm::vec2& maxC details.clear(); _lastRegisteredQuad2D[id] = key; #ifdef WANT_DEBUG - qDebug() << "renderQuad() 2D ... RELEASING REGISTERED"; + qCDebug(renderutils) << "renderQuad() 2D ... RELEASING REGISTERED"; #endif // def WANT_DEBUG } #ifdef WANT_DEBUG else { - qDebug() << "renderQuad() 2D ... REUSING PREVIOUSLY REGISTERED"; + qCDebug(renderutils) << "renderQuad() 2D ... REUSING PREVIOUSLY REGISTERED"; } #endif // def WANT_DEBUG } @@ -1153,12 +1154,12 @@ void GeometryCache::renderQuad(const glm::vec2& minCorner, const glm::vec2& maxC details.clear(); _lastRegisteredQuad2DTexture[id] = key; #ifdef WANT_DEBUG - qDebug() << "renderQuad() 2D+texture ... RELEASING REGISTERED"; + qCDebug(renderutils) << "renderQuad() 2D+texture ... RELEASING REGISTERED"; #endif // def WANT_DEBUG } #ifdef WANT_DEBUG else { - qDebug() << "renderQuad() 2D+texture ... REUSING PREVIOUSLY REGISTERED"; + qCDebug(renderutils) << "renderQuad() 2D+texture ... REUSING PREVIOUSLY REGISTERED"; } #endif // def WANT_DEBUG } @@ -1243,12 +1244,12 @@ void GeometryCache::renderQuad(const glm::vec3& minCorner, const glm::vec3& maxC details.clear(); _lastRegisteredQuad3D[id] = key; #ifdef WANT_DEBUG - qDebug() << "renderQuad() 3D ... RELEASING REGISTERED"; + qCDebug(renderutils) << "renderQuad() 3D ... RELEASING REGISTERED"; #endif // def WANT_DEBUG } #ifdef WANT_DEBUG else { - qDebug() << "renderQuad() 3D ... REUSING PREVIOUSLY REGISTERED"; + qCDebug(renderutils) << "renderQuad() 3D ... REUSING PREVIOUSLY REGISTERED"; } #endif // def WANT_DEBUG } @@ -1318,14 +1319,14 @@ void GeometryCache::renderQuad(const glm::vec3& topLeft, const glm::vec3& bottom const glm::vec4& color, int id) { #ifdef WANT_DEBUG - qDebug() << "renderQuad() vec3 + texture VBO..."; - qDebug() << " topLeft:" << topLeft; - qDebug() << " bottomLeft:" << bottomLeft; - qDebug() << " bottomRight:" << bottomRight; - qDebug() << " topRight:" << topRight; - qDebug() << " texCoordTopLeft:" << texCoordTopLeft; - qDebug() << " texCoordBottomRight:" << texCoordBottomRight; - qDebug() << " color:" << color; + qCDebug(renderutils) << "renderQuad() vec3 + texture VBO..."; + qCDebug(renderutils) << " topLeft:" << topLeft; + qCDebug(renderutils) << " bottomLeft:" << bottomLeft; + qCDebug(renderutils) << " bottomRight:" << bottomRight; + qCDebug(renderutils) << " topRight:" << topRight; + qCDebug(renderutils) << " texCoordTopLeft:" << texCoordTopLeft; + qCDebug(renderutils) << " texCoordBottomRight:" << texCoordBottomRight; + qCDebug(renderutils) << " color:" << color; #endif //def WANT_DEBUG bool registered = (id != UNKNOWN_ID); @@ -1342,12 +1343,12 @@ void GeometryCache::renderQuad(const glm::vec3& topLeft, const glm::vec3& bottom details.clear(); _lastRegisteredQuad3DTexture[id] = key; #ifdef WANT_DEBUG - qDebug() << "renderQuad() 3D+texture ... RELEASING REGISTERED"; + qCDebug(renderutils) << "renderQuad() 3D+texture ... RELEASING REGISTERED"; #endif // def WANT_DEBUG } #ifdef WANT_DEBUG else { - qDebug() << "renderQuad() 3D+texture ... REUSING PREVIOUSLY REGISTERED"; + qCDebug(renderutils) << "renderQuad() 3D+texture ... REUSING PREVIOUSLY REGISTERED"; } #endif // def WANT_DEBUG } @@ -1434,7 +1435,7 @@ void GeometryCache::renderDashedLine(const glm::vec3& start, const glm::vec3& en details.clear(); _lastRegisteredDashedLines[id] = key; #ifdef WANT_DEBUG - qDebug() << "renderDashedLine()... RELEASING REGISTERED"; + qCDebug(renderutils) << "renderDashedLine()... RELEASING REGISTERED"; #endif // def WANT_DEBUG } } @@ -1516,9 +1517,9 @@ void GeometryCache::renderDashedLine(const glm::vec3& start, const glm::vec3& en #ifdef WANT_DEBUG if (registered) { - qDebug() << "new registered dashed line buffer made -- _registeredVertices:" << _registeredDashedLines.size(); + qCDebug(renderutils) << "new registered dashed line buffer made -- _registeredVertices:" << _registeredDashedLines.size(); } else { - qDebug() << "new dashed lines buffer made -- _dashedLines:" << _dashedLines.size(); + qCDebug(renderutils) << "new dashed lines buffer made -- _dashedLines:" << _dashedLines.size(); } #endif } @@ -1551,7 +1552,7 @@ GeometryCache::BatchItemDetails::BatchItemDetails() : { population++; #ifdef WANT_DEBUG - qDebug() << "BatchItemDetails()... population:" << population << "**********************************"; + qCDebug(renderutils) << "BatchItemDetails()... population:" << population << "**********************************"; #endif } @@ -1566,7 +1567,7 @@ GeometryCache::BatchItemDetails::BatchItemDetails(const GeometryCache::BatchItem { population++; #ifdef WANT_DEBUG - qDebug() << "BatchItemDetails()... population:" << population << "**********************************"; + qCDebug(renderutils) << "BatchItemDetails()... population:" << population << "**********************************"; #endif } @@ -1574,7 +1575,7 @@ GeometryCache::BatchItemDetails::~BatchItemDetails() { population--; clear(); #ifdef WANT_DEBUG - qDebug() << "~BatchItemDetails()... population:" << population << "**********************************"; + qCDebug(renderutils) << "~BatchItemDetails()... population:" << population << "**********************************"; #endif } @@ -1612,12 +1613,12 @@ void GeometryCache::renderLine(const glm::vec3& p1, const glm::vec3& p2, details.clear(); _lastRegisteredLine3D[id] = key; #ifdef WANT_DEBUG - qDebug() << "renderLine() 3D ... RELEASING REGISTERED line"; + qCDebug(renderutils) << "renderLine() 3D ... RELEASING REGISTERED line"; #endif // def WANT_DEBUG } #ifdef WANT_DEBUG else { - qDebug() << "renderLine() 3D ... REUSING PREVIOUSLY REGISTERED line"; + qCDebug(renderutils) << "renderLine() 3D ... REUSING PREVIOUSLY REGISTERED line"; } #endif // def WANT_DEBUG } @@ -1657,9 +1658,9 @@ void GeometryCache::renderLine(const glm::vec3& p1, const glm::vec3& p2, #ifdef WANT_DEBUG if (id == UNKNOWN_ID) { - qDebug() << "new renderLine() 3D VBO made -- _line3DVBOs.size():" << _line3DVBOs.size(); + qCDebug(renderutils) << "new renderLine() 3D VBO made -- _line3DVBOs.size():" << _line3DVBOs.size(); } else { - qDebug() << "new registered renderLine() 3D VBO made -- _registeredLine3DVBOs.size():" << _registeredLine3DVBOs.size(); + qCDebug(renderutils) << "new registered renderLine() 3D VBO made -- _registeredLine3DVBOs.size():" << _registeredLine3DVBOs.size(); } #endif } @@ -1704,12 +1705,12 @@ void GeometryCache::renderLine(const glm::vec2& p1, const glm::vec2& p2, details.clear(); _lastRegisteredLine2D[id] = key; #ifdef WANT_DEBUG - qDebug() << "renderLine() 2D ... RELEASING REGISTERED line"; + qCDebug(renderutils) << "renderLine() 2D ... RELEASING REGISTERED line"; #endif // def WANT_DEBUG } #ifdef WANT_DEBUG else { - qDebug() << "renderLine() 2D ... REUSING PREVIOUSLY REGISTERED line"; + qCDebug(renderutils) << "renderLine() 2D ... REUSING PREVIOUSLY REGISTERED line"; } #endif // def WANT_DEBUG } @@ -1749,9 +1750,9 @@ void GeometryCache::renderLine(const glm::vec2& p1, const glm::vec2& p2, #ifdef WANT_DEBUG if (id == UNKNOWN_ID) { - qDebug() << "new renderLine() 2D VBO made -- _line3DVBOs.size():" << _line2DVBOs.size(); + qCDebug(renderutils) << "new renderLine() 2D VBO made -- _line3DVBOs.size():" << _line2DVBOs.size(); } else { - qDebug() << "new registered renderLine() 2D VBO made -- _registeredLine2DVBOs.size():" << _registeredLine2DVBOs.size(); + qCDebug(renderutils) << "new registered renderLine() 2D VBO made -- _registeredLine2DVBOs.size():" << _registeredLine2DVBOs.size(); } #endif } @@ -1998,7 +1999,7 @@ void NetworkGeometry::setTextureWithNameToURL(const QString& name, const QUrl& u } } } else { - qDebug() << "Adding a name url pair to pending" << name << url; + qCDebug(renderutils) << "Adding a name url pair to pending" << name << url; // we don't have meshes downloaded yet, so hold this texture as pending _pendingTextureChanges.insert(name, url); } @@ -2112,7 +2113,7 @@ void GeometryReader::run() { } } catch (const QString& error) { - qDebug() << "Error reading " << _url << ": " << error; + qCDebug(renderutils) << "Error reading " << _url << ": " << error; QMetaObject::invokeMethod(geometry.data(), "finishedLoading", Q_ARG(bool, false)); } _reply->deleteLater(); @@ -2136,7 +2137,7 @@ void NetworkGeometry::downloadFinished(QNetworkReply* reply) { reply->deleteLater(); QString filename = _mapping.value("filename").toString(); if (filename.isNull()) { - qDebug() << "Mapping file " << url << " has no filename."; + qCDebug(renderutils) << "Mapping file " << url << " has no filename."; finishedLoading(false); } else { diff --git a/libraries/render-utils/src/GlowEffect.cpp b/libraries/render-utils/src/GlowEffect.cpp index 628dbf455f..2ba1d7df13 100644 --- a/libraries/render-utils/src/GlowEffect.cpp +++ b/libraries/render-utils/src/GlowEffect.cpp @@ -22,6 +22,7 @@ #include "ProgramObject.h" #include "RenderUtil.h" #include "TextureCache.h" +#include "RenderUtilsLogging.h" GlowEffect::GlowEffect() @@ -64,7 +65,7 @@ static ProgramObject* createProgram(const QString& name) { void GlowEffect::init(QGLWidget* widget, bool enabled) { if (_initialized) { - qDebug("[ERROR] GlowEffeect is already initialized."); + qCDebug(renderutils, "[ERROR] GlowEffeect is already initialized."); return; } diff --git a/libraries/render-utils/src/Model.cpp b/libraries/render-utils/src/Model.cpp index 1153335a4a..b98123803f 100644 --- a/libraries/render-utils/src/Model.cpp +++ b/libraries/render-utils/src/Model.cpp @@ -34,6 +34,7 @@ #include "DeferredLightingEffect.h" #include "GlowEffect.h" #include "Model.h" +#include "RenderUtilsLogging.h" #include "model_vert.h" #include "model_shadow_vert.h" @@ -2071,7 +2072,7 @@ void Model::segregateMeshGroups() { } const bool wantDebug = false; if (wantDebug) { - qDebug() << "materialID:" << materialID << "parts:" << mesh.parts.size(); + qCDebug(renderutils) << "materialID:" << materialID << "parts:" << mesh.parts.size(); } if (!hasLightmap) { @@ -2139,7 +2140,7 @@ void Model::segregateMeshGroups() { _unsortedMeshesOpaqueSpecularSkinned.insertMulti(materialID, i); } else { - qDebug() << "unexpected!!! this mesh didn't fall into any or our groups???"; + qCDebug(renderutils) << "unexpected!!! this mesh didn't fall into any or our groups???"; } } else { if (!translucentMesh && !hasTangents && !hasSpecular && !isSkinned) { @@ -2159,7 +2160,7 @@ void Model::segregateMeshGroups() { _unsortedMeshesOpaqueLightmapSpecular.insertMulti(materialID, i); } else { - qDebug() << "unexpected!!! this mesh didn't fall into any or our groups???"; + qCDebug(renderutils) << "unexpected!!! this mesh didn't fall into any or our groups???"; } } } @@ -2321,7 +2322,7 @@ QVector* Model::pickMeshList(bool translucent, float alphaThreshold, bool h whichList = &_meshesOpaqueLightmapSpecular; } else { - qDebug() << "unexpected!!! this mesh didn't fall into any or our groups???"; + qCDebug(renderutils) << "unexpected!!! this mesh didn't fall into any or our groups???"; } return whichList; } @@ -2399,7 +2400,7 @@ int Model::renderMeshes(gpu::Batch& batch, RenderMode mode, bool translucent, fl QVector* whichList = pickMeshList(translucent, alphaThreshold, hasLightmap, hasTangents, hasSpecular, isSkinned); if (!whichList) { - qDebug() << "unexpected!!! we don't know which list of meshes to render..."; + qCDebug(renderutils) << "unexpected!!! we don't know which list of meshes to render..."; return 0; } QVector& list = *whichList; @@ -2525,9 +2526,9 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod if (lastMaterialID != part.materialID) { const bool wantDebug = false; if (wantDebug) { - qDebug() << "Material Changed ---------------------------------------------"; - qDebug() << "part INDEX:" << j; - qDebug() << "NEW part.materialID:" << part.materialID; + qCDebug(renderutils) << "Material Changed ---------------------------------------------"; + qCDebug(renderutils) << "part INDEX:" << j; + qCDebug(renderutils) << "NEW part.materialID:" << part.materialID; } /* if (locations->glowIntensity >= 0) { diff --git a/libraries/render-utils/src/RenderUtilsLogging.cpp b/libraries/render-utils/src/RenderUtilsLogging.cpp new file mode 100644 index 0000000000..6af4a53b90 --- /dev/null +++ b/libraries/render-utils/src/RenderUtilsLogging.cpp @@ -0,0 +1,14 @@ +// +// RenderUtilsLogging.cpp +// libraries/render-utils/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "RenderUtilsLogging.h" + +Q_LOGGING_CATEGORY(renderutils, "hifi.renderutils") diff --git a/libraries/render-utils/src/RenderUtilsLogging.h b/libraries/render-utils/src/RenderUtilsLogging.h new file mode 100644 index 0000000000..defb10ed26 --- /dev/null +++ b/libraries/render-utils/src/RenderUtilsLogging.h @@ -0,0 +1,14 @@ +// +// RenderUtilsLogging.h +// libraries/render-utils/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include + +Q_DECLARE_LOGGING_CATEGORY(renderutils) diff --git a/libraries/render-utils/src/TextRenderer.cpp b/libraries/render-utils/src/TextRenderer.cpp index 75448f90cc..dbe5a027e7 100644 --- a/libraries/render-utils/src/TextRenderer.cpp +++ b/libraries/render-utils/src/TextRenderer.cpp @@ -32,6 +32,7 @@ #include "GLMHelpers.h" #include "MatrixStack.h" +#include "RenderUtilsLogging.h" #include "TextRenderer.h" #include "sdf_text_vert.h" @@ -180,7 +181,7 @@ Font* loadFont(const QString& family) { QFile fontFile(loadFilename); fontFile.open(QIODevice::ReadOnly); - qDebug() << "Loaded font" << loadFilename << "from Qt Resource System."; + qCDebug(renderutils) << "Loaded font" << loadFilename << "from Qt Resource System."; LOADED_FONTS[family] = loadFont(fontFile); } diff --git a/libraries/render-utils/src/TextureCache.cpp b/libraries/render-utils/src/TextureCache.cpp index 022e722c14..9b2a458231 100644 --- a/libraries/render-utils/src/TextureCache.cpp +++ b/libraries/render-utils/src/TextureCache.cpp @@ -23,6 +23,7 @@ #include #include +#include "RenderUtilsLogging.h" #include "TextureCache.h" #include "gpu/GLBackend.h" @@ -467,7 +468,7 @@ void ImageReader::run() { float scaleRatio = sqrtf((float)MAXIMUM_AREA_SIZE) / sqrtf((float)imageArea); int resizeWidth = static_cast(std::floor(scaleRatio * static_cast(image.width()))); int resizeHeight = static_cast(std::floor(scaleRatio * static_cast(image.height()))); - qDebug() << "Image greater than maximum size:" << _url << image.width() << image.height() << + qCDebug(renderutils) << "Image greater than maximum size:" << _url << image.width() << image.height() << " scaled to:" << resizeWidth << resizeHeight; image = image.scaled(resizeWidth, resizeHeight, Qt::IgnoreAspectRatio); imageArea = image.width() * image.height(); @@ -519,7 +520,7 @@ void ImageReader::run() { } } if (opaquePixels == imageArea) { - qDebug() << "Image with alpha channel is completely opaque:" << _url; + qCDebug(renderutils) << "Image with alpha channel is completely opaque:" << _url; image = image.convertToFormat(QImage::Format_RGB888); } QMetaObject::invokeMethod(texture.data(), "setImage", Q_ARG(const QImage&, image), diff --git a/libraries/script-engine/src/AudioScriptingInterface.cpp b/libraries/script-engine/src/AudioScriptingInterface.cpp index 387852fe00..deb1e1e9e9 100644 --- a/libraries/script-engine/src/AudioScriptingInterface.cpp +++ b/libraries/script-engine/src/AudioScriptingInterface.cpp @@ -10,7 +10,7 @@ // #include "ScriptAudioInjector.h" - +#include "ScriptEngineLogging.h" #include "AudioScriptingInterface.h" void registerAudioMetaTypes(QScriptEngine* engine) { @@ -65,7 +65,7 @@ ScriptAudioInjector* AudioScriptingInterface::playSound(Sound* sound, const Audi return new ScriptAudioInjector(injector); } else { - qDebug() << "AudioScriptingInterface::playSound called with null Sound object."; + qCDebug(scriptengine) << "AudioScriptingInterface::playSound called with null Sound object."; return NULL; } -} \ No newline at end of file +} diff --git a/libraries/script-engine/src/BatchLoader.cpp b/libraries/script-engine/src/BatchLoader.cpp index c455ca91ec..db0743808f 100644 --- a/libraries/script-engine/src/BatchLoader.cpp +++ b/libraries/script-engine/src/BatchLoader.cpp @@ -13,10 +13,14 @@ #include #include +#include "ScriptEngineLogging.h" #include "BatchLoader.h" #include #include + + + BatchLoader::BatchLoader(const QList& urls) : QObject(), _started(false), @@ -38,7 +42,7 @@ void BatchLoader::start() { request.setHeader(QNetworkRequest::UserAgentHeader, HIGH_FIDELITY_USER_AGENT); QNetworkReply* reply = networkAccessManager.get(request); - qDebug() << "Downloading file at" << url; + qCDebug(scriptengine) << "Downloading file at" << url; connect(reply, &QNetworkReply::finished, [=]() { if (reply->error()) { @@ -60,7 +64,7 @@ void BatchLoader::start() { QString fileName = url.toLocalFile(); #endif - qDebug() << "Reading file at " << fileName; + qCDebug(scriptengine) << "Reading file at " << fileName; QFile scriptFile(fileName); if (scriptFile.open(QFile::ReadOnly | QFile::Text)) { diff --git a/libraries/script-engine/src/KeyEvent.cpp b/libraries/script-engine/src/KeyEvent.cpp index febc8fc21f..6d3a8aad44 100644 --- a/libraries/script-engine/src/KeyEvent.cpp +++ b/libraries/script-engine/src/KeyEvent.cpp @@ -12,6 +12,8 @@ #include #include +#include "ScriptEngineLogging.h" + #include "KeyEvent.h" KeyEvent::KeyEvent() : @@ -276,7 +278,7 @@ void KeyEvent::fromScriptValue(const QScriptValue& object, KeyEvent& event) { const bool wantDebug = false; if (wantDebug) { - qDebug() << "event.key=" << event.key + qCDebug(scriptengine) << "event.key=" << event.key << " event.text=" << event.text << " event.isShifted=" << event.isShifted << " event.isControl=" << event.isControl diff --git a/libraries/script-engine/src/Quat.cpp b/libraries/script-engine/src/Quat.cpp index e961eb0acf..a44a623b1e 100644 --- a/libraries/script-engine/src/Quat.cpp +++ b/libraries/script-engine/src/Quat.cpp @@ -15,6 +15,7 @@ #include #include +#include "ScriptEngineLogging.h" #include "Quat.h" @@ -81,7 +82,7 @@ float Quat::dot(const glm::quat& q1, const glm::quat& q2) { } void Quat::print(const QString& lable, const glm::quat& q) { - qDebug() << qPrintable(lable) << q.x << "," << q.y << "," << q.z << "," << q.w; + qCDebug(scriptengine) << qPrintable(lable) << q.x << "," << q.y << "," << q.z << "," << q.w; } bool Quat::equal(const glm::vec3& q1, const glm::vec3& q2) { diff --git a/libraries/script-engine/src/ScriptAudioInjector.cpp b/libraries/script-engine/src/ScriptAudioInjector.cpp index 7bdf78be63..a9cf40558c 100644 --- a/libraries/script-engine/src/ScriptAudioInjector.cpp +++ b/libraries/script-engine/src/ScriptAudioInjector.cpp @@ -9,6 +9,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include "ScriptEngineLogging.h" #include "ScriptAudioInjector.h" QScriptValue injectorToScriptValue(QScriptEngine* engine, ScriptAudioInjector* const& in) { @@ -38,6 +39,6 @@ ScriptAudioInjector::~ScriptAudioInjector() { } void ScriptAudioInjector::stopInjectorImmediately() { - qDebug() << "ScriptAudioInjector::stopInjectorImmediately called to stop audio injector immediately."; + qCDebug(scriptengine) << "ScriptAudioInjector::stopInjectorImmediately called to stop audio injector immediately."; _injector->stopAndDeleteLater(); } diff --git a/libraries/script-engine/src/ScriptCache.cpp b/libraries/script-engine/src/ScriptCache.cpp index c0ffc7b4e7..5025d02918 100644 --- a/libraries/script-engine/src/ScriptCache.cpp +++ b/libraries/script-engine/src/ScriptCache.cpp @@ -17,7 +17,7 @@ #include #include - +#include "ScriptEngineLogging.h" #include "ScriptCache.h" ScriptCache::ScriptCache(QObject* parent) { @@ -27,7 +27,7 @@ ScriptCache::ScriptCache(QObject* parent) { QString ScriptCache::getScript(const QUrl& url, ScriptUser* scriptUser, bool& isPending) { QString scriptContents; if (_scriptCache.contains(url)) { - qDebug() << "Found script in cache:" << url.toString(); + qCDebug(scriptengine) << "Found script in cache:" << url.toString(); scriptContents = _scriptCache[url]; scriptUser->scriptContentsAvailable(url, scriptContents); isPending = false; @@ -37,13 +37,13 @@ QString ScriptCache::getScript(const QUrl& url, ScriptUser* scriptUser, bool& is _scriptUsers.insert(url, scriptUser); if (alreadyWaiting) { - qDebug() << "Already downloading script at:" << url.toString(); + qCDebug(scriptengine) << "Already downloading script at:" << url.toString(); } else { QNetworkAccessManager& networkAccessManager = NetworkAccessManager::getInstance(); QNetworkRequest networkRequest = QNetworkRequest(url); networkRequest.setHeader(QNetworkRequest::UserAgentHeader, HIGH_FIDELITY_USER_AGENT); - qDebug() << "Downloading script at:" << url.toString(); + qCDebug(scriptengine) << "Downloading script at:" << url.toString(); QNetworkReply* reply = networkAccessManager.get(networkRequest); connect(reply, &QNetworkReply::finished, this, &ScriptCache::scriptDownloaded); } @@ -59,13 +59,13 @@ void ScriptCache::scriptDownloaded() { if (reply->error() == QNetworkReply::NoError && reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 200) { _scriptCache[url] = reply->readAll(); - qDebug() << "Done downloading script at:" << url.toString(); + qCDebug(scriptengine) << "Done downloading script at:" << url.toString(); foreach(ScriptUser* user, scriptUsers) { user->scriptContentsAvailable(url, _scriptCache[url]); } } else { - qDebug() << "ERROR Loading file:" << reply->url().toString(); + qCDebug(scriptengine) << "ERROR Loading file:" << reply->url().toString(); foreach(ScriptUser* user, scriptUsers) { user->errorInLoadingScript(url); } diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 390b889579..2f9427a63d 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -35,6 +35,7 @@ #include "MenuItemProperties.h" #include "ScriptAudioInjector.h" #include "ScriptCache.h" +#include "ScriptEngineLogging.h" #include "ScriptEngine.h" #include "TypedArrays.h" #include "XMLHttpRequestClass.h" @@ -45,7 +46,7 @@ static QScriptValue debugPrint(QScriptContext* context, QScriptEngine* engine){ - qDebug() << "script:print()<<" << context->argument(0).toString(); + qCDebug(scriptengine) << "script:print()<<" << context->argument(0).toString(); QString message = context->argument(0).toString() .replace("\\", "\\\\") .replace("\n", "\\n") @@ -271,12 +272,12 @@ void ScriptEngine::loadURL(const QUrl& scriptURL) { _fileNameString = url.toLocalFile(); QFile scriptFile(_fileNameString); if (scriptFile.open(QFile::ReadOnly | QFile::Text)) { - qDebug() << "ScriptEngine loading file:" << _fileNameString; + qCDebug(scriptengine) << "ScriptEngine loading file:" << _fileNameString; QTextStream in(&scriptFile); _scriptContents = in.readAll(); emit scriptLoaded(_fileNameString); } else { - qDebug() << "ERROR Loading file:" << _fileNameString << "line:" << __LINE__; + qCDebug(scriptengine) << "ERROR Loading file:" << _fileNameString << "line:" << __LINE__; emit errorLoadingScript(_fileNameString); } } else { @@ -294,7 +295,7 @@ void ScriptEngine::scriptContentsAvailable(const QUrl& url, const QString& scrip } void ScriptEngine::errorInLoadingScript(const QUrl& url) { - qDebug() << "ERROR Loading file:" << url.toString() << "line:" << __LINE__; + qCDebug(scriptengine) << "ERROR Loading file:" << url.toString() << "line:" << __LINE__; emit errorLoadingScript(_fileNameString); // ?? } @@ -402,7 +403,7 @@ void ScriptEngine::evaluate() { // will cause this code to never actually run... if (hasUncaughtException()) { int line = uncaughtExceptionLineNumber(); - qDebug() << "Uncaught exception at (" << _fileNameString << ") line" << line << ":" << result.toString(); + qCDebug(scriptengine) << "Uncaught exception at (" << _fileNameString << ") line" << line << ":" << result.toString(); emit errorMessage("Uncaught exception at (" + _fileNameString + ") line" + QString::number(line) + ":" + result.toString()); clearExceptions(); } @@ -417,7 +418,7 @@ QScriptValue ScriptEngine::evaluate(const QString& program, const QString& fileN QScriptValue result = QScriptEngine::evaluate(program, fileName, lineNumber); if (hasUncaughtException()) { int line = uncaughtExceptionLineNumber(); - qDebug() << "Uncaught exception at (" << _fileNameString << " : " << fileName << ") line" << line << ": " << result.toString(); + qCDebug(scriptengine) << "Uncaught exception at (" << _fileNameString << " : " << fileName << ") line" << line << ": " << result.toString(); } _evaluatesPending--; emit evaluationFinished(result, hasUncaughtException()); @@ -591,7 +592,7 @@ void ScriptEngine::run() { if (hasUncaughtException()) { int line = uncaughtExceptionLineNumber(); - qDebug() << "Uncaught exception at (" << _fileNameString << ") line" << line << ":" << uncaughtException().toString(); + qCDebug(scriptengine) << "Uncaught exception at (" << _fileNameString << ") line" << line << ":" << uncaughtException().toString(); emit errorMessage("Uncaught exception at (" + _fileNameString + ") line" + QString::number(line) + ":" + uncaughtException().toString()); clearExceptions(); } @@ -684,7 +685,7 @@ QObject* ScriptEngine::setupTimerWithInterval(const QScriptValue& function, int QObject* ScriptEngine::setInterval(const QScriptValue& function, int intervalMS) { if (_stoppingAllScripts) { - qDebug() << "Script.setInterval() while shutting down is ignored... parent script:" << getFilename(); + qCDebug(scriptengine) << "Script.setInterval() while shutting down is ignored... parent script:" << getFilename(); return NULL; // bail early } @@ -693,7 +694,7 @@ QObject* ScriptEngine::setInterval(const QScriptValue& function, int intervalMS) QObject* ScriptEngine::setTimeout(const QScriptValue& function, int timeoutMS) { if (_stoppingAllScripts) { - qDebug() << "Script.setTimeout() while shutting down is ignored... parent script:" << getFilename(); + qCDebug(scriptengine) << "Script.setTimeout() while shutting down is ignored... parent script:" << getFilename(); return NULL; // bail early } @@ -743,7 +744,7 @@ void ScriptEngine::print(const QString& message) { // all of the files have finished loading. void ScriptEngine::include(const QStringList& includeFiles, QScriptValue callback) { if (_stoppingAllScripts) { - qDebug() << "Script.include() while shutting down is ignored..." + qCDebug(scriptengine) << "Script.include() while shutting down is ignored..." << "includeFiles:" << includeFiles << "parent script:" << getFilename(); return; // bail early } @@ -758,7 +759,7 @@ void ScriptEngine::include(const QStringList& includeFiles, QScriptValue callbac for (QUrl url : urls) { QString contents = data[url]; if (contents.isNull()) { - qDebug() << "Error loading file: " << url << "line:" << __LINE__; + qCDebug(scriptengine) << "Error loading file: " << url << "line:" << __LINE__; } else { QScriptValue result = evaluate(contents, url.toString()); } @@ -787,7 +788,7 @@ void ScriptEngine::include(const QStringList& includeFiles, QScriptValue callbac void ScriptEngine::include(const QString& includeFile, QScriptValue callback) { if (_stoppingAllScripts) { - qDebug() << "Script.include() while shutting down is ignored... " + qCDebug(scriptengine) << "Script.include() while shutting down is ignored... " << "includeFile:" << includeFile << "parent script:" << getFilename(); return; // bail early } @@ -802,7 +803,7 @@ void ScriptEngine::include(const QString& includeFile, QScriptValue callback) { // the Application or other context will connect to in order to know to actually load the script void ScriptEngine::load(const QString& loadFile) { if (_stoppingAllScripts) { - qDebug() << "Script.load() while shutting down is ignored... " + qCDebug(scriptengine) << "Script.load() while shutting down is ignored... " << "loadFile:" << loadFile << "parent script:" << getFilename(); return; // bail early } diff --git a/libraries/script-engine/src/ScriptEngineLogging.cpp b/libraries/script-engine/src/ScriptEngineLogging.cpp new file mode 100644 index 0000000000..2e5d293728 --- /dev/null +++ b/libraries/script-engine/src/ScriptEngineLogging.cpp @@ -0,0 +1,14 @@ +// +// ScriptEngineLogging.cpp +// libraries/script-engine/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "ScriptEngineLogging.h" + +Q_LOGGING_CATEGORY(scriptengine, "hifi.scriptengine") diff --git a/libraries/script-engine/src/ScriptEngineLogging.h b/libraries/script-engine/src/ScriptEngineLogging.h new file mode 100644 index 0000000000..0e614dd5bf --- /dev/null +++ b/libraries/script-engine/src/ScriptEngineLogging.h @@ -0,0 +1,20 @@ +// +// ScriptEngineLogging.h +// libraries/script-engine/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_ScriptEngineLogging_h +#define hifi_ScriptEngineLogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(scriptengine) + +#endif // hifi_ScriptEngineLogging_h + diff --git a/libraries/script-engine/src/ScriptUUID.cpp b/libraries/script-engine/src/ScriptUUID.cpp index 9e00f9c095..6a52f4f6ca 100644 --- a/libraries/script-engine/src/ScriptUUID.cpp +++ b/libraries/script-engine/src/ScriptUUID.cpp @@ -13,6 +13,7 @@ #include +#include "ScriptEngineLogging.h" #include "ScriptUUID.h" QUuid ScriptUUID::fromString(const QString& s) { @@ -36,5 +37,5 @@ bool ScriptUUID::isNull(const QUuid& id) { } void ScriptUUID::print(const QString& lable, const QUuid& id) { - qDebug() << qPrintable(lable) << id.toString(); + qCDebug(scriptengine) << qPrintable(lable) << id.toString(); } diff --git a/libraries/script-engine/src/Vec3.cpp b/libraries/script-engine/src/Vec3.cpp index cb9ad045ff..49a2ad2cbe 100644 --- a/libraries/script-engine/src/Vec3.cpp +++ b/libraries/script-engine/src/Vec3.cpp @@ -13,6 +13,7 @@ #include +#include "ScriptEngineLogging.h" #include "Vec3.h" glm::vec3 Vec3::reflect(const glm::vec3& v1, const glm::vec3& v2) { @@ -66,7 +67,7 @@ glm::vec3 Vec3::mix(const glm::vec3& v1, const glm::vec3& v2, float m) { } void Vec3::print(const QString& lable, const glm::vec3& v) { - qDebug() << qPrintable(lable) << v.x << "," << v.y << "," << v.z; + qCDebug(scriptengine) << qPrintable(lable) << v.x << "," << v.y << "," << v.z; } bool Vec3::equal(const glm::vec3& v1, const glm::vec3& v2) { diff --git a/libraries/shared/src/HifiConfigVariantMap.cpp b/libraries/shared/src/HifiConfigVariantMap.cpp index 648f15648a..c92260210e 100644 --- a/libraries/shared/src/HifiConfigVariantMap.cpp +++ b/libraries/shared/src/HifiConfigVariantMap.cpp @@ -18,6 +18,7 @@ #include #include +#include "SharedLogging.h" #include "HifiConfigVariantMap.h" QVariantMap HifiConfigVariantMap::mergeCLParametersWithJSONConfig(const QStringList& argumentList) { @@ -132,14 +133,14 @@ void HifiConfigVariantMap::loadMapFromJSONFile(QVariantMap& existingMap, const Q QFile configFile(filename); if (configFile.exists()) { - qDebug() << "Reading JSON config file at" << filename; + qCDebug(shared) << "Reading JSON config file at" << filename; configFile.open(QIODevice::ReadOnly); QJsonDocument configDocument = QJsonDocument::fromJson(configFile.readAll()); existingMap = configDocument.toVariant().toMap(); } else { - qDebug() << "Could not find JSON config file at" << filename; + qCDebug(shared) << "Could not find JSON config file at" << filename; } } diff --git a/libraries/shared/src/PerfStat.cpp b/libraries/shared/src/PerfStat.cpp index f5f6964b6d..f16e6d7d9d 100644 --- a/libraries/shared/src/PerfStat.cpp +++ b/libraries/shared/src/PerfStat.cpp @@ -18,6 +18,7 @@ #include "PerfStat.h" +#include "SharedLogging.h" #include "SharedUtil.h" // ---------------------------------------------------------------------------- @@ -35,20 +36,20 @@ PerformanceWarning::~PerformanceWarning() { if ((_alwaysDisplay || _renderWarningsOn) && elapsedmsec > 1) { if (elapsedmsec > 1000) { double elapsedsec = (end - _start) / 1000000.0; - qDebug("%s took %.2lf seconds %s", _message, elapsedsec, (_alwaysDisplay ? "" : "WARNING!") ); + qCDebug(shared, "%s took %.2lf seconds %s", _message, elapsedsec, (_alwaysDisplay ? "" : "WARNING!") ); } else { if (_suppressShortTimings) { if (elapsedmsec > 10) { - qDebug("%s took %.1lf milliseconds %s", _message, elapsedmsec, + qCDebug(shared, "%s took %.1lf milliseconds %s", _message, elapsedmsec, (_alwaysDisplay || (elapsedmsec < 10) ? "" : "WARNING!")); } } else { - qDebug("%s took %.2lf milliseconds %s", _message, elapsedmsec, + qCDebug(shared, "%s took %.2lf milliseconds %s", _message, elapsedmsec, (_alwaysDisplay || (elapsedmsec < 10) ? "" : "WARNING!")); } } } else if (_alwaysDisplay) { - qDebug("%s took %.2lf milliseconds", _message, elapsedmsec); + qCDebug(shared, "%s took %.2lf milliseconds", _message, elapsedmsec); } // if the caller gave us a pointer to store the running total, track it now. if (_runningTotal) { @@ -120,7 +121,7 @@ void PerformanceTimer::dumpAllTimerRecords() { QMapIterator i(_records); while (i.hasNext()) { i.next(); - qDebug() << i.key() << ": average " << i.value().getAverage() + qCDebug(shared) << i.key() << ": average " << i.value().getAverage() << " [" << i.value().getMovingAverage() << "]" << "usecs over" << i.value().getCount() << "calls"; } diff --git a/libraries/shared/src/SettingInterface.cpp b/libraries/shared/src/SettingInterface.cpp index 217a8f00b2..e263d83ef6 100644 --- a/libraries/shared/src/SettingInterface.cpp +++ b/libraries/shared/src/SettingInterface.cpp @@ -16,6 +16,7 @@ #include "PathUtils.h" #include "SettingInterface.h" #include "SettingManager.h" +#include "SharedLogging.h" namespace Setting { static Manager* privateInstance = nullptr; @@ -58,7 +59,7 @@ namespace Setting { QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); privateInstance->moveToThread(thread); thread->start(); - qDebug() << "Settings thread started."; + qCDebug(shared) << "Settings thread started."; // Register cleanupPrivateInstance to run inside QCoreApplication's destructor. qAddPostRoutine(cleanupPrivateInstance); @@ -104,4 +105,4 @@ namespace Setting { privateInstance->loadSetting(this); } } -} \ No newline at end of file +} diff --git a/libraries/shared/src/SharedLogging.cpp b/libraries/shared/src/SharedLogging.cpp new file mode 100644 index 0000000000..31ad0c7a0a --- /dev/null +++ b/libraries/shared/src/SharedLogging.cpp @@ -0,0 +1,14 @@ +// +// SharedLogging.cpp +// libraries/shared/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "SharedLogging.h" + +Q_LOGGING_CATEGORY(shared, "hifi.shared") diff --git a/libraries/shared/src/SharedLogging.h b/libraries/shared/src/SharedLogging.h new file mode 100644 index 0000000000..e32b754dd9 --- /dev/null +++ b/libraries/shared/src/SharedLogging.h @@ -0,0 +1,20 @@ +// +// SharedLogging.h +// libraries/shared/src +// +// Created by Seth Alves on 4/6/15. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_SharedLogging_h +#define hifi_SharedLogging_h + +#include + +Q_DECLARE_LOGGING_CATEGORY(shared) + +#endif // hifi_SharedLogging_h + diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index 7b5a0bb15d..ce566df0b6 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -30,6 +30,7 @@ #include #include "OctalCode.h" +#include "SharedLogging.h" #include "SharedUtil.h" static int usecTimestampNowAdjust = 0; // in usec @@ -65,14 +66,14 @@ quint64 usecTimestampNow(bool wantDebug) { now = TIME_REFERENCE + ::usecTimestampNowAdjust; if (wantDebug) { - qDebug() << "usecTimestampNow() - resetting QElapsedTimer. "; - qDebug() << " msecsCurrentTime:" << msecsCurrentTime; - qDebug() << " msecsEstimate:" << msecsEstimate; - qDebug() << " possibleSkew:" << possibleSkew; - qDebug() << " TOLERANCE:" << TOLERANCE; + qCDebug(shared) << "usecTimestampNow() - resetting QElapsedTimer. "; + qCDebug(shared) << " msecsCurrentTime:" << msecsCurrentTime; + qCDebug(shared) << " msecsEstimate:" << msecsEstimate; + qCDebug(shared) << " possibleSkew:" << possibleSkew; + qCDebug(shared) << " TOLERANCE:" << TOLERANCE; - qDebug() << " nsecsElapsed:" << nsecsElapsed; - qDebug() << " usecsElapsed:" << usecsElapsed; + qCDebug(shared) << " nsecsElapsed:" << nsecsElapsed; + qCDebug(shared) << " usecsElapsed:" << usecsElapsed; QDateTime currentLocalTime = QDateTime::currentDateTime(); @@ -80,11 +81,11 @@ quint64 usecTimestampNow(bool wantDebug) { QDateTime nowAsString; nowAsString.setMSecsSinceEpoch(msecsNow); - qDebug() << " now:" << now; - qDebug() << " msecsNow:" << msecsNow; + qCDebug(shared) << " now:" << now; + qCDebug(shared) << " msecsNow:" << msecsNow; - qDebug() << " nowAsString:" << nowAsString.toString("yyyy-MM-dd hh:mm:ss.zzz"); - qDebug() << " currentLocalTime:" << currentLocalTime.toString("yyyy-MM-dd hh:mm:ss.zzz"); + qCDebug(shared) << " nowAsString:" << nowAsString.toString("yyyy-MM-dd hh:mm:ss.zzz"); + qCDebug(shared) << " currentLocalTime:" << currentLocalTime.toString("yyyy-MM-dd hh:mm:ss.zzz"); } } else { now = TIME_REFERENCE + usecsElapsed + ::usecTimestampNowAdjust; @@ -101,16 +102,16 @@ quint64 usecTimestampNow(bool wantDebug) { QDateTime timeReferenceAsString; timeReferenceAsString.setMSecsSinceEpoch(msecsTimeReference); - qDebug() << "usecTimestampNow() - details... "; - qDebug() << " TIME_REFERENCE:" << TIME_REFERENCE; - qDebug() << " timeReferenceAsString:" << timeReferenceAsString.toString("yyyy-MM-dd hh:mm:ss.zzz"); - qDebug() << " usecTimestampNowAdjust:" << usecTimestampNowAdjust; - qDebug() << " nsecsElapsed:" << nsecsElapsed; - qDebug() << " usecsElapsed:" << usecsElapsed; - qDebug() << " now:" << now; - qDebug() << " msecsNow:" << msecsNow; - qDebug() << " nowAsString:" << nowAsString.toString("yyyy-MM-dd hh:mm:ss.zzz"); - qDebug() << " currentLocalTime:" << currentLocalTime.toString("yyyy-MM-dd hh:mm:ss.zzz"); + qCDebug(shared) << "usecTimestampNow() - details... "; + qCDebug(shared) << " TIME_REFERENCE:" << TIME_REFERENCE; + qCDebug(shared) << " timeReferenceAsString:" << timeReferenceAsString.toString("yyyy-MM-dd hh:mm:ss.zzz"); + qCDebug(shared) << " usecTimestampNowAdjust:" << usecTimestampNowAdjust; + qCDebug(shared) << " nsecsElapsed:" << nsecsElapsed; + qCDebug(shared) << " usecsElapsed:" << usecsElapsed; + qCDebug(shared) << " now:" << now; + qCDebug(shared) << " msecsNow:" << msecsNow; + qCDebug(shared) << " nowAsString:" << nowAsString.toString("yyyy-MM-dd hh:mm:ss.zzz"); + qCDebug(shared) << " currentLocalTime:" << currentLocalTime.toString("yyyy-MM-dd hh:mm:ss.zzz"); } return now; @@ -427,16 +428,16 @@ unsigned char* pointToVoxel(float x, float y, float z, float s, unsigned char r, void printVoxelCode(unsigned char* voxelCode) { unsigned char octets = voxelCode[0]; - unsigned int voxelSizeInBits = octets*3; - unsigned int voxelSizeInBytes = (voxelSizeInBits/8)+1; - unsigned int voxelSizeInOctets = (voxelSizeInBits/3); - unsigned int voxelBufferSize = voxelSizeInBytes+1+3; // 1 for size, 3 for color + unsigned int voxelSizeInBits = octets*3; + unsigned int voxelSizeInBytes = (voxelSizeInBits/8)+1; + unsigned int voxelSizeInOctets = (voxelSizeInBits/3); + unsigned int voxelBufferSize = voxelSizeInBytes+1+3; // 1 for size, 3 for color - qDebug("octets=%d",octets); - qDebug("voxelSizeInBits=%d",voxelSizeInBits); - qDebug("voxelSizeInBytes=%d",voxelSizeInBytes); - qDebug("voxelSizeInOctets=%d",voxelSizeInOctets); - qDebug("voxelBufferSize=%d",voxelBufferSize); + qCDebug(shared, "octets=%d",octets); + qCDebug(shared, "voxelSizeInBits=%d",voxelSizeInBits); + qCDebug(shared, "voxelSizeInBytes=%d",voxelSizeInBytes); + qCDebug(shared, "voxelSizeInOctets=%d",voxelSizeInOctets); + qCDebug(shared, "voxelBufferSize=%d",voxelBufferSize); for(unsigned int i=0; i < voxelBufferSize; i++) { QDebug voxelBufferDebug = qDebug(); diff --git a/libraries/shared/src/VariantMapToScriptValue.cpp b/libraries/shared/src/VariantMapToScriptValue.cpp index 6fa3fd04e6..6c21557325 100644 --- a/libraries/shared/src/VariantMapToScriptValue.cpp +++ b/libraries/shared/src/VariantMapToScriptValue.cpp @@ -10,6 +10,7 @@ // #include +#include "SharedLogging.h" #include "VariantMapToScriptValue.h" QScriptValue variantMapToScriptValue(QVariantMap& variantMap, QScriptEngine& scriptEngine) { @@ -39,7 +40,7 @@ QScriptValue variantMapToScriptValue(QVariantMap& variantMap, QScriptEngine& scr break; } default: - qDebug() << "unhandled QScript type" << qValue.type(); + qCDebug(shared) << "unhandled QScript type" << qValue.type(); } } diff --git a/libraries/shared/src/qtimespan.cpp b/libraries/shared/src/qtimespan.cpp index f3482cfb14..72a227948e 100644 --- a/libraries/shared/src/qtimespan.cpp +++ b/libraries/shared/src/qtimespan.cpp @@ -69,6 +69,7 @@ #include #endif +#include "SharedLogging.h" /*! @@ -740,7 +741,7 @@ bool QTimeSpan::parts(int *msecondsPtr, QDate newStartDate(startDate); newStartDate = newStartDate.addYears(*_years); newStartDate = newStartDate.addMonths(*_months); - //qDebug() << "working with new start date" << newStartDate << "and end date" << endDate; + //qCDebug(shared) << "working with new start date" << newStartDate << "and end date" << endDate; ts = QDateTime(endDate, ts.endDate().time()) - QDateTime(newStartDate, ts.startDate().time()); *_months = totalMonths; @@ -756,7 +757,7 @@ bool QTimeSpan::parts(int *msecondsPtr, //from here on, we use ts as the time span! qint64 intervalLeft = ts.toMSecs(); qint64 unitFactor; - //qDebug() << "intervalLeft" << intervalLeft; + //qCDebug(shared) << "intervalLeft" << intervalLeft; if (weeksPtr) { unitFactor = (7 * 24 * 60 * 60 * 1000); CHECK_INT_LIMIT(intervalLeft, unitFactor) @@ -1089,8 +1090,8 @@ bool QTimeSpan::operator<=(const QTimeSpan &other) const \code QTimeSpan s1 = 2 * QTimeSpan::Day; QTimeSpan s2 = -2 * QTimeSpan::Day; - qDebug() << s1.matchesLength(s2); //returns false - qDebug() << s1.matchesLength(s2, true); //returns true + qCDebug(shared) << s1.matchesLength(s2); //returns false + qCDebug(shared) << s1.matchesLength(s2, true); //returns true \endcode */ bool QTimeSpan::matchesLength(const QTimeSpan &other, bool normalize) const @@ -2060,7 +2061,7 @@ QString QTimeSpan::toApproximateString(int suppresSecondUnitLimit, Qt::TimeSpanF bool result = partsHash.fill(*this); if (!result) { - qDebug() << "false result from parts function"; + qCDebug(shared) << "false result from parts function"; return QString(); } @@ -2214,7 +2215,7 @@ QTimeSpan QTimeSpan::fromString(const QString &string, const QString &format, co it.next(); if (it.value()) { span.d->addUnit(&span, it.key(), *(it.value())); - qDebug() << "Added unit" << it.key() << "with value" << *(it.value()) << "new value" << span.d->interval; + qCDebug(shared) << "Added unit" << it.key() << "with value" << *(it.value()) << "new value" << span.d->interval; } }