Skip to content

state callbacks of the modelviewer #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/model_viewer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@
library model_viewer;

export 'src/model_viewer.dart';
export 'src/controller.dart';
19 changes: 19 additions & 0 deletions lib/src/controller.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import 'package:flutter/material.dart';

typedef ChangeColorTypeDef = Future<String> Function(String);

/// The [ModelViewerColorController] is used to control the color settings of the model viewer.
/// If the function [changeColor(colorString)] is called, then the base color of the model will be changed.
///
/// At the moment the [ModelViewerColorController] can only change the base color of the model.
/// The base color is auto detected by the biggest size object of the model.
class ModelViewerColorController {
/// change the color by a given colorString
ChangeColorTypeDef changeColor;
// ToDo: Add a function to get possibble color areas
// ToDo: set colors for detected areas

void dispose() {
changeColor = null;
}
}
38 changes: 38 additions & 0 deletions lib/src/html_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ abstract class HTMLBuilder {
final int autoRotateDelay,
final bool autoPlay,
final bool cameraControls,
final bool enableColorChange,
final String iosSrc}) {
final html = StringBuffer(htmlTemplate);
html.write('<model-viewer');
Expand Down Expand Up @@ -64,6 +65,11 @@ abstract class HTMLBuilder {
if (iosSrc != null) {
html.write(' ios-src="${htmlEscape.convert(iosSrc)}"');
}

if (enableColorChange ?? false) {
html.write(' id="color"');
}

// TODO: max-camera-orbit
// TODO: max-field-of-view
// TODO: min-camera-orbit
Expand All @@ -75,6 +81,38 @@ abstract class HTMLBuilder {
// TODO: shadow-intensity
// TODO: shadow-softness
html.writeln('></model-viewer>');

if (enableColorChange ?? false) {
html.write(_buildColorChangeJSFunction());
}

html.write(_buildModelVisibilityEventJSFunction());

return html.toString();
}

static String _buildColorChangeJSFunction() {
return '''
<script type="text/javascript">
function changeColor(colorString) {
const modelViewerColor = document.querySelector("model-viewer#color");
const color = colorString.split(',')
.map(numberString => parseFloat(numberString));
const [material] = modelViewerColor.model.materials;
material.pbrMetallicRoughness.setBaseColorFactor(color);
}
</script>
''';
}

static String _buildModelVisibilityEventJSFunction() {
return '''
<script type="text/javascript">
const modelViewerElement = document.querySelector("model-viewer");
modelViewerElement.addEventListener('model-visibility', (event) => {
messageIsVisibile.postMessage(event.detail.visible);
});
</script>
''';
}
}
83 changes: 81 additions & 2 deletions lib/src/model_viewer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import 'package:flutter_android/android_content.dart' as android_content;
import 'package:webview_flutter/platform_interface.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'controller.dart';
import 'html_builder.dart';

/// Flutter widget for rendering interactive 3D models.
Expand All @@ -28,7 +29,14 @@ class ModelViewer extends StatefulWidget {
this.autoRotateDelay,
this.autoPlay,
this.cameraControls,
this.iosSrc})
this.enableColorChange,
this.colorController,
this.iosSrc,
this.onModelViewCreated,
this.onModelViewError,
this.onModelViewFinished,
this.onModelIsVisisble,
this.onModelViewStarted})
: super(key: key);

/// The background color for the model viewer.
Expand Down Expand Up @@ -66,6 +74,15 @@ class ModelViewer extends StatefulWidget {
/// Defaults to "auto" which allows the model to be resized.
final String arScale;

/// Enable the ability to change the color of the model with the [ModelViewerColorController]
/// If this value is set to true, it's possible to set the color of the model.
final bool enableColorChange;

/// Controller to set the color of the model
/// Call the Function [ModelViewerColorController.changeColor(colorString)]
/// to set a color by an given colorString
ModelViewerColorController colorController;

/// Enables the auto-rotation of the model.
final bool autoRotate;

Expand All @@ -85,6 +102,25 @@ class ModelViewer extends StatefulWidget {
/// via AR Quick Look.
final String iosSrc;

/// Invoked once when the model viewer is created.
final VoidCallback onModelViewCreated;

/// Invoked when the model viewer has finished loading the url.
final VoidCallback onModelViewStarted;

/// Invoked when the model viewer has finished loading the url.
///
/// Please note: This function is invoked when the url has finished loading,
/// but it doesn't represents the finished loading process of the model visibility.
final VoidCallback onModelViewFinished;

/// Invoked when the model viewer has loaded the model and the model is visibile.
/// See: https://modelviewer.dev/docs/#entrydocs-loading-events-modelVisibility
final VoidCallback onModelIsVisisble;

/// Invoked when the model viewer has failed to load the resource.
final ValueChanged<String> onModelViewError;

@override
State<ModelViewer> createState() => _ModelViewerState();
}
Expand All @@ -98,6 +134,10 @@ class _ModelViewerState extends State<ModelViewer> {
@override
void initState() {
super.initState();
var _colorController = widget.colorController;
if (_colorController != null) {
_colorController.changeColor = _changeColor;
}
_initProxy();
}

Expand All @@ -121,14 +161,29 @@ class _ModelViewerState extends State<ModelViewer> {
return WebView(
initialUrl: null,
javascriptMode: JavascriptMode.unrestricted,
javascriptChannels: Set.from({
JavascriptChannel(
name: 'messageIsVisibile',
onMessageReceived: (JavascriptMessage message) {
if (widget.onModelIsVisisble != null) {
if (message.message == 'true') {
widget.onModelIsVisisble();
}
}
}),
}),
initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow,
onWebViewCreated: (final WebViewController webViewController) async {
_controller.complete(webViewController);
final host = _proxy.address.address;
final port = _proxy.port;
final url = "http://$host:$port/";
print('>>>> ModelViewer initializing... <$url>'); // DEBUG
await webViewController.loadUrl(url);
await webViewController.loadUrl(url).then((value) {
if (widget.onModelViewCreated != null) {
widget.onModelViewCreated();
}
});
},
navigationDelegate: (final NavigationRequest navigation) async {
//print('>>>> ModelViewer wants to load: <${navigation.url}>'); // DEBUG
Expand Down Expand Up @@ -158,18 +213,41 @@ class _ModelViewerState extends State<ModelViewer> {
return NavigationDecision.prevent;
},
onPageStarted: (final String url) {
if (widget.onModelViewStarted != null) {
widget.onModelViewStarted();
}
//print('>>>> ModelViewer began loading: <$url>'); // DEBUG
},
onPageFinished: (final String url) {
if (widget.onModelViewFinished != null) {
widget.onModelViewFinished();
}
//print('>>>> ModelViewer finished loading: <$url>'); // DEBUG
},
onWebResourceError: (final WebResourceError error) {
if (widget.onModelViewError != null) {
widget.onModelViewError(error.description);
}

print(
'>>>> ModelViewer failed to load: ${error.description} (${error.errorType} ${error.errorCode})'); // DEBUG
},
);
}

Future<String> _changeColor(String color) async {
var c = Completer<String>();
var webviewcontroller = await _controller.future;
await webviewcontroller
.evaluateJavascript('changeColor("$color")')
.then((result) {
c.complete(result);
}).catchError((onError) {
c.completeError(onError.toString());
});
return c.future;
}

String _buildHTML(final String htmlTemplate) {
return HTMLBuilder.build(
htmlTemplate: htmlTemplate,
Expand All @@ -183,6 +261,7 @@ class _ModelViewerState extends State<ModelViewer> {
autoRotateDelay: widget.autoRotateDelay,
autoPlay: widget.autoPlay,
cameraControls: widget.cameraControls,
enableColorChange: widget.enableColorChange,
iosSrc: widget.iosSrc,
);
}
Expand Down